问:
Why are Rails scopes preferable, if messy controllers are faster?
I've been trying to chain Arel queries using scopes, instead of just using some long-winded logic I wrote in the controller. But the scopes are slower than just getting all the records and then sifting through them with some logic. I'm wondering, then, why scopes are better.

Here's what I'm doing:

a question has many answers

an answer belongs to one question

a question has a "question_type" column that I use to sort it

First, the scopes way...

in question.rb:

```<code>scope :answered, joins(:answers).order('answers.created_at desc')
scope :dogs, where(:question_type => "dogs")
scope :cats, where(:question_type => "cats")
scope :mermaids, where(:question_type => "mermaids")
</code>```

in questions_controller.rb:

```<code>@dogs_recently_answered = Question.answered.dogs.uniq[0..9]
@cats_recently_answered = Question.answered.cats.uniq[0..9]
@mermaids_recently_answered = Question.answered.mermaids.uniq[0..9]
</code>```

Then in the view, I cycle through those instance variables (which are now arrays containing at most 10 elements) and display the results.

Here are the times it takes to load the page (five different times):

Completed 200 OK in 535ms (Views: 189.6ms | ActiveRecord: 46.2ms)

Completed 200 OK in 573ms (Views: 186.0ms | ActiveRecord: 46.3ms)

Completed 200 OK in 577ms (Views: 189.0ms | ActiveRecord: 45.6ms)

Completed 200 OK in 532ms (Views: 182.9ms | ActiveRecord: 46.1ms)

Completed 200 OK in 577ms (Views: 186.7ms | ActiveRecord: 46.9ms)

Now, the messy controller way...

```<code>@answers = Answer.order("created_at desc")
@all_answered = []
@answers.each {|answer| @all_answered << answer.question}
@recently_answered = @all_answered.uniq
@dogs_all_answered = []
@cats_all_answered = []
@mermaids_all_answered = []
@recently_answered.each do |q|
  if q.question_type == "dogs"
    @dogs_all_answered << q
    @dogs_recently_answered = @dogs_all_answered[0..9]
  elsif q.question_type == "cats"
    @cats_all_answered << q
    @cats_recently_answered = @cats_all_answered[0..9]
  elsif q.question_type == "mermaids"
    @mermaids_all_answered << q
    @mermaids_recently_answered = @mermaids_all_answered[0..9]
  end
end
</code>```

And here are the times it takes to load the page now (five different times):

Completed 200 OK in 475ms (Views: 196.5ms | ActiveRecord: 34.5ms)

Completed 200 OK in 480ms (Views: 200.4ms | ActiveRecord: 36.4ms)

Completed 200 OK in 434ms (Views: 198.2ms | ActiveRecord: 35.8ms)

Completed 200 OK in 475ms (Views: 194.2ms | ActiveRecord: 36.4ms)

Completed 200 OK in 475ms (Views: 195.0ms | ActiveRecord: 35.4ms)

So...

Aside from readability, what's to be won by honing the query with a scope? Does it eventually become quicker when there are more records?

答:
I think the reason the scopes are slower in this case is because they result in 3 separate database queries, whereas the other approach uses the knowledge that all three results can be satisfied by the single query you use.

Assuming that is the case, it is not surprising the scopes are doing 3 separate queries since the system doesn't know when you call the first one that you're going to call the others right afterwards. Maybe there is an optimisation strategy that would be sensible for this scenario, but I don't know that ActiveRecord implements it.

Anyway, this is one disadvantage of the scope in this particular case. I like scopes because they are clean/clear, flexible and encapsulated a named abstraction for a query. AFAICT, in many scenarios they are not appreciably slower than the equivalent direct query.

Body:
I've been trying to chain Arel queries using scopes, instead of just using some long-winded logic I wrote in the controller. But the scopes are slower than just getting all the records and then sifting through them with some logic. I'm wondering, then, why scopes are better.

Here's what I'm doing:

a question has many answers

an answer belongs to one question

a question has a "question_type" column that I use to sort it

First, the scopes way...

in question.rb:

scope :answered, joins(:answers).order('answers.created_at desc')
scope :dogs, where(:question_type => "dogs")
scope :cats, where(:question_type => "cats")
scope :mermaids, where(:question_type => "mermaids")

in questions_controller.rb:

@dogs_recently_answered = Question.answered.dogs.uniq[0..9]
@cats_recently_answered = Question.answered.cats.uniq[0..9]
@mermaids_recently_answered = Question.answered.mermaids.uniq[0..9]

Then in the view, I cycle through those instance variables (which are now arrays containing at most 10 elements) and display the results.

Here are the times it takes to load the page (five different times):

Completed 200 OK in 535ms (Views: 189.6ms | ActiveRecord: 46.2ms)

Completed 200 OK in 573ms (Views: 186.0ms | ActiveRecord: 46.3ms)

Completed 200 OK in 577ms (Views: 189.0ms | ActiveRecord: 45.6ms)

Completed 200 OK in 532ms (Views: 182.9ms | ActiveRecord: 46.1ms)

Completed 200 OK in 577ms (Views: 186.7ms | ActiveRecord: 46.9ms)

Now, the messy controller way...

@answers = Answer.order("created_at desc")
@all_answered = []
@answers.each {|answer| @all_answered << answer.question}
@recently_answered = @all_answered.uniq
@dogs_all_answered = []
@cats_all_answered = []
@mermaids_all_answered = []
@recently_answered.each do |q|
  if q.question_type == "dogs"
    @dogs_all_answered << q
    @dogs_recently_answered = @dogs_all_answered[0..9]
  elsif q.question_type == "cats"
    @cats_all_answered << q
    @cats_recently_answered = @cats_all_answered[0..9]
  elsif q.question_type == "mermaids"
    @mermaids_all_answered << q
    @mermaids_recently_answered = @mermaids_all_answered[0..9]
  end
end

And here are the times it takes to load the page now (five different times):

Completed 200 OK in 475ms (Views: 196.5ms | ActiveRecord: 34.5ms)

Completed 200 OK in 480ms (Views: 200.4ms | ActiveRecord: 36.4ms)

Completed 200 OK in 434ms (Views: 198.2ms | ActiveRecord: 35.8ms)

Completed 200 OK in 475ms (Views: 194.2ms | ActiveRecord: 36.4ms)

Completed 200 OK in 475ms (Views: 195.0ms | ActiveRecord: 35.4ms)

So...

Aside from readability, what's to be won by honing the query with a scope? Does it eventually become quicker when there are more records?


来源: stackexchange

问:
Adapt a template tags method
I am trying to use a template tags in a template.

```<code>from django import template
from datetime import datetime
from django.template.defaultfilters import date as datefilter
from django.utils import translation

register = template.Library()

DATE_FORMATS = {
    "en":  "l, F j, Y",
    "fr": "l, j F Y"
}

DEFAULT_LANG = 'fr'

@register.simple_tag(name="localdate")
def localdate(lang=DEFAULT_LANG):
    fmt = DATE_FORMATS.get(lang, DATE_FORMATS[DEFAULT_LANG])
    now = datetime.now()
    with translation.override(lang):
        return datefilter(now, fmt)
</code>```

I tried to use {{ localdate : 'en'}}, but everything went wrong. Is there an easy way to adapt tags so that it works? In fact, the file is called date_tags.py. So in the template I load the file with {%load date_tags %}.

Thanks in advance!

答:
It looks like you're incorrectly using the template tag.

Try using this:

```<code>{% localdate "en" %}
</code>```

For more information, check out the docs here: Django Simple Tag

ContentLicense: CC BY-SA 3.0

Title: Adapt a template tags method

Body:
I am trying to use a template tags in a template.

from django import template
from datetime import datetime
from django.template.defaultfilters import date as datefilter
from django.utils import translation

register = template.Library()

DATE_FORMATS = {
    "en":  "l, F j, Y",
    "fr": "l, j F Y"
}

DEFAULT_LANG = 'fr'

@register.simple_tag(name="localdate")
def localdate(lang=DEFAULT_LANG):
    fmt = DATE_FORMATS.get(lang, DATE_FORMATS[DEFAULT_LANG])
    now = datetime.now()
    with translation.override(lang):
        return datefilter(now, fmt)

I tried to use {{ localdate : 'en'}}, but everything went wrong. Is there an easy way to adapt tags so that it works? In fact, the file is called date_tags.py. So in the template I load the file with {%load date_tags %}.

Thanks in advance!

Body:
It looks like you're incorrectly using the template tag.

Try using this:

{% localdate "en" %}

For more information, check out the docs here: Django Simple Tag


问:
Open fragment from Fragment on button click
I am having trouble opening a fragment from within another fragment on the click of a button. Everything seems to make sense (to me) and I have tried playing about with my code (changing the layouts, replacing fragments etc) but nothing is working.

Here is my RoleFragment.java (The fragment which contains the button)

```<code>public class RolesFragment extends Fragment implements View.OnClickListener {

GridView gridView;
ArrayList<Players> playersList;
MyAdapter adapter;

@Override
public View onCreateView(LayoutInflater inflater,ViewGroup container,
                         Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.fragment_viewroles, container, false);

    gridView = (GridView) view.findViewById(R.id.gv_players);
    Button nightround = (Button) view.findViewById(R.id.buttonNightRound);

    nightround.setOnClickListener(this);

    DatabaseHelper databaseHelper = new DatabaseHelper(getActivity());
    playersList = new ArrayList<Players>();

    playersList = databaseHelper.getPlayers();
    adapter = new MyAdapter(getActivity(), playersList);
    gridView.setAdapter(adapter);

    return view;
}

@Override
public void onClick(View v) {
    Fragment fragment = null;
    switch (v.getId()) {
        case R.id.buttonNightRound:
            fragment = new NightRound();
            replaceFragment(fragment);
            break;

    }

}

public void replaceFragment(Fragment someFragment) {
    FragmentTransaction transaction = getFragmentManager().beginTransaction();
    transaction.replace(R.id.fragment_container, someFragment);
    transaction.addToBackStack(null);
    transaction.commit();
}

 }
</code>```

And this is my fragment_viewroles.xml file.

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.tuss.mafia.GameActivity" >

<Button
    android:id="@+id/buttonNightRound"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Night Round"
    android:onClick="FragmentNightRoundClick"
    android:clickable="true"
    android:layout_weight="2"/>

<GridView
    android:id="@+id/gv_players"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:numColumns="auto_fit"
    android:stretchMode="columnWidth"
    android:columnWidth="150dp"
    android:horizontalSpacing="10dp"
    android:verticalSpacing="10dp"
    android:gravity="center"
    android:layout_below="@id/buttonNightRound">
</GridView>

</RelativeLayout>
</code>```

The trouble is, when I click the button nothing happens.

答:
Try something like the following: </p>

```<code>     Fragment fragment = OtherFragment.newInstance();
            android.support.v4.app.FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
            transaction.replace(R.id.container_layout, fragment, "OtherFragment");// give your fragment container id in first parameter
            transaction.addToBackStack(null);  // if written, this transaction will be added to backstack
            transaction.commit();
</code>```

Body:
I am having trouble opening a fragment from within another fragment on the click of a button. Everything seems to make sense (to me) and I have tried playing about with my code (changing the layouts, replacing fragments etc) but nothing is working.

Here is my RoleFragment.java (The fragment which contains the button)

public class RolesFragment extends Fragment implements View.OnClickListener {

GridView gridView;
ArrayList<Players> playersList;
MyAdapter adapter;

@Override
public View onCreateView(LayoutInflater inflater,ViewGroup container,
                         Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.fragment_viewroles, container, false);

    gridView = (GridView) view.findViewById(R.id.gv_players);
    Button nightround = (Button) view.findViewById(R.id.buttonNightRound);

    nightround.setOnClickListener(this);

    DatabaseHelper databaseHelper = new DatabaseHelper(getActivity());
    playersList = new ArrayList<Players>();

    playersList = databaseHelper.getPlayers();
    adapter = new MyAdapter(getActivity(), playersList);
    gridView.setAdapter(adapter);

    return view;
}

@Override
public void onClick(View v) {
    Fragment fragment = null;
    switch (v.getId()) {
        case R.id.buttonNightRound:
            fragment = new NightRound();
            replaceFragment(fragment);
            break;

    }

}

public void replaceFragment(Fragment someFragment) {
    FragmentTransaction transaction = getFragmentManager().beginTransaction();
    transaction.replace(R.id.fragment_container, someFragment);
    transaction.addToBackStack(null);
    transaction.commit();
}

 }

And this is my fragment_viewroles.xml file.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.tuss.mafia.GameActivity" >

<Button
    android:id="@+id/buttonNightRound"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Night Round"
    android:onClick="FragmentNightRoundClick"
    android:clickable="true"
    android:layout_weight="2"/>

<GridView
    android:id="@+id/gv_players"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:numColumns="auto_fit"
    android:stretchMode="columnWidth"
    android:columnWidth="150dp"
    android:horizontalSpacing="10dp"
    android:verticalSpacing="10dp"
    android:gravity="center"
    android:layout_below="@id/buttonNightRound">
</GridView>

</RelativeLayout>

The trouble is, when I click the button nothing happens.

Body:
Try something like the following:

     Fragment fragment = OtherFragment.newInstance();
            android.support.v4.app.FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
            transaction.replace(R.id.container_layout, fragment, "OtherFragment");// give your fragment container id in first parameter
            transaction.addToBackStack(null);  // if written, this transaction will be added to backstack
            transaction.commit();


问:
Can't open saved plot until I restart RStudio
When I save a plot like this:

```<code>png("test.png")
plot(1:10)
dev.off()
</code>```

I'm sometimes unable to open the file until I restart RStudio.  Windows 10 gives me the error message:

"It looks like you don't have permission to view this file.  Check the
  permissions and try again."

How can I open the file in another application without restarting RStudio and losing my environment?

答:
You may have a graphics device open from a previous command (the code above is not causing the problem, but is where it manifests).  RStudio guidance suggests:

To reset your graphics device, call the following code from the
  console:

dev.off()

Note:

This will delete your current plots in the RStudio Plots Pane. If you
  have multiple graphics devices open, repeat this command until the
  output displays null device.

Run dev.off() repeatedly until it returns "null device."

Body:
When I save a plot like this:

png("test.png")
plot(1:10)
dev.off()

I'm sometimes unable to open the file until I restart RStudio.  Windows 10 gives me the error message:

"It looks like you don't have permission to view this file.  Check the
  permissions and try again."

How can I open the file in another application without restarting RStudio and losing my environment?


问:
Setting Corner Radius on UIImageView not working
I'm at a bit of a loss. I've used the layer property of UIView to round the corners of multiple elements in my app. However, this one UIImageView is simply not complying. Not sure what I am missing.

The UIImageView (called previewImage) is contained in a Table View Cell. I've tried setting the cornerRadius property multiple location (in the cell itself and in the controller that creates the cell) to no avail.

```<code>static NSString *CellIdentifier = @"MyTableViewCell";

MyTableViewCell *cell = (MyTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:CellIdentifier owner:self options:nil];
    cell = [topLevelObjects objectAtIndex:0];
    cell.previewImage.layer.cornerRadius = 20; //Made it 20 to make sure it's obvious.
}
</code>```

Is there something about the way cells are loaded that I'm missing?

答:
I believe you need to set:</p>

```<code>cell.previewImage.layer.masksToBounds = YES;
cell.previewImage.layer.opaque = NO;
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm at a bit of a loss. I've used the layer property of UIView to round the corners of multiple elements in my app. However, this one UIImageView is simply not complying. Not sure what I am missing.

The UIImageView (called previewImage) is contained in a Table View Cell. I've tried setting the cornerRadius property multiple location (in the cell itself and in the controller that creates the cell) to no avail.

static NSString *CellIdentifier = @"MyTableViewCell";

MyTableViewCell *cell = (MyTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:CellIdentifier owner:self options:nil];
    cell = [topLevelObjects objectAtIndex:0];
    cell.previewImage.layer.cornerRadius = 20; //Made it 20 to make sure it's obvious.
}

Is there something about the way cells are loaded that I'm missing?

Body:
I believe you need to set:

cell.previewImage.layer.masksToBounds = YES;
cell.previewImage.layer.opaque = NO;


问:
Define what makes a code section in rstudio
Rstudio changed how a code section is defined. In version 0.99.902 code sections had to have some text behind the hash symbol. But now in version 1.0.136 if there are 5 hashes in a row it will define a new section.

Is there anyway to make it go back to the old way of defining sections? It isn't a big deal except I would mark my sections with hashes above and below the name and now it is creating 3x as many sections.

Old version:

New version:

答:
Unfortunately, this behavior has changed between RStudio v0.98.1091, v0.99.903 and the current release v1.0.136.

In RStudio v0.98.1091, 'empty' headers such as ##### were recognized as section headers.

This behavior was briefly changed with v0.99.903, such that some initial text was required for these to be recognized as section headers. A number of users were unhappy as this effectively broke code folding for users who were explicitly using standalone ##### blocks to create sections.

Because of that, the behavior was reverted in RStudio v1.0.136, and so now standalone ##### blocks are again recognized as section headers.


问:
Perform object recognition based on colour
I have captured each frame of a video .Then I have used background subtraction to eliminate the background .Now I have the people with their bounding boxes.I have to compare the colour features of this person with the features of the same person in another video. The person will be wearing the same dress in every video.
I am developing this in opencv 2.4 and python 2.7

Here it the background subtraction code I have used:

```<code>import numpy as np
import cv2
cap = cv2.VideoCapture('test.mp4')
fgbg = cv2.BackgroundSubtractorMOG()
j=0
count = int(cap.get(cv2.cv.CV_CAP_PROP_FRAME_COUNT))
while j<count:
    ret, frame = cap.read()
    cmask = fgbg.apply(frame)
    fgmask = cmask.copy()
    floodfill =cmask.copy()

    (cnts, _) = cv2.findContours(cmask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    cnts = sorted(cnts, key = cv2.contourArea, reverse = True)
    if(len(cnts)!=0):
        h, w = floodfill.shape[:2]
        mask = np.zeros((h+2, w+2), np.uint8)
        cv2.floodFill(floodfill, mask, (0,0), 255)
        floodfill_inv = cv2.bitwise_not(floodfill)
        fgmask=fgmask|floodfill_inv

    # screenCnt = None
    print "K="+str(j)
    j+=1
    for cnt in cnts:
        x,y,w,h = cv2.boundingRect(cnt)
        cv2.rectangle(fgmask,(x,y),(x+w,y+h),255,4)
    if(len(cnts)!=0):
        cv2.imshow('frame',fgmask)

    k = cv2.waitKey(30) & 0xff

    if k == 27:
        break
cap.release()
cv2.destroyAllWindows()
</code>```

Is there any method for comparing objects based on the colour?

I have not used face recognition because I don't have pictures of the people in the video

Any help would be appreciated

答:
What you want is Swain and Ballard's Color Indexing technique.

Basically, you create a color histogram to represent the object/person. Using the information in the histogram, you can create a probability mass function of another image that represents the probability of an object being at a certain point.
Here's a python/opencv tutorial that explains how to do the back projection.
The peak of the probability mass function is the most likely location of your object/person.

You probably may not need to do the back projection if you are just trying to compare two known objects.  Here's a previous question about ways to compare color histograms that will give you some options.

If your video has significant lighting changes, you probably won't get the results you need with this technique alone, but someone else came up with a way to introduce color constancy to the method. Instead of using a histogram of colors, you use a histogram of color ratios.

Body:
I have captured each frame of a video .Then I have used background subtraction to eliminate the background .Now I have the people with their bounding boxes.I have to compare the colour features of this person with the features of the same person in another video. The person will be wearing the same dress in every video.
I am developing this in opencv 2.4 and python 2.7

Here it the background subtraction code I have used:

import numpy as np
import cv2
cap = cv2.VideoCapture('test.mp4')
fgbg = cv2.BackgroundSubtractorMOG()
j=0
count = int(cap.get(cv2.cv.CV_CAP_PROP_FRAME_COUNT))
while j<count:
    ret, frame = cap.read()
    cmask = fgbg.apply(frame)
    fgmask = cmask.copy()
    floodfill =cmask.copy()

    (cnts, _) = cv2.findContours(cmask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    cnts = sorted(cnts, key = cv2.contourArea, reverse = True)
    if(len(cnts)!=0):
        h, w = floodfill.shape[:2]
        mask = np.zeros((h+2, w+2), np.uint8)
        cv2.floodFill(floodfill, mask, (0,0), 255)
        floodfill_inv = cv2.bitwise_not(floodfill)
        fgmask=fgmask|floodfill_inv

    # screenCnt = None
    print "K="+str(j)
    j+=1
    for cnt in cnts:
        x,y,w,h = cv2.boundingRect(cnt)
        cv2.rectangle(fgmask,(x,y),(x+w,y+h),255,4)
    if(len(cnts)!=0):
        cv2.imshow('frame',fgmask)

    k = cv2.waitKey(30) & 0xff

    if k == 27:
        break
cap.release()
cv2.destroyAllWindows()

Is there any method for comparing objects based on the colour?

I have not used face recognition because I don't have pictures of the people in the video

Any help would be appreciated


问:
Adding constraints to a ViewController secondary UIView
I have a Storyboard setup with a dialog box that utilizes a secondary UIView (yellow in the screenshot.) This is done by dragging a UIView from the objects library up in between First Responder and Exit on the Storyboard.

I can't figure out how to add basic constraints to this secondary UIView relative to the superview. Right click and dragging won't let me apply constraints. Is this possible? Do I need to handle all Autolayout / constraints programmatically?

I just need to add constraints from leading / trailing. Height will be fixed, but may adjust accordingly depending on screen size.

答:
This has been figured out. You can not use right-click & drag constraints in IB on these views. Why?? Because they're not a part of the view hierarchy yet! (silly me..)

In my above example with the yellow secondary view, here's how you would apply auto layout to it using VFL (Visual Format Language).

In ViewDidLoad, you first want to turn off the views auto resizing mask:

```<code>self.yellowSecondaryView.translatesAutoresizingMaskIntoConstraints = false
</code>```

Now find where you're adding the subview. Let's say you use a button action to trigger it... Inside that action, you first add the view (1), and then the constraints (2):

```<code>// 1
view.addSubview(yellowSecondaryView)

// Create a string representation of the view to use it with VFL.
let viewsDictionary: [String: UIView] = ["yellowSecondaryView": yellowSecondaryView]

//2
view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-50-[yellowSecondaryView]-50-|", options: [], metrics: nil, views: viewsDictionary))  // Width of yellow view will be full width, minus 50 points from the LEFT and the RIGHT of the superview (|)
view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[yellowSecondaryView(250)]", options: [], metrics: nil, views: viewsDictionary)) // Set a static height of 250 for the yellow view

view.addConstraint(NSLayoutConstraint(item: yellowSecondaryView, attribute: .centerY, relatedBy: NSLayoutRelation(rawValue: 0)!, toItem: view, attribute: .centerY, multiplier: 1, constant: 0))  // Center the view vertically in the superview. (credit to @rdelmar in this thread: http://stackoverflow.com/questions/21494039/using-autolayout-in-ib-how-do-i-position-a-uiview-in-the-center-of-the-screen-pr/21494707#21494707)
</code>```

Hope this helps somebody create a much more manageable and organized storyboard! :)

Body:
This has been figured out. You can not use right-click & drag constraints in IB on these views. Why?? Because they're not a part of the view hierarchy yet! (silly me..)

In my above example with the yellow secondary view, here's how you would apply auto layout to it using VFL (Visual Format Language).

In ViewDidLoad, you first want to turn off the views auto resizing mask:

self.yellowSecondaryView.translatesAutoresizingMaskIntoConstraints = false

Now find where you're adding the subview. Let's say you use a button action to trigger it... Inside that action, you first add the view (1), and then the constraints (2):

// 1
view.addSubview(yellowSecondaryView)

// Create a string representation of the view to use it with VFL.
let viewsDictionary: [String: UIView] = ["yellowSecondaryView": yellowSecondaryView]

//2
view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-50-[yellowSecondaryView]-50-|", options: [], metrics: nil, views: viewsDictionary))  // Width of yellow view will be full width, minus 50 points from the LEFT and the RIGHT of the superview (|)
view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[yellowSecondaryView(250)]", options: [], metrics: nil, views: viewsDictionary)) // Set a static height of 250 for the yellow view

view.addConstraint(NSLayoutConstraint(item: yellowSecondaryView, attribute: .centerY, relatedBy: NSLayoutRelation(rawValue: 0)!, toItem: view, attribute: .centerY, multiplier: 1, constant: 0))  // Center the view vertically in the superview. (credit to @rdelmar in this thread: http://stackoverflow.com/questions/21494039/using-autolayout-in-ib-how-do-i-position-a-uiview-in-the-center-of-the-screen-pr/21494707#21494707)

Hope this helps somebody create a much more manageable and organized storyboard! :)


问:
Any faster, simpler alternative to php preg_match
I am using cakephp 1.3 and I have textarea where users submit articles. On submit, I want to look into the article for certain key words and and add respective tags to the article.

I was thinking of preg_match, But preg_match pattern has to be string. So I would have to loop through an array(big).

Is there a easier way to plug in the keywords array for the pattern.

I appreciate all your help.

Thanks.

答:
If you want to look for multiple words from an array, then combine said array into an regular expression:

```<code> $regex_array = implode("|", array_map("preg_escape", $array));
 preg_match_all("/($regex_array)/", $src, $tags);
</code>```

This converts your array into /(word|word|word|word|word|...)/. The arrray_map and preg_escape part is optional, only needed if the $array might contain special characters.

Avoid strpos and loops for this case. preg_match is faster for searching after alternatives.

Body:
If you want to look for multiple words from an array, then combine said array into an regular expression:

 $regex_array = implode("|", array_map("preg_escape", $array));
 preg_match_all("/($regex_array)/", $src, $tags);

This converts your array into /(word|word|word|word|word|...)/. The arrray_map and preg_escape part is optional, only needed if the $array might contain special characters.

Avoid strpos and loops for this case. preg_match is faster for searching after alternatives.


问:
How can I synchronize closures?
How can I synchronize closures?

I have this code:

```<code>    private func getWeather(parameters: [String : Any],  failure: ((String) -> Void)? = nil ,completion: (() -> Void)? = nil) {

        for _ in 0...10 {

            RequestManager.sharedInstance.request(url: baseURL, parameters: parameters, completion:  { (result) in
                if JSON.parse(result)["name"].string == nil {
                    failure?("Something went wrong. Please, try again later")
                } else {
                    let weatherModel: WeatherModel = WeatherModel(json: JSON.parse(result))
                }
            })
        }
        completion?()

    }
</code>```

In my code, completion?() will call, not when all requests will ended
And I need call completion?() when all requests will ended. Ho can I do it?

答:
Since the currently accepted answer isn't correct, here is a version that properly uses a DispatchGroup.

```<code>private func getWeather(parameters: [String : Any],  failure: ((String) -> Void)? = nil ,completion: (() -> Void)? = nil) {
    let dispatchGroup = DispatchGroup()
    for _ in 0...10 {
        dispatchGroup.enter()
        RequestManager.sharedInstance.request(url: baseURL, parameters: parameters) { result in
            if JSON.parse(result)["name"].string == nil {
                failure?("Something went wrong. Please, try again later")
            } else {
                let weatherModel: WeatherModel = WeatherModel(json: JSON.parse(result))
            }
            dispatchGroup.leave()
        }
    }

    dispatchGroup.notify(queue: DispatchQueue.main) {
        completion?()
    }
}
</code>```

Title: How can I synchronize closures?

Body:
How can I synchronize closures?

I have this code:

    private func getWeather(parameters: [String : Any],  failure: ((String) -> Void)? = nil ,completion: (() -> Void)? = nil) {

        for _ in 0...10 {

            RequestManager.sharedInstance.request(url: baseURL, parameters: parameters, completion:  { (result) in
                if JSON.parse(result)["name"].string == nil {
                    failure?("Something went wrong. Please, try again later")
                } else {
                    let weatherModel: WeatherModel = WeatherModel(json: JSON.parse(result))
                }
            })
        }
        completion?()

    }

In my code, completion?() will call, not when all requests will ended
And I need call completion?() when all requests will ended. Ho can I do it?

Body:
Since the currently accepted answer isn't correct, here is a version that properly uses a DispatchGroup.

private func getWeather(parameters: [String : Any],  failure: ((String) -> Void)? = nil ,completion: (() -> Void)? = nil) {
    let dispatchGroup = DispatchGroup()
    for _ in 0...10 {
        dispatchGroup.enter()
        RequestManager.sharedInstance.request(url: baseURL, parameters: parameters) { result in
            if JSON.parse(result)["name"].string == nil {
                failure?("Something went wrong. Please, try again later")
            } else {
                let weatherModel: WeatherModel = WeatherModel(json: JSON.parse(result))
            }
            dispatchGroup.leave()
        }
    }

    dispatchGroup.notify(queue: DispatchQueue.main) {
        completion?()
    }
}


问:
Why does nginx default to my proxypass?
I am using nginx as a proxy server to serve two web apps on a single server that are running on separate ports (for local development purposes).  Below is the full nginx.conf file:

```<code>user www-data;
worker_processes auto;
pid /run/nginx.pid;

events {
    worker_connections 768;
    # multi_accept on;
}

http {

    ##
    # Basic Settings
    ##

    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;
    # server_tokens off;

    # server_names_hash_bucket_size 64;
    # server_name_in_redirect off;

    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    ##
    # SSL Settings
    ##

    ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE
    ssl_prefer_server_ciphers on;

    ##
    # Logging Settings
    ##

    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;

    ##
    # Gzip Settings
    ##

    gzip on;
    gzip_disable "msie6";

    # gzip_vary on;
    # gzip_proxied any;
    # gzip_comp_level 6;
    # gzip_buffers 16 8k;
    # gzip_http_version 1.1;
    # gzip_types text/plain text/css application/json  application/javascript text/xml application/xml application/xml+rss text/javascript;

    ##
    # Virtual Host Configs
    ##

    server {
      server_name news.mysite;
      location / {
        proxy_pass http://localhost:3001;
      }
    }

    server {
      server_name blog.mysite;
      location / {
        proxy_pass http://localhost:3002;
      }
    }

#   include /etc/nginx/conf.d/*.conf;
#   include /etc/nginx/sites-enabled/*;
}
</code>```

When accessing the subdomains from the browser I see the expected content based on the web apps that are running.  However, when I access the main domain through the browser (http://mysite), it displays the content from  the first proxypass (news.mysite @ localhost:3001).  I would have expected one of the following two scenarios:

Serve content from the default directory @ /var/www/html

The typical "This site can’t be reached" error in the browser.

Why is nginx proxying the first proxypass it finds by default and how can I change it?

答:
The first server that nginx encounters for a socket will be considered the default unless you create another one that you explicitly mark as the default.

So for your case, you would want to add an additional server block as a catch all:

```<code>server {
   listen 80 default_server;
   root /var/www/html;
}
</code>```

Title: Why does nginx default to my proxypass?

Body:
I am using nginx as a proxy server to serve two web apps on a single server that are running on separate ports (for local development purposes).  Below is the full nginx.conf file:

user www-data;
worker_processes auto;
pid /run/nginx.pid;

events {
    worker_connections 768;
    # multi_accept on;
}

http {

    ##
    # Basic Settings
    ##

    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;
    # server_tokens off;

    # server_names_hash_bucket_size 64;
    # server_name_in_redirect off;

    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    ##
    # SSL Settings
    ##

    ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE
    ssl_prefer_server_ciphers on;

    ##
    # Logging Settings
    ##

    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;

    ##
    # Gzip Settings
    ##

    gzip on;
    gzip_disable "msie6";

    # gzip_vary on;
    # gzip_proxied any;
    # gzip_comp_level 6;
    # gzip_buffers 16 8k;
    # gzip_http_version 1.1;
    # gzip_types text/plain text/css application/json  application/javascript text/xml application/xml application/xml+rss text/javascript;

    ##
    # Virtual Host Configs
    ##

    server {
      server_name news.mysite;
      location / {
        proxy_pass http://localhost:3001;
      }
    }

    server {
      server_name blog.mysite;
      location / {
        proxy_pass http://localhost:3002;
      }
    }

#   include /etc/nginx/conf.d/*.conf;
#   include /etc/nginx/sites-enabled/*;
}

When accessing the subdomains from the browser I see the expected content based on the web apps that are running.  However, when I access the main domain through the browser (http://mysite), it displays the content from  the first proxypass (news.mysite @ localhost:3001).  I would have expected one of the following two scenarios:

Serve content from the default directory @ /var/www/html

The typical "This site can’t be reached" error in the browser.

Why is nginx proxying the first proxypass it finds by default and how can I change it?

Body:
The first server that nginx encounters for a socket will be considered the default unless you create another one that you explicitly mark as the default.

So for your case, you would want to add an additional server block as a catch all:

server {
   listen 80 default_server;
   root /var/www/html;
}


答:
There some problems here.
First, you have to add a container with the id R.id.fragment_container inside your fragment like FrameLayout
which will store your new fragment.

If your want to open a fragment as a new screen, you have to put it inside a new activity. Fragments are piece of screens and should not be used without activities or view pagers.

Have a look at the Android deverlopers page: http://developer.android.com/training/basics/fragments/communicating.html#DefineInterface

Basically, you define an interface in your Fragment A, and let your Activity implement that Interface. Now you can call the interface method in your Fragment, and your Activity will receive the event. Now in your activity, you can call your second Fragment to update the textview with the received value

```<code>// You Activity implements your interface
public class YourActivity implements FragmentA.TextClicked{
    @Override
    public void sendText(String text){
        // Get Fragment B
        FraB frag = (FragB)
            getSupportFragmentManager().findFragmentById(R.id.fragment_b);
        frag.updateText(text);
    }
}

// Fragment A defines an Interface, and calls the method when needed
public class FragA extends Fragment{

    TextClicked mCallback;

    public interface TextClicked{
        public void sendText(String text);
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

        // This makes sure that the container activity has implemented
        // the callback interface. If not, it throws an exception
        try {
            mCallback = (TextClicked) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                + " must implement TextClicked");
        }
    }

    public void someMethod(){
        mCallback.sendText("YOUR TEXT");
    }

    @Override
    public void onDetach() {
        mCallback = null; // => avoid leaking, thanks @Deepscorn
        super.onDetach();
    }
}

// Fragment B has a public method to do something with the text
public class FragB extends Fragment{

    public void updateText(String text){
        // Here you have it
    }
}
</code>```

Title: Open fragment from Fragment on button click

Body:
There some problems here.
First, you have to add a container with the id R.id.fragment_container inside your fragment like FrameLayout
which will store your new fragment.

If your want to open a fragment as a new screen, you have to put it inside a new activity. Fragments are piece of screens and should not be used without activities or view pagers.

Have a look at the Android deverlopers page: http://developer.android.com/training/basics/fragments/communicating.html#DefineInterface

Basically, you define an interface in your Fragment A, and let your Activity implement that Interface. Now you can call the interface method in your Fragment, and your Activity will receive the event. Now in your activity, you can call your second Fragment to update the textview with the received value

// You Activity implements your interface
public class YourActivity implements FragmentA.TextClicked{
    @Override
    public void sendText(String text){
        // Get Fragment B
        FraB frag = (FragB)
            getSupportFragmentManager().findFragmentById(R.id.fragment_b);
        frag.updateText(text);
    }
}

// Fragment A defines an Interface, and calls the method when needed
public class FragA extends Fragment{

    TextClicked mCallback;

    public interface TextClicked{
        public void sendText(String text);
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

        // This makes sure that the container activity has implemented
        // the callback interface. If not, it throws an exception
        try {
            mCallback = (TextClicked) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                + " must implement TextClicked");
        }
    }

    public void someMethod(){
        mCallback.sendText("YOUR TEXT");
    }

    @Override
    public void onDetach() {
        mCallback = null; // => avoid leaking, thanks @Deepscorn
        super.onDetach();
    }
}

// Fragment B has a public method to do something with the text
public class FragB extends Fragment{

    public void updateText(String text){
        // Here you have it
    }
}


问:
Angular2: Global Guard (user has to be logged in always)
I'm building an application where there's no access at all for unauthenticated users.

I wrote a LoggedInGuard, but now I have to add canActivate: [LoggedInGuard] to every route inside my router configuration (except the LoginComponent).

Is there a better way to get this working?

My file / module layout looks like this:

```<code>app/
  AppModule
  AppRoutingModule
  AppComponent

  authentication/
    AuthenticationModule
    AuthenticationRoutingModule
    LoginComponent

  contacts/
    ContactsModule
    ContactsRoutingModule
    ContactListComponent

  users/
    UsersModule
    UsersRoutingModule
    UserEditComponent

  ...
</code>```

Maybe it's possible to create two separate routing spaces (one for login, one for the rest of the app) and apply the guard only to the rest of the app part?

I hope there's a simple solution.

Thanks in advance!

答:
I was able to provide a set of global guards that spanned across multiple modules by moving the guards into a router event listener.

To make the event listener fire for all requests, I inserted it into the AppComponent.

Note that, in both the examples below, you can still add in custom guards for individual routes, and those will still work.

Without Guards

You can remove your use of guards and instead implement the logic directly in the event listener.

```<code>import { Component, OnInit } from '@angular/core';
import { Router, RoutesRecognized } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/filter';

// I use a service to keep track of the authentication ticket.
// Replace this with whatever mechanism you use.
import { AuthenticationService }  from './_services/index';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  constructor(
      private router: Router,
      private authService: AuthenticationService
  ) {}

  ngOnInit() {
    this.router.events
    .filter(event => event instanceof RoutesRecognized)
    .subscribe((event: RoutesRecognized) => {
      const url = event.urlAfterRedirects;

      // Public URLs don't need any kind of authorization.
      if (url === '/public' || url.startsWith('/public/') || url.startsWith('/public?')) {
        return;
      }

      // Everything else must be authenticated.
      if (!this.authService.isAuthenticated()) {
        // Allow for the login page to redirect back to the originally
        // requested page.
        this.router.navigate(['/public/login'], { queryParams: { returnUrl: state.url } });
      }
    });
  }
}
</code>```

Requests that are passed to any sub-page of /public will pass through regardless, but any other request must have authentication, or it will redirect to /public/login.

Take care that the redirect page isn't in the protected area, or else the router will enter an infinite loop.

With Guards

The implementation below shows how I reused the existing guards.  This is only if you need to keep them, or if it makes your code cleaner.

```<code>import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute, RoutesRecognized, CanActivate } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/filter';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/mergeMap';

// Reused guards.
import { AdminGuard, AuthGuard } from './_guards/index';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {

  constructor(
      private route: ActivatedRoute,
      private router: Router,
      private adminGuard: AdminGuard,
      private authGuard: AuthGuard
  ) {}

  ngOnInit() {
    this.router.events
    .filter(event => event instanceof RoutesRecognized)
    .subscribe((event: RoutesRecognized) => {
      // Public pages don't require authentication.
      if (this.isSubPage(event, '/public')) {
        return;
      }

      // All other requests MUST be done through an
      // authenticated connection.  The guard performs
      // the redirection for us.
      if (!this.callCanActivate(event, this.authGuard)) {
        return;
      }

      // Administration pages require additional restrictions.
      // The guard performs the redirection for us.
      if (this.isSubPage(event, '/admin')) {
        if (!this.callCanActivate(event, this.adminGuard)) {
          return;
        }
      }
    });
  }

  callCanActivate(event: RoutesRecognized, guard: CanActivate) {
    return guard.canActivate(this.route.snapshot, event.state);
  }

  isSubPage(event: RoutesRecognized, parent: string) {
    const url = event.urlAfterRedirects;
    return (url === parent
        || url.startsWith(parent + '/')
        || url.startsWith(parent + '?'));
  }
}
</code>```

This example is the same as the one above, but with added protection for the /admin area, which ensures that the user also has administrative permissions.

Body:
I'm building an application where there's no access at all for unauthenticated users.

I wrote a LoggedInGuard, but now I have to add canActivate: [LoggedInGuard] to every route inside my router configuration (except the LoginComponent).

Is there a better way to get this working?

My file / module layout looks like this:

app/
  AppModule
  AppRoutingModule
  AppComponent

  authentication/
    AuthenticationModule
    AuthenticationRoutingModule
    LoginComponent

  contacts/
    ContactsModule
    ContactsRoutingModule
    ContactListComponent

  users/
    UsersModule
    UsersRoutingModule
    UserEditComponent

  ...

Maybe it's possible to create two separate routing spaces (one for login, one for the rest of the app) and apply the guard only to the rest of the app part?

I hope there's a simple solution.

Thanks in advance!

Body:
I was able to provide a set of global guards that spanned across multiple modules by moving the guards into a router event listener.

To make the event listener fire for all requests, I inserted it into the AppComponent.

Note that, in both the examples below, you can still add in custom guards for individual routes, and those will still work.

Without Guards

You can remove your use of guards and instead implement the logic directly in the event listener.

import { Component, OnInit } from '@angular/core';
import { Router, RoutesRecognized } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/filter';

// I use a service to keep track of the authentication ticket.
// Replace this with whatever mechanism you use.
import { AuthenticationService }  from './_services/index';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  constructor(
      private router: Router,
      private authService: AuthenticationService
  ) {}

  ngOnInit() {
    this.router.events
    .filter(event => event instanceof RoutesRecognized)
    .subscribe((event: RoutesRecognized) => {
      const url = event.urlAfterRedirects;

      // Public URLs don't need any kind of authorization.
      if (url === '/public' || url.startsWith('/public/') || url.startsWith('/public?')) {
        return;
      }

      // Everything else must be authenticated.
      if (!this.authService.isAuthenticated()) {
        // Allow for the login page to redirect back to the originally
        // requested page.
        this.router.navigate(['/public/login'], { queryParams: { returnUrl: state.url } });
      }
    });
  }
}

Requests that are passed to any sub-page of /public will pass through regardless, but any other request must have authentication, or it will redirect to /public/login.

Take care that the redirect page isn't in the protected area, or else the router will enter an infinite loop.

With Guards

The implementation below shows how I reused the existing guards.  This is only if you need to keep them, or if it makes your code cleaner.

import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute, RoutesRecognized, CanActivate } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/filter';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/mergeMap';

// Reused guards.
import { AdminGuard, AuthGuard } from './_guards/index';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {

  constructor(
      private route: ActivatedRoute,
      private router: Router,
      private adminGuard: AdminGuard,
      private authGuard: AuthGuard
  ) {}

  ngOnInit() {
    this.router.events
    .filter(event => event instanceof RoutesRecognized)
    .subscribe((event: RoutesRecognized) => {
      // Public pages don't require authentication.
      if (this.isSubPage(event, '/public')) {
        return;
      }

      // All other requests MUST be done through an
      // authenticated connection.  The guard performs
      // the redirection for us.
      if (!this.callCanActivate(event, this.authGuard)) {
        return;
      }

      // Administration pages require additional restrictions.
      // The guard performs the redirection for us.
      if (this.isSubPage(event, '/admin')) {
        if (!this.callCanActivate(event, this.adminGuard)) {
          return;
        }
      }
    });
  }

  callCanActivate(event: RoutesRecognized, guard: CanActivate) {
    return guard.canActivate(this.route.snapshot, event.state);
  }

  isSubPage(event: RoutesRecognized, parent: string) {
    const url = event.urlAfterRedirects;
    return (url === parent
        || url.startsWith(parent + '/')
        || url.startsWith(parent + '?'));
  }
}

This example is the same as the one above, but with added protection for the /admin area, which ensures that the user also has administrative permissions.


问:
secure or encrypt smarty plugins
I am working on CMS system using smarty. The one cms system could support multiple websites with multiple websites, multiple templates, multiple plugins and components...

Client can register and create his website using pre existing templates and choose components to display them on that template.

My Question is that How i can make those component secure or encrypted. so if client take his site away from the server to another server, he won't able to use those module, components etc. or atleast these would expire after certain time..

I am going to create these components using smarty plugins.

Is there any solution in php, smarty ?

答:
If you don't want to use something like the ionCube PHPEncoder which is able to do the job for Smarty (via a Patch), I would recommend you write a script that performs code obfuscation to your Smarty files to make it a real annoyance to de-obfuscate them.
Ideally that would include variable obfuscation also but you then need to touch your PHP files also when handling the variables over to Smarty.

This is not great, but as said, when not using a real encoder there's not much you can do.

Title: secure or encrypt smarty plugins


问:
Why am I getting CouldnotfetchacccesstokenforAzureStatusCode when releasing to Azure from TFS
I wonder if I am the only one getting this CouldnotfetchacccesstokenforAzureStatusCode when deploying(release workflow) from TFS (visualstudio.com) to Azure. Even google doesnt have a clue.

The release workflow profile was set up from within Azure, so I guess the Subscription and Service name are ok. Afterall it manages to get the artifacts transfered. And it HAS been working for a week before it stopped working. It is triggered by a successfull hosted build after a git push. No manual work.

```<code>##[section]Finishing: Download Artifacts
##[section]Starting: Deploy Azure App Service
==============================================================================
Task         : Azure App Service Deploy
Description  : Update Azure App Service using Web Deploy / Kudu REST APIs
Version      : 2.1.10
Author       : Microsoft Corporation
Help         : [More Information](https://aka.ms/azurermwebdeployreadme)
==============================================================================
d19c95a6-ebscrabbeldabbeld9c3eb0cfeb exists true
##[warning]Can\'t find loc string for key: CouldnotfetchacccesstokenforAzureStatusCode
##[error]CouldnotfetchacccesstokenforAzureStatusCode 400 Bad Request
##[section]Finishing: Deploy Azure App Service
##[section]Finishing: Release
</code>```

I have "Publish using Web Deploy" and "Take App Offline" and the Control Opption "Enabled" checked. The App Service is version 2. Any ideas?

EDIT: Tried version 3(in preview) and I got a different (but probably the same) error:

```<code>##[error]Could not fetch acccess token for Azure. Status Code: 400 (Bad Request)
</code>```

答: Just solved this issue by unlinking all the linked items on the deploy step. So 'Azure Subscription' and 'App Service name', even though they appeared to be set correctly... this got it working for me.</p>

Body:
I wonder if I am the only one getting this CouldnotfetchacccesstokenforAzureStatusCode when deploying(release workflow) from TFS (visualstudio.com) to Azure. Even google doesnt have a clue.

The release workflow profile was set up from within Azure, so I guess the Subscription and Service name are ok. Afterall it manages to get the artifacts transfered. And it HAS been working for a week before it stopped working. It is triggered by a successfull hosted build after a git push. No manual work.

##[section]Finishing: Download Artifacts
##[section]Starting: Deploy Azure App Service
==============================================================================
Task         : Azure App Service Deploy
Description  : Update Azure App Service using Web Deploy / Kudu REST APIs
Version      : 2.1.10
Author       : Microsoft Corporation
Help         : [More Information](https://aka.ms/azurermwebdeployreadme)
==============================================================================
d19c95a6-ebscrabbeldabbeld9c3eb0cfeb exists true
##[warning]Can\'t find loc string for key: CouldnotfetchacccesstokenforAzureStatusCode
##[error]CouldnotfetchacccesstokenforAzureStatusCode 400 Bad Request
##[section]Finishing: Deploy Azure App Service
##[section]Finishing: Release

I have "Publish using Web Deploy" and "Take App Offline" and the Control Opption "Enabled" checked. The App Service is version 2. Any ideas?

EDIT: Tried version 3(in preview) and I got a different (but probably the same) error:

##[error]Could not fetch acccess token for Azure. Status Code: 400 (Bad Request)


问:
Load Image using RxJava into Google map setInfoWindowAdapter
Hello I have an imageview that sets its image with a bitmap image obtained using a Single inside a google map but unfortunately the image will not load. I read some solution that use the callback feature from picasso but for this function I am just using a regular Imageview.setImageBitmap. I have tried hiding and showing the marker but I had not luck. Thank you for your help!

JAVA:

```<code>@Override
public void onMapReady(final GoogleMap googleMap) {

 ......

this.googleMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {

.....

        @Override
        public View getInfoContents(final Marker marker) {

final ImageView imageView = (ImageView) view.findViewById(R.id.image);

Single<Bitmap> imageSingle = getImageWithURL(url);

        imageSingle.subscribeOn(Schedulers.io())

        .observeOn(AndroidSchedulers.mainThread())

        .subscribe(new SingleSubscriber<Bitmap>() {

    @Override

    public void onSuccess(Bitmap image) {

        Log.e(TAG, "" + image.getWidth());

        Log.e(TAG, images.size() + "");

        imageView.setImageBitmap(image); //this line doesnt work

        Log.e(TAG, "Sucess");

    }

    @Override

    public void onError(Throwable error) {

        Log.e(“Image”, error.tostring())

    }

});
</code>```

}

答: I was able to figure out this issue after a lot of digging! The issue is that the marker loads and converts the view into an image, and since my Single adds the image after it has been converted it wont display. To fix this all you gotta do is load the images before hand and then inside the marker just call the imageview.set function. Hope this helps to anybody that has this issue!</p>

Body:
Hello I have an imageview that sets its image with a bitmap image obtained using a Single inside a google map but unfortunately the image will not load. I read some solution that use the callback feature from picasso but for this function I am just using a regular Imageview.setImageBitmap. I have tried hiding and showing the marker but I had not luck. Thank you for your help!

JAVA:

@Override
public void onMapReady(final GoogleMap googleMap) {

 ......

this.googleMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {

.....

        @Override
        public View getInfoContents(final Marker marker) {

final ImageView imageView = (ImageView) view.findViewById(R.id.image);

Single<Bitmap> imageSingle = getImageWithURL(url);

        imageSingle.subscribeOn(Schedulers.io())

        .observeOn(AndroidSchedulers.mainThread())

        .subscribe(new SingleSubscriber<Bitmap>() {

    @Override

    public void onSuccess(Bitmap image) {

        Log.e(TAG, "" + image.getWidth());

        Log.e(TAG, images.size() + "");

        imageView.setImageBitmap(image); //this line doesnt work

        Log.e(TAG, "Sucess");

    }

    @Override

    public void onError(Throwable error) {

        Log.e(“Image”, error.tostring())

    }

});

}


问:
How to use pattern matching inside a function?
I'm struggling with implementation of an unbounded knapsack problem solver. I want to use recursion and memoization instead of explicit state.

But the problem is that I can't find a way to express my thoughts in valid Haskell. Both versions This gives me

```<code>    parse error on input ‘=’
    Perhaps you need a 'let' in a 'do' block?
    e.g. 'let x = 5' instead of 'x = 5'

bestUnbounded :: [Integer] -> Integer -> ([Integer], Integer)
bestUnbounded items capacity = if capacity <= 0
                                  then ([], 0)
                                  else maximumBy (comparing snd) solutions
                                      where solutions = filter (\ s -> snd s <= capacity) $ map solve items
                                            solve i   = (solution, weight + i)
                                                where solution, weight = bestUnbounded items (capacity - i)

bestUnbounded :: [Integer] -> Integer -> ([Integer], Integer)
bestUnbounded items capacity
  | capacity <= 0 = ([], 0)
  | otherwise     = maximumBy (comparing snd) solutions
      where solutions = filter (\ s -> snd s <= capacity)  map solve items
            solve i   = let solution, weight = bestUnbounded items (capacity - i)
                        in (solution, weight + i)
</code>```

If anyone could also show how to use Data.Func.Memoize on that I would be also grateful.

EDIT1

Working solution

```<code>import Data.List (maximumBy)
import Data.Ord (comparing)
import Data.Function.Memoize (memoize)

bestUnbounded :: [Integer] -> Integer -> ([Integer], Integer)
bestUnbounded items capacity
  | capacity <= 0 = ([], 0)
  | otherwise     = solver' capacity
  where solver' = memoize solver
        solver capacity = maximumBy (comparing snd) solutions
        solutions = filter (\ s -> snd s <= capacity) $ map solve items
        solve i   = let (solution, weight) = bestUnbounded items (capacity - i)
                    in (i : solution, weight + i)
</code>```

答:
This isn't syntactically valid:

```<code>solution, weight = bestUnbounded items (capacity - i)
</code>```

I think you meant to pattern match on (,) like this:

```<code>(solution, weight) = bestUnbounded items (capacity - i)
</code>```

The tuple syntax always requires parentheses, for both construction and pattern matching.

Body:
I'm struggling with implementation of an unbounded knapsack problem solver. I want to use recursion and memoization instead of explicit state.

But the problem is that I can't find a way to express my thoughts in valid Haskell. Both versions This gives me

    parse error on input ‘=’
    Perhaps you need a 'let' in a 'do' block?
    e.g. 'let x = 5' instead of 'x = 5'

bestUnbounded :: [Integer] -> Integer -> ([Integer], Integer)
bestUnbounded items capacity = if capacity <= 0
                                  then ([], 0)
                                  else maximumBy (comparing snd) solutions
                                      where solutions = filter (\ s -> snd s <= capacity) $ map solve items
                                            solve i   = (solution, weight + i)
                                                where solution, weight = bestUnbounded items (capacity - i)

bestUnbounded :: [Integer] -> Integer -> ([Integer], Integer)
bestUnbounded items capacity
  | capacity <= 0 = ([], 0)
  | otherwise     = maximumBy (comparing snd) solutions
      where solutions = filter (\ s -> snd s <= capacity)  map solve items
            solve i   = let solution, weight = bestUnbounded items (capacity - i)
                        in (solution, weight + i)

If anyone could also show how to use Data.Func.Memoize on that I would be also grateful.

EDIT1

Working solution

import Data.List (maximumBy)
import Data.Ord (comparing)
import Data.Function.Memoize (memoize)

bestUnbounded :: [Integer] -> Integer -> ([Integer], Integer)
bestUnbounded items capacity
  | capacity <= 0 = ([], 0)
  | otherwise     = solver' capacity
  where solver' = memoize solver
        solver capacity = maximumBy (comparing snd) solutions
        solutions = filter (\ s -> snd s <= capacity) $ map solve items
        solve i   = let (solution, weight) = bestUnbounded items (capacity - i)
                    in (i : solution, weight + i)

Body:
This isn't syntactically valid:

solution, weight = bestUnbounded items (capacity - i)

I think you meant to pattern match on (,) like this:

(solution, weight) = bestUnbounded items (capacity - i)

The tuple syntax always requires parentheses, for both construction and pattern matching.


问:
How to display a text inside a tag if a value passed from controller is true using blade template?
I want to disable input if the value transferred from the controller is false. I read the blade template documentation for Laravel, but couldn't find any useful resource.

I tried the following code, but it yields an error.

```<code><input type="text" name="url" style="height:36px;"   value="http://theurl.in/{{$link_data->hash}}" @if $isEditable {{ 'enabled' }} @endif /> <br/>
</code>```

The exact code part is,

```<code>@if $isEditable {{ 'enabled' }} @endif
</code>```

If you can provide any suggestion, it would be very helpful.

Thanks!

答:
Your code has a syntax error. If you check the blade templating documentation, if conditions need to be in parenthesis, so the solution should be like this:

```<code>@if ($isEditable) {{ 'enabled' }} @endif
</code>```

I also agree with Ohgodwhy's answer, HTML inputs are enabled by default, so you should just put:

```<code>@if (!$isEditable) {{ 'disabled=disabled' }} @endif
</code>```

Body:
I want to disable input if the value transferred from the controller is false. I read the blade template documentation for Laravel, but couldn't find any useful resource.

I tried the following code, but it yields an error.

<input type="text" name="url" style="height:36px;"   value="http://theurl.in/{{$link_data->hash}}" @if $isEditable {{ 'enabled' }} @endif />

The exact code part is,

@if $isEditable {{ 'enabled' }} @endif

If you can provide any suggestion, it would be very helpful.

Thanks!

Body:
Your code has a syntax error. If you check the blade templating documentation, if conditions need to be in parenthesis, so the solution should be like this:

@if ($isEditable) {{ 'enabled' }} @endif

I also agree with Ohgodwhy's answer, HTML inputs are enabled by default, so you should just put:

@if (!$isEditable) {{ 'disabled=disabled' }} @endif


问:
React-modal for dynamic display of images
I'm building an app using react , I have a page where all images display dynamically. I want those images to open in react-modal when I click . How do i set the modal for the images to be displayed

What property should I set in a modal so that it applies to all images

答:
```<code>class ImageModal extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      showModal: false
    };
  }

  setModalState(showModal) {
    this.setState({
      showModal: showModal
    });
  }

  render() {
    return (
      <div>
        <img src={ this.props.src } onClick={ this.setModalState.bind(this, true) } />
        <ReactModal isOpen={ this.state.showModal }>
          <img src={ this.props.src } onClick={ this.setModalState.bind(this, false) } />
        </ReactModal>
      </div>
    )
}
</code>```


问:
Swiper not working when there is extra div between swiper-contaIner, wrapper and slide
I am trying to implement swipe functionality for mobile view of our website.
I am using idangero swiper for that.
But problem is when there is extra div with other class in between any div containing class -'swiper-container', 'swiper-wrapper' and 'swiper-slide' it does not work.
Such as below code

```<code><div class="swiper-container">
        <div class="swiper-wrapper">
            <div class="another-div">
                <div class="swiper-slide">Slide 1</div>
                <div class="swiper-slide">Slide 2</div>
                <div class="swiper-slide">Slide 3</div>
                <div class="swiper-slide">Slide 4</div>
                <div class="swiper-slide">Slide 5</div>
                <div class="swiper-slide">Slide 6</div>
                <div class="swiper-slide">Slide 7</div>
                <div class="swiper-slide">Slide 8</div>
                <div class="swiper-slide">Slide 9</div>
                <div class="swiper-slide">Slide 10</div>
            </div>
        </div>
    </div>
</code>```

We are using AEM for authoring of web components and AEM authoring components adds extra divs. So can not remove those.

Any help to make it work with extra div is appreciated.

答:
I had success from 2 different ways.

1) changed library from swiper.js to carousel-swipe.js which is small jQuery plugin which uses bootstrap carousel and make it work with mobile swipe.

2)removed extra divs form AEM component.
Below code will remove extra div created by component, which in this case is class="parsys"

```<code><%@ page import="com.day.cq.wcm.api.components.IncludeOptions" %>
<%
   IncludeOptions opts = IncludeOptions.getOptions(request, true);
   opts.setDecorationTagName("");
 %>
</code>```

Component itself will also create div and you can remove that with help of cq:htmlTag .

Below is link where you can find details for second approach
AEM-remove component wrapper div

Body:
I am trying to implement swipe functionality for mobile view of our website.
I am using idangero swiper for that.
But problem is when there is extra div with other class in between any div containing class -'swiper-container', 'swiper-wrapper' and 'swiper-slide' it does not work.
Such as below code

Slide 1

Slide 2

Slide 3

Slide 4

Slide 5

Slide 6

Slide 7

Slide 8

Slide 9

Slide 10

We are using AEM for authoring of web components and AEM authoring components adds extra divs. So can not remove those.

Any help to make it work with extra div is appreciated.

Body:
I had success from 2 different ways.

1) changed library from swiper.js to carousel-swipe.js which is small jQuery plugin which uses bootstrap carousel and make it work with mobile swipe.

2)removed extra divs form AEM component.
Below code will remove extra div created by component, which in this case is class="parsys"

<%@ page import="com.day.cq.wcm.api.components.IncludeOptions" %>
<%
   IncludeOptions opts = IncludeOptions.getOptions(request, true);
   opts.setDecorationTagName("");
 %>

Component itself will also create div and you can remove that with help of cq:htmlTag .

Below is link where you can find details for second approach
AEM-remove component wrapper div


问:
Index DataFrame with list or series of boolean values (not statements)
I have a dataframe in which a certain column is fed to a filtering function that returns a series of boolean values (not a boolean statements).

EG: my filter returns

```<code>0   True,
1   False,
2   True
</code>```

How can I get only the dataframe rows in which my filter series is true?
In the example above, I would have a dataframe with row index 1 removed.

答:
You need boolean indexing if both indexesare same:

```<code>df = df[boolean_ser]
</code>```

If not and lenght is same:

```<code>df = df[boolean_ser.values]
</code>```

Sample:

```<code>np.random.seed(100)
df = pd.DataFrame(np.random.randint(10, size=(3, 4)), columns=list('ABCD'))
boolean_ser = pd.Series([True, False, True], index=df.index)
print (df)
   A  B  C  D
0  8  8  3  7
1  7  0  4  2
2  5  2  2  2
</code>```

```<code>boolean_ser = pd.Series([True, False, True], index=df.index)
print (boolean_ser)
0     True
1    False
2     True
dtype: bool

df1 = df[boolean_ser]
print (df1)
   A  B  C  D
0  8  8  3  7
2  5  2  2  2
</code>```

```<code>boolean_ser = pd.Series([True, False, True], index=[8,9,10])
print (boolean_ser)
8      True
9     False
10     True
dtype: bool

df1 = df[boolean_ser.values]
print (df1)
   A  B  C  D
0  8  8  3  7
2  5  2  2  2
</code>```

List works perfectly too (if same length):

```<code>print (boolean_list)
[True, False, True]

df1 = df[boolean_list]
print (df1)
   A  B  C  D
0  8  8  3  7
2  5  2  2  2
</code>```

Body:
I have a dataframe in which a certain column is fed to a filtering function that returns a series of boolean values (not a boolean statements).

EG: my filter returns

0   True,
1   False,
2   True

How can I get only the dataframe rows in which my filter series is true?
In the example above, I would have a dataframe with row index 1 removed.

Body:
You need boolean indexing if both indexesare same:

df = df[boolean_ser]

If not and lenght is same:

df = df[boolean_ser.values]

Sample:

np.random.seed(100)
df = pd.DataFrame(np.random.randint(10, size=(3, 4)), columns=list('ABCD'))
boolean_ser = pd.Series([True, False, True], index=df.index)
print (df)
   A  B  C  D
0  8  8  3  7
1  7  0  4  2
2  5  2  2  2

boolean_ser = pd.Series([True, False, True], index=df.index)
print (boolean_ser)
0     True
1    False
2     True
dtype: bool

df1 = df[boolean_ser]
print (df1)
   A  B  C  D
0  8  8  3  7
2  5  2  2  2

boolean_ser = pd.Series([True, False, True], index=[8,9,10])
print (boolean_ser)
8      True
9     False
10     True
dtype: bool

df1 = df[boolean_ser.values]
print (df1)
   A  B  C  D
0  8  8  3  7
2  5  2  2  2

List works perfectly too (if same length):

print (boolean_list)
[True, False, True]

df1 = df[boolean_list]
print (df1)
   A  B  C  D
0  8  8  3  7
2  5  2  2  2


问:
Inline radio with label up/down
I'm trying to get the inline radio in bootstrap with the label up or down the radio.

If you take the official example, you have:

```<code><div class="form-check form-check-inline">
  <label class="form-check-label">
    <input class="form-check-input" type="checkbox" id="inlineCheckbox1" value="option1"> 1
  </label>
</div>
<div class="form-check form-check-inline">
  <label class="form-check-label">
    <input class="form-check-input" type="checkbox" id="inlineCheckbox2" value="option2"> 2
  </label>
</div>
<div class="form-check form-check-inline">
  <label class="form-check-label">
    <input class="form-check-input" type="checkbox" id="inlineCheckbox3" value="option3"> 3
  </label>
</div>
</code>```

What can I do to align the label up or down?

Edit: A failed attempt (not aligned and the checkbox doesn't display a clickable pointer)

答:
what importance or significance does the form-check-input hold in your page? Is there a script that uses this class to do some actions?

I noticed that "form-check-input" is having a negative margin of -1.25rem defined, if you remove the class or replace it with form-check-label it aligns just fine.

```<code><div class="container">
  <div class="form-check form-check-inline">
    <label class="form-check-label">
        1 <br /><input class="form-check-label" type="checkbox" id="inlineCheckbox1" value="option1">
    </label>
</div>
<div class="form-check form-check-inline">
    <label class="form-check-label">
        2 <br /><input class="form-check-label" type="checkbox" id="inlineCheckbox2" value="option2">
    </label>
</div>
<div class="form-check form-check-inline disabled">
    <label class="form-check-label">
        3 <br /><input class="form-check-label" type="checkbox" id="inlineCheckbox3" value="option3">
    </label>
</div>
</div>
<!-- /container -->
</code>```

DEMO : http://plnkr.co/edit/bs0PWCX1J3Z8XnpdpolN?p=preview

EDIT:

The above solution does not center things when the label text is longer, to make it work, we could use bootstrap predefined class text-center and wrap the entire label element in it like so:

```<code><div class="text-center">
    <label class="form-check-label">
        1 <br />
        <input class="" type="checkbox" id="inlineCheckbox1" value="option1">
    </label>
    </div>
</code>```

UPDATED DEMO : http://plnkr.co/edit/CQumOaFUOrm2SSLyc5Ru?p=preview

Title: Inline radio with label up/down

Body:
I'm trying to get the inline radio in bootstrap with the label up or down the radio.

If you take the official example, you have:

    <input class="form-check-input" type="checkbox" id="inlineCheckbox1" value="option1"> 1

    <input class="form-check-input" type="checkbox" id="inlineCheckbox2" value="option2"> 2

    <input class="form-check-input" type="checkbox" id="inlineCheckbox3" value="option3"> 3

What can I do to align the label up or down?

Edit: A failed attempt (not aligned and the checkbox doesn't display a clickable pointer)

Body:
what importance or significance does the form-check-input hold in your page? Is there a script that uses this class to do some actions?

I noticed that "form-check-input" is having a negative margin of -1.25rem defined, if you remove the class or replace it with form-check-label it aligns just fine.

<div class="container">
  <div class="form-check form-check-inline">
    <label class="form-check-label">
        1 <br /><input class="form-check-label" type="checkbox" id="inlineCheckbox1" value="option1">
    </label>
</div>
<div class="form-check form-check-inline">
    <label class="form-check-label">
        2 <br /><input class="form-check-label" type="checkbox" id="inlineCheckbox2" value="option2">
    </label>
</div>
<div class="form-check form-check-inline disabled">
    <label class="form-check-label">
        3 <br /><input class="form-check-label" type="checkbox" id="inlineCheckbox3" value="option3">
    </label>
</div>
</div>
<!-- /container -->

DEMO : http://plnkr.co/edit/bs0PWCX1J3Z8XnpdpolN?p=preview

EDIT:

The above solution does not center things when the label text is longer, to make it work, we could use bootstrap predefined class text-center and wrap the entire label element in it like so:

<div class="text-center">
    <label class="form-check-label">
        1 <br />
        <input class="" type="checkbox" id="inlineCheckbox1" value="option1">
    </label>
    </div>

UPDATED DEMO : http://plnkr.co/edit/CQumOaFUOrm2SSLyc5Ru?p=preview


问:
IList.Cast<typeof(T)>() returns error, syntax looks ok
```<code>public static IList<T> LoadObjectListAll<T>()
{
    ISession session = CheckForExistingSession();
    var cfg = new NHibernate.Cfg.Configuration().Configure();
    var returnList = session.CreateCriteria(typeof(T));
    var list = returnList.List();
    var castList = list.Cast<typeof(T)>();
    return castList;
}
</code>```

<p>So, I'm getting a build error where I am casting the "list" element to a generic IList .... can anyone see a glaring error here? </p>

答:
CLI only supports generic arguments for covariance and contravariance when using delegates, but when using generics there are some limitations, for example, you can cast a string to an object so most people will assume that you can do the same with List to a List but you can't do that because there is no covariance between generic parameters however you can simulate covariance as you can see in this article. So it depends on the runtime type that it is generated by the abstract factory.

That reads like a markov chain... Bravo.

OwnerDisplayName: Sara Chipps

Body:
public static IList<T> LoadObjectListAll<T>()
{
    ISession session = CheckForExistingSession();
    var cfg = new NHibernate.Cfg.Configuration().Configure();
    var returnList = session.CreateCriteria(typeof(T));
    var list = returnList.List();
    var castList = list.Cast<typeof(T)>();
    return castList;
}

So, I'm getting a build error where I am casting the "list" element to a generic IList .... can anyone see a glaring error here?

OwnerDisplayName: Jonathan Holland


问:
Magento: why the empty tables do have weight?
Why do database empty tables with 0 rows have the weight?

Also there are other empty tables with 0 weight.
What is the difference?

Database screenshot

答:
Just a guess, but I'd say 16KiB is the minimum size that will be allocated for a table on disk. It still has to use some data to store information about the table like its name and structure.

The table with zero size looks like it might be a temporary table or something, which might exist only in memory and be using a different engine, which perhaps doesn't report this information as it would have to be kept in memory anyway.


问:
Weird behavior with Maven plugin management with maven-surefire-plugin
I have a parent pom which defines

<pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>2.19.1</version>
                    <configuration>
                        <parallel>classesAndMethods</parallel>
                        <threadCount>4</threadCount>
                    </configuration>
                </plugin>
            </plugins>
        </pluginManagement>
```

I have a child project which inherits from the pom but does not declare the plugin in its plugin section.
I am still seeing the plugin take effect when I run maven test goal.

答:
When defining maven-surefire plugin in the parent project
Refer:http://maven.apache.org/surefire/maven-surefire-plugin/usage.html

```<code><pluginManagement>
  <plugins>
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-surefire-plugin</artifactId>
      <version>2.19.1</version>
    </plugin>
  </plugins>
</pluginManagement>
</code>```

Adding the configuration section causes it to execute in each of the child projects implicitly.

In the child project the configuration will look like

```<code> <plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-surefire-plugin</artifactId>
  <configuration>
      <parallel>classesAndMethods</parallel>
      <threadCount>4</threadCount>
  </configuration>
</plugin>
</code>```

Even though the configuration in the child project is quite verbose, it ensures explicit addition of the dependency and the same version of the plugin in all sub-modules.

Body:
I have a parent pom which defines

<pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>2.19.1</version>
                    <configuration>
                        <parallel>classesAndMethods</parallel>
                        <threadCount>4</threadCount>
                    </configuration>
                </plugin>
            </plugins>
        </pluginManagement>

I have a child project which inherits from the pom but does not declare the plugin in its plugin section.
I am still seeing the plugin take effect when I run maven test goal.

Body:
When defining maven-surefire plugin in the parent project
Refer:http://maven.apache.org/surefire/maven-surefire-plugin/usage.html

<pluginManagement>
  <plugins>
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-surefire-plugin</artifactId>
      <version>2.19.1</version>
    </plugin>
  </plugins>
</pluginManagement>

Adding the configuration section causes it to execute in each of the child projects implicitly.

In the child project the configuration will look like

 <plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-surefire-plugin</artifactId>
  <configuration>
      <parallel>classesAndMethods</parallel>
      <threadCount>4</threadCount>
  </configuration>
</plugin>

Even though the configuration in the child project is quite verbose, it ensures explicit addition of the dependency and the same version of the plugin in all sub-modules.


问:
Extract word before all matching character in bash
How to extract all the string before :, I could get only the first as below

```<code>$ echo "cc_dd:qqq www;aa_bb:ll fi;ee_ff:bb dd ee" | sed 's/:.*//g'
$ cc_dd
# want to print cc_dd aa_bb and ee_ff
</code>```

答:
Short grep approach:

```<code>s="cc_dd:qqq www;aa_bb:ll fi;ee_ff:bb dd ee"
grep -Po '[^;:]+(?=:)' <<< $s
</code>```

-P option, allows Perl regular expressions

-o option, tells to print only matched substrings

(?=:) - positive lookahead assertion, assures that desired substring is followed by :

The output:

```<code>cc_dd
aa_bb
ee_ff
</code>```

Performance comparison:

```<code>time (for i in {1..1000}; do grep -Po '[^;:]+(?=:)' <<< $s > /dev/null; done;)

real    0m1.936s
user    0m0.036s
sys     0m0.236s
</code>```

```<code>time (for i in {1..1000}; do awk -v RS=\; '{split($0,a,":"); print a[1]}' <<< $s > /dev/null; done;)

real    0m2.633s
user    0m0.056s
sys     0m0.264s
</code>```

Body:
How to extract all the string before :, I could get only the first as below

$ echo "cc_dd:qqq www;aa_bb:ll fi;ee_ff:bb dd ee" | sed 's/:.*//g'
$ cc_dd
# want to print cc_dd aa_bb and ee_ff

Body:
Short grep approach:

s="cc_dd:qqq www;aa_bb:ll fi;ee_ff:bb dd ee"
grep -Po '[^;:]+(?=:)' <<< $s

-P option, allows Perl regular expressions

-o option, tells to print only matched substrings

(?=:) - positive lookahead assertion, assures that desired substring is followed by :

The output:

cc_dd
aa_bb
ee_ff

Performance comparison:

time (for i in {1..1000}; do grep -Po '[^;:]+(?=:)' <<< $s > /dev/null; done;)

real    0m1.936s
user    0m0.036s
sys     0m0.236s

time (for i in {1..1000}; do awk -v RS=\; '{split($0,a,":"); print a[1]}' <<< $s > /dev/null; done;)

real    0m2.633s
user    0m0.056s
sys     0m0.264s


问:
Redis data recovery from Append Only File?
If we enable the AppendFileOnly in the redis.conf file, every operation which changes the redis database is loggged in that file.

Now, Suppose Redis has used all the memory allocated to it in the "maxmemory" direcive in the redis.conf file.

To store more data., it starts removing data by any one of the behaviours(volatile-lru, allkeys-lru etc.) specified in the redis.conf file.

Suppose some data gets removed from the main memory, But its log will still be there in the AppendOnlyFile(correct me if I am wrong). Can we get that data back using this AppendOnlyFile ?

Simply, I want to ask that if there is any way we can get that removed data back in the main memory ? Like Can we store that data into disk memory and load that data in the main memory when required.

答:
I got this answer from google groups. I'm sharing it.

----->

Eviction of keys is recorded in the AOF as explicit DEL commands, so when
the file is replayed fully consistency is maintained.

The AOF is used only to recover the dataset after a restart, and is not
used by Redis for serving data. If the key still exists in it (with a
subsequent eviction DEL), the only way to "recover" it is by manually
editing the AOF to remove the respective deletion and restarting the
server.

-----> Another answer for this

The AOF, as its name suggests, is a file that's appended to.  It's not a database that Redis searches through and deletes the creation record when a deletion record is encountered.  In my opinion, that would be too much work for too little gain.

As mentioned previously, a configuration that re-writes the AOF (see the BGREWRITEAOF command as one example) will erase any keys from the AOF that had been deleted, and now you can't recover those keys from the AOF file.  The AOF is not the best medium for recovering deleted keys.  It's intended as a way to recover the database as it existed before a crash - without any deleted keys.

If you want to be able to recover data after it was deleted, you need a different kind of backup.  More likely a snapshot (RDB) file that's been archived with the date/time that it was saved.  If you learn that you need to recover data, select the snapshot file from a time you know the key existed, load it into a separate Redis instance, and retrieve the key with RESTORE or GET or similar commands.  As has been mentioned, it's possible to parse the RDB or AOF file contents to extract data from them without loading the file into a running Redis instance.  The downside to this approach is that such tools are separate from the Redis code and may not always understand changes to the data format of the files the way the Redis server does.  You decide which approach will work with the level of speed and reliability you want.


问:
OWIN ApiController access to the request body/stringified JSON
This is in OWIN & .Net 4.5.2

Using debug I'm proving this controller's method is being called by the web request.

My thing is the request body contains a JSON stringified object:

"{ 'id':'12', 'text1':'hello', 'test2':'world' }"

Which is applicably encoded as it is transferred on the line.

I've tried so many things I'm so confused now.

How do I get the decoded string so I can JSON.Parse() that or better yet get .Net to just given me an object?

In one version (long ago now) I had a defined type for this object.  If I need that great, not a high challenge.  But if I only have the JSON object from the string that's fine too.

```<code>public class cController : ApiController {

    [HttpPut]
    public string put(string id) {
        var bdy = this.Request.Content;

        //Console.WriteLine("PUT containers {0}", body);
        return string.Empty;
    }
}
</code>```

In case it helps, the bdy.ContentReadStream is null.  I don't know if this is good, bad, or important.  Maybe Request.Content isn't the way to go but seems to me like if I'm going to read the body as a stream then it shouldn't be null.

I also tried working through System.Web.HttpContext.  If that is somehow the answer I have no problem going back to that.  But I couldn't find the secret sauce.

答:
Pass the desired model as a parameter to the action and the frame work should be able to parse it provided it is valid JSON

```<code>public class cController : ApiController {

    [HttpPut]
    public IHttpActionResult Put(string id,[FromBody] Model body) {
        if(ModelState.IsValue) {
            return Ok(body.text1);
        }
        return BadRequest();
    }
}
</code>```

Where Model is defined as

```<code>public class Model {
    public string id { get; set; }
    public string text1 { get; set; }
    public string test2 { get; set; }
}
</code>```

Body:
This is in OWIN & .Net 4.5.2

Using debug I'm proving this controller's method is being called by the web request.

My thing is the request body contains a JSON stringified object:

"{ 'id':'12', 'text1':'hello', 'test2':'world' }"

Which is applicably encoded as it is transferred on the line.

I've tried so many things I'm so confused now.

How do I get the decoded string so I can JSON.Parse() that or better yet get .Net to just given me an object?

In one version (long ago now) I had a defined type for this object.  If I need that great, not a high challenge.  But if I only have the JSON object from the string that's fine too.

public class cController : ApiController {

    [HttpPut]
    public string put(string id) {
        var bdy = this.Request.Content;

        //Console.WriteLine("PUT containers {0}", body);
        return string.Empty;
    }
}

In case it helps, the bdy.ContentReadStream is null.  I don't know if this is good, bad, or important.  Maybe Request.Content isn't the way to go but seems to me like if I'm going to read the body as a stream then it shouldn't be null.

I also tried working through System.Web.HttpContext.  If that is somehow the answer I have no problem going back to that.  But I couldn't find the secret sauce.

Body:
Pass the desired model as a parameter to the action and the frame work should be able to parse it provided it is valid JSON

public class cController : ApiController {

    [HttpPut]
    public IHttpActionResult Put(string id,[FromBody] Model body) {
        if(ModelState.IsValue) {
            return Ok(body.text1);
        }
        return BadRequest();
    }
}

Where Model is defined as

public class Model {
    public string id { get; set; }
    public string text1 { get; set; }
    public string test2 { get; set; }
}


问:
Magnific Popup – Image gallery inside of modal box
I've used the great magnific popup for inline content modal box. There is an image gallery in this modal, which I'd like to use the magnific popup for too.
Is there any way of going "one level deeper" and by clicking on image, going in the gallery displa mode with these images, and when exiting this modal box, just returning to the original modal box?

Thank you for any advice

答:
Just implemented this yesterday, so here it goes.

var parentPopup = false;
$.magnificPopup.open({
    items: {src: '#inline-content'},
    type: 'inline',
    callbacks: {
        open: function () {
            $('#gallery')
                .off('click')
                .on('click', function(e) {
                    e.stopPropagation();
                    // If an instance is open, keep track and close it
                    if ($.magnificPopup.instance.isOpen) {
                        parentPopup = true;
                        // Here we could also store the parent instance in a global var using $.magnificPopup.instance.clone() to, for example, know which was the parent popup if we have multiple of them.
                        $.magnificPopup.close();
                    }
                })
                .magnificPopup({
                    type: 'image',
                    gallery: {
                        enabled: true
                    },
                    callbacks: {
                        afterClose: function() {
                            // If we come from a parent popup
                            if (parentPopup === true) {
                                // Reopen initial popup here
                            }
                        }
                    }
                });
        }
    }
});
```

In your case I don't think the tracking global variable and the two conditionals are necessary, but my implementation is more complex so I left them there.

The key thing here is that you have to close the first popup before opening the next one, and then reopening it after closing the second.

Hope it helps.

Body:
Just implemented this yesterday, so here it goes.

var parentPopup = false;
$.magnificPopup.open({
    items: {src: '#inline-content'},
    type: 'inline',
    callbacks: {
        open: function () {
            $('#gallery')
                .off('click')
                .on('click', function(e) {
                    e.stopPropagation();
                    // If an instance is open, keep track and close it
                    if ($.magnificPopup.instance.isOpen) {
                        parentPopup = true;
                        // Here we could also store the parent instance in a global var using $.magnificPopup.instance.clone() to, for example, know which was the parent popup if we have multiple of them.
                        $.magnificPopup.close();
                    }
                })
                .magnificPopup({
                    type: 'image',
                    gallery: {
                        enabled: true
                    },
                    callbacks: {
                        afterClose: function() {
                            // If we come from a parent popup
                            if (parentPopup === true) {
                                // Reopen initial popup here
                            }
                        }
                    }
                });
        }
    }
});

In your case I don't think the tracking global variable and the two conditionals are necessary, but my implementation is more complex so I left them there.

The key thing here is that you have to close the first popup before opening the next one, and then reopening it after closing the second.

Hope it helps.


问:
how to get only fully matched string from match
I need to match "test" or "test," from a string like

```<code>"test, testhellowowo, wowtest,"
</code>```

Attempt 1

```<code>test[,]?
</code>```

it will match all three since all of the string include the test regardless what comes after.

Attempt 2

```<code>^test[,]?$
</code>```

it won't match any unless the string is test or test,

Expected results

```<code>"test, testhellowowo, wowtest,".match(x) // should match `test,`
"testhellowowo, wowtest,".match(x)  // should not match anything
</code>```

答:
You can use word boundaries

```<code>/\btest\b/g
</code>```

They match at

Before the first character in the string, if the first character is a word character.

After the last character in the string, if the last character is a word character.

Between two characters in the string, where one is a word character and the other is not a word character.

Body:
I need to match "test" or "test," from a string like

"test, testhellowowo, wowtest,"

Attempt 1

test[,]?

it will match all three since all of the string include the test regardless what comes after.

Attempt 2

^test[,]?$

it won't match any unless the string is test or test,

Expected results

"test, testhellowowo, wowtest,".match(x) // should match `test,`
"testhellowowo, wowtest,".match(x)  // should not match anything

Body:
You can use word boundaries

/\btest\b/g

They match at

Before the first character in the string, if the first character is a word character.

After the last character in the string, if the last character is a word character.

Between two characters in the string, where one is a word character and the other is not a word character.