问:
awk command fails with command substitution
Running this command fails:

```<code>$(printf "awk '{%sprint}'" $(tail -n +2 file.txt | cut -f2 | sort | uniq | awk 'BEGIN{a=1}{printf "gsub(\"%s\",%i);", $1,a++}')) file.txt
</code>```

It gives the following error:

```<code>awk: '
awk: ^ invalid char ''' in expression
</code>```

However, if I run the substituted command, I get this:

```<code>awk '{gsub("ACB",1);gsub("ASW",2);gsub("BEB",3);gsub("CDX",4);gsub("CEU",5);gsub("CHB",6);gsub("CHS",7);gsub("CLM",8);gsub("ESN",9);gsub("FIN",10);gsub("GBR",11);gsub("GIH",12);gsub("GWD",13);gsub("IBS",14);gsub("ITU",15);gsub("JPT",16);gsub("KHV",17);gsub("LWK",18);gsub("MSL",19);gsub("MXL",20);gsub("PEL",21);gsub("PJL",22);gsub("PUR",23);gsub("STU",24);gsub("TSI",25);gsub("YRI",26);print}'
</code>```

which I can run like so:

```<code>awk '{gsub("ACB",1);gsub("ASW",2);gsub("BEB",3);gsub("CDX",4);gsub("CEU",5);gsub("CHB",6);gsub("CHS",7);gsub("CLM",8);gsub("ESN",9);gsub("FIN",10);gsub("GBR",11);gsub("GIH",12);gsub("GWD",13);gsub("IBS",14);gsub("ITU",15);gsub("JPT",16);gsub("KHV",17);gsub("LWK",18);gsub("MSL",19);gsub("MXL",20);gsub("PEL",21);gsub("PJL",22);gsub("PUR",23);gsub("STU",24);gsub("TSI",25);gsub("YRI",26);print}' file.txt
</code>```

And it works perfectly. What am I doing wrong?

@ChrisLear gave me a working solution, but I still don't quite understand what the command solution is doing. Here's the working code:

```<code>$(printf "awk {%sprint}" $(tail -n +2 file.txt | cut -f2 | sort | uniq | awk 'BEGIN{a=1}{printf "gsub(\"%s\",%i);", $1,a++}')) file.txt
</code>```

The single quotes around {%sprint} are removed. Why do those single quotes break the command substitution?

edit: changed backtick to $(...) notation. Also added solution I don't understand.

答:
Try removing the quotes from the command being generated.

```<code>`printf "awk {%sprint}" $(tail -n +2 file.txt | cut -f2 | sort | uniq | awk 'BEGIN{a=1}{printf "gsub(\"%s\",%i);", $1,a++}')` file.txt
</code>```

For an explanation, see the accepted answer at Why does command substitution change how quoted arguments work?

Body:
Running this command fails:

$(printf "awk '{%sprint}'" $(tail -n +2 file.txt | cut -f2 | sort | uniq | awk 'BEGIN{a=1}{printf "gsub(\"%s\",%i);", $1,a++}')) file.txt

It gives the following error:

awk: '
awk: ^ invalid char ''' in expression

However, if I run the substituted command, I get this:

awk '{gsub("ACB",1);gsub("ASW",2);gsub("BEB",3);gsub("CDX",4);gsub("CEU",5);gsub("CHB",6);gsub("CHS",7);gsub("CLM",8);gsub("ESN",9);gsub("FIN",10);gsub("GBR",11);gsub("GIH",12);gsub("GWD",13);gsub("IBS",14);gsub("ITU",15);gsub("JPT",16);gsub("KHV",17);gsub("LWK",18);gsub("MSL",19);gsub("MXL",20);gsub("PEL",21);gsub("PJL",22);gsub("PUR",23);gsub("STU",24);gsub("TSI",25);gsub("YRI",26);print}'

which I can run like so:

awk '{gsub("ACB",1);gsub("ASW",2);gsub("BEB",3);gsub("CDX",4);gsub("CEU",5);gsub("CHB",6);gsub("CHS",7);gsub("CLM",8);gsub("ESN",9);gsub("FIN",10);gsub("GBR",11);gsub("GIH",12);gsub("GWD",13);gsub("IBS",14);gsub("ITU",15);gsub("JPT",16);gsub("KHV",17);gsub("LWK",18);gsub("MSL",19);gsub("MXL",20);gsub("PEL",21);gsub("PJL",22);gsub("PUR",23);gsub("STU",24);gsub("TSI",25);gsub("YRI",26);print}' file.txt

And it works perfectly. What am I doing wrong?

@ChrisLear gave me a working solution, but I still don't quite understand what the command solution is doing. Here's the working code:

$(printf "awk {%sprint}" $(tail -n +2 file.txt | cut -f2 | sort | uniq | awk 'BEGIN{a=1}{printf "gsub(\"%s\",%i);", $1,a++}')) file.txt

The single quotes around {%sprint} are removed. Why do those single quotes break the command substitution?

edit: changed backtick to $(...) notation. Also added solution I don't understand.

Body:
Try removing the quotes from the command being generated.

`printf "awk {%sprint}" $(tail -n +2 file.txt | cut -f2 | sort | uniq | awk 'BEGIN{a=1}{printf "gsub(\"%s\",%i);", $1,a++}')` file.txt

For an explanation, see the accepted answer at Why does command substitution change how quoted arguments work?


来源: stackexchange

问:
How to build multi tenant application using docker
I am pretty much new to the docker concept and know basics of it.
I just wanted to know how can we build multi tenant application using docker.
Where the containers will use the local hosted database with different schema.With the nginx we can do reverse proxy but how we can achieve it?
because every container will be accessed by localhost:8080 and how we can add upstream and server part.
It will be very helpful if some one explains it to me.

答:
If I understand correctly you want processes in containers to connect to resources on the host.

From you containers perspective in bridge mode (the default), the host's IP is the gateway. Unfortunate the gateway IP address may vary and can only be determinate at runtime.

Here are a few ways to get it:

From the host using docker inspect: docker inspect <container name or ID>. The gateway will be available under NetworkSettings.Networks.Gateway.

From the container you can execute route | awk '/^default/ { print $2 }'

One other possibility is to use --net=host when running your container.
This will run you processes on the same network as your processes on your host. Doing so will make your database accessible from the container on localhost.

Note that using --net=host will not work on Docker for mac/windows.

ContentLicense: CC BY-SA 3.0


问:
Rails: How to pass value from textfield to a partial
How can I easily pass the value I get from the auto_complete textfield to a partial.

```<code><%= text_field_with_auto_complete :participant, :name, {}, {:url => {:controller => "contentcom/discussions", :action => :get_users_for_auto_complete}, :method => :get, :param_name => 'search'} %>
        <%= button_to_function(:OK) do |page|
                page.insert_html :top, :participants, :partial => 'participant', :locals =>  end %>
</code>```

Bye,

Nico

答: Note first that the block of button_to_function (and its partial, of course) is generated server-side, so it has no way to know the value of the autocomplete in the client. You have 2 ways to accomplish what you want: create a RJS action for the auto_complete (if that's possible) or 2) use Javascript/AJAX and connect to the auto_complete URL, get the value and modify the DOM accordingly (also in JS).

ContentLicense: CC BY-SA 2.5

Body:
How can I easily pass the value I get from the auto_complete textfield to a partial.

<%= text_field_with_auto_complete :participant, :name, {}, {:url => {:controller => "contentcom/discussions", :action => :get_users_for_auto_complete}, :method => :get, :param_name => 'search'} %>
        <%= button_to_function(:OK) do |page|
                page.insert_html :top, :participants, :partial => 'participant', :locals =>  end %>

Bye,

Nico


问:
JavaScript animation using 'background-position-x' doesn't work in IE
I'm trying to make an animation using jquery-3.2.1 and the css() function. The animation works on all browsers except for IE, where it just jumps to the last frame on hover, instead of animating them

$(".hi").hover(
  function() {
    $(".hi").animateSteps(-3429, -127, 37);
  },
  function() {
    $(".hi").animateSteps(0, 127, 37);
  }
);

$.fn.animateSteps = function(final, step, duration) {
  if (typeof t != "undefined") clearTimeout(t);
  var self = $(this);
  if (parseInt(self.css('background-position-x')) == final) return;
  self.css('background-position-x', '+=' + step + 'px');
  t = setTimeout(function() {
    self.animateSteps(final, step, duration);
  }, duration);
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.hi {
  width: 127px;
  height: 120px;
  background-image: url("https://image.ibb.co/c1L4LF/logo_sprites.png");
  background-position: 0px;
}</code>```

```

JS FIddle link

Update: There is no errors in console. It is IE11. It's just jumps on first/last position on hover/mouse out.

答:
I have good news and bad news. Bad news, is I really don't know what the issue is. Good new is I found a fix. JS Fiddle

Replacing background-position-x with backgroundPosition seems to do the trick. Some debugging was showing that IE kept showing a null value for background-position-x but would show a backgroundPosition value in the DOM explorer.

Why? I have no idea, everything I've read says that IE should support background-position-x, yet I couldn't get it to. If anyone knows or has a guess as to why this is, please feel free to chime in, as I'm interested in knowing!

$(".hi").hover(
  function() {
    $(".hi").animateSteps(-3429, -127, 37);
  },
  function() {
    $(".hi").animateSteps(0, 127, 37);
  }
);

$.fn.animateSteps = function(final, step, duration) {
  if (typeof t != "undefined") clearTimeout(t);
  var self = $(this);
  if (parseInt(self.css('backgroundPosition')) == final) return;
  // console.log(self.css('background-position-x'));
  console.log(self)
  self.css('backgroundPosition', '+=' + step + 'px');
  t = setTimeout(function() {
    self.animateSteps(final, step, duration);
  }, duration);
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.hi {
  width: 127px;
  height: 120px;
  background-image: url("https://image.ibb.co/c1L4LF/logo_sprites.png");
  background-position: 0px;
  background-position-x: 0px;
}</code>```

```

Body:
I'm trying to make an animation using jquery-3.2.1 and the css() function. The animation works on all browsers except for IE, where it just jumps to the last frame on hover, instead of animating them

$(".hi").hover(
  function() {
    $(".hi").animateSteps(-3429, -127, 37);
  },
  function() {
    $(".hi").animateSteps(0, 127, 37);
  }
);

$.fn.animateSteps = function(final, step, duration) {
  if (typeof t != "undefined") clearTimeout(t);
  var self = $(this);
  if (parseInt(self.css('background-position-x')) == final) return;
  self.css('background-position-x', '+=' + step + 'px');
  t = setTimeout(function() {
    self.animateSteps(final, step, duration);
  }, duration);
}

.hi {
  width: 127px;
  height: 120px;
  background-image: url("https://image.ibb.co/c1L4LF/logo_sprites.png");
  background-position: 0px;
}

JS FIddle link

Update: There is no errors in console. It is IE11. It's just jumps on first/last position on hover/mouse out.

Body:
I have good news and bad news. Bad news, is I really don't know what the issue is. Good new is I found a fix. JS Fiddle

Replacing background-position-x with backgroundPosition seems to do the trick. Some debugging was showing that IE kept showing a null value for background-position-x but would show a backgroundPosition value in the DOM explorer.

Why? I have no idea, everything I've read says that IE should support background-position-x, yet I couldn't get it to. If anyone knows or has a guess as to why this is, please feel free to chime in, as I'm interested in knowing!

$(".hi").hover(
  function() {
    $(".hi").animateSteps(-3429, -127, 37);
  },
  function() {
    $(".hi").animateSteps(0, 127, 37);
  }
);

$.fn.animateSteps = function(final, step, duration) {
  if (typeof t != "undefined") clearTimeout(t);
  var self = $(this);
  if (parseInt(self.css('backgroundPosition')) == final) return;
  // console.log(self.css('background-position-x'));
  console.log(self)
  self.css('backgroundPosition', '+=' + step + 'px');
  t = setTimeout(function() {
    self.animateSteps(final, step, duration);
  }, duration);
}

.hi {
  width: 127px;
  height: 120px;
  background-image: url("https://image.ibb.co/c1L4LF/logo_sprites.png");
  background-position: 0px;
  background-position-x: 0px;
}

<div class="hi"></div>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>


问:
Class inside a class in Python
How can i call a class inside a class in Python? For example:

```<code>class POINT:
    def __init__(self, x, y):
        self.x = x
        self.y = y

class CIRCLE:
    def __init__(self, x, y, radius):
        self.x = x
        self.y = y
        self.radius = radius
</code>```

I want to call POINT class in CIRCLE.
Thanks for answers.

答:
Are you trying to do this?

```<code>class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

class Circle:
    def __init__(self, point, radius):
        self.point = point
        self.radius = radius

c = Circle(Point(2,3), 5)
</code>```

That way, you'll have a class Circle which in its constructor accepts a point (an instance of class Point) and a radius, producing and instance of Circle.

Title: Class inside a class in Python

Body:
How can i call a class inside a class in Python? For example:

class POINT:
    def __init__(self, x, y):
        self.x = x
        self.y = y

class CIRCLE:
    def __init__(self, x, y, radius):
        self.x = x
        self.y = y
        self.radius = radius

I want to call POINT class in CIRCLE.
Thanks for answers.

Body:
Are you trying to do this?

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

class Circle:
    def __init__(self, point, radius):
        self.point = point
        self.radius = radius

c = Circle(Point(2,3), 5)

That way, you'll have a class Circle which in its constructor accepts a point (an instance of class Point) and a radius, producing and instance of Circle.


问:
How to return first 5 objects of Array in Swift?
In Swift, is there a clever way of using the higher order methods on Array to return the 5 first objects?
The obj-c way of doing it was saving an index, and for-loop through the array incrementing index until it was 5 and returning the new array. Is there a way to do this with filter, map or reduce?

答:
With Swift 5, according to your needs, you may choose one of the 6 following Playground codes in order to solve your problem.

#1. Using subscript(_:) subscript

```<code>let array = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L"]
let arraySlice = array[..<5]
//let arraySlice = array[0..<5] // also works
//let arraySlice = array[0...4] // also works
//let arraySlice = array[...4] // also works
let newArray = Array(arraySlice)
print(newArray) // prints: ["A", "B", "C", "D", "E"]
</code>```

#2. Using prefix(_:) method

Complexity: O(1) if the collection conforms to RandomAccessCollection; otherwise, O(k), where k is the number of elements to select from the beginning of the collection.

```<code>let array = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L"]
let arraySlice = array.prefix(5)
let newArray = Array(arraySlice)
print(newArray) // prints: ["A", "B", "C", "D", "E"]
</code>```

Apple states for prefix(_:):

If the maximum length exceeds the number of elements in the collection, the result contains all the elements in the collection.

#3. Using prefix(upTo:) method

Complexity: O(1)

```<code>let array = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L"]
let arraySlice = array.prefix(upTo: 5)
let newArray = Array(arraySlice)
print(newArray) // prints: ["A", "B", "C", "D", "E"]
</code>```

Apple states for prefix(upTo:):

Using the prefix(upTo:) method is equivalent to using a partial half-open range as the collection's subscript. The subscript notation is preferred over prefix(upTo:).

#4. Using prefix(through:) method

```<code>let array = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L"]
let arraySlice = array.prefix(through: 4)
let newArray = Array(arraySlice)
print(newArray) // prints: ["A", "B", "C", "D", "E"]
</code>```

#5. Using removeSubrange(_:) method

Complexity: O(n), where n is the length of the collection.

```<code>var array = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L"]
array.removeSubrange(5...)
print(array) // prints: ["A", "B", "C", "D", "E"]
</code>```

#6. Using dropLast(_:) method

Complexity: O(1) if the collection conforms to RandomAccessCollection; otherwise, O(k), where k is the number of elements to drop.

```<code>let array = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L"]
let distance = array.distance(from: 5, to: array.endIndex)
let arraySlice = array.dropLast(distance)
let newArray = Array(arraySlice)
print(newArray) // prints: ["A", "B", "C", "D", "E"]
</code>```

Body:
With Swift 5, according to your needs, you may choose one of the 6 following Playground codes in order to solve your problem.

#1. Using subscript(_:) subscript

let array = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L"]
let arraySlice = array[..<5]
//let arraySlice = array[0..<5] // also works
//let arraySlice = array[0...4] // also works
//let arraySlice = array[...4] // also works
let newArray = Array(arraySlice)
print(newArray) // prints: ["A", "B", "C", "D", "E"]

#2. Using prefix(_:) method

Complexity: O(1) if the collection conforms to RandomAccessCollection; otherwise, O(k), where k is the number of elements to select from the beginning of the collection.

let array = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L"]
let arraySlice = array.prefix(5)
let newArray = Array(arraySlice)
print(newArray) // prints: ["A", "B", "C", "D", "E"]

Apple states for prefix(_:):

If the maximum length exceeds the number of elements in the collection, the result contains all the elements in the collection.

#3. Using prefix(upTo:) method

Complexity: O(1)

let array = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L"]
let arraySlice = array.prefix(upTo: 5)
let newArray = Array(arraySlice)
print(newArray) // prints: ["A", "B", "C", "D", "E"]

Apple states for prefix(upTo:):

Using the prefix(upTo:) method is equivalent to using a partial half-open range as the collection's subscript. The subscript notation is preferred over prefix(upTo:).

#4. Using prefix(through:) method

let array = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L"]
let arraySlice = array.prefix(through: 4)
let newArray = Array(arraySlice)
print(newArray) // prints: ["A", "B", "C", "D", "E"]

#5. Using removeSubrange(_:) method

Complexity: O(n), where n is the length of the collection.

var array = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L"]
array.removeSubrange(5...)
print(array) // prints: ["A", "B", "C", "D", "E"]

#6. Using dropLast(_:) method

Complexity: O(1) if the collection conforms to RandomAccessCollection; otherwise, O(k), where k is the number of elements to drop.

let array = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L"]
let distance = array.distance(from: 5, to: array.endIndex)
let arraySlice = array.dropLast(distance)
let newArray = Array(arraySlice)
print(newArray) // prints: ["A", "B", "C", "D", "E"]

ContentLicense: CC BY-SA 4.0


问:
How can I color a UIImage in Swift?
I have an image called arrowWhite. I want to colour this image to black.

```<code>func attachDropDownArrow() -> NSMutableAttributedString {
    let image:UIImage = UIImage(named: "arrowWhite.png")!
    let attachment = NSTextAttachment()
    attachment.image = image
    attachment.bounds = CGRectMake(2.25, 2, attachment.image!.size.width - 2.25, attachment.image!.size.height - 2.25)
    let attachmentString = NSAttributedString(attachment: attachment)
    let myString = NSMutableAttributedString(string: NSString(format: "%@", self.privacyOptions[selectedPickerRow]) as String)
    myString.appendAttributedString(attachmentString)
    return myString
}
</code>```

I want to get this image in blackColour.

tintColor is not working...

答:
I have modified the extension found here: Github Gist, for Swift 3 which I have tested in the context of an extension for UIImage.

```<code>func tint(with color: UIColor) -> UIImage
{
   UIGraphicsBeginImageContext(self.size)
   guard let context = UIGraphicsGetCurrentContext() else { return self }

   // flip the image
   context.scaleBy(x: 1.0, y: -1.0)
   context.translateBy(x: 0.0, y: -self.size.height)

   // multiply blend mode
   context.setBlendMode(.multiply)

   let rect = CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height)
   context.clip(to: rect, mask: self.cgImage!)
   color.setFill()
   context.fill(rect)

   // create UIImage
   guard let newImage = UIGraphicsGetImageFromCurrentImageContext() else { return self }
   UIGraphicsEndImageContext()

   return newImage
}
</code>```

Title: How can I color a UIImage in Swift?

Body:
I have an image called arrowWhite. I want to colour this image to black.

func attachDropDownArrow() -> NSMutableAttributedString {
    let image:UIImage = UIImage(named: "arrowWhite.png")!
    let attachment = NSTextAttachment()
    attachment.image = image
    attachment.bounds = CGRectMake(2.25, 2, attachment.image!.size.width - 2.25, attachment.image!.size.height - 2.25)
    let attachmentString = NSAttributedString(attachment: attachment)
    let myString = NSMutableAttributedString(string: NSString(format: "%@", self.privacyOptions[selectedPickerRow]) as String)
    myString.appendAttributedString(attachmentString)
    return myString
}

I want to get this image in blackColour.

tintColor is not working...

Body:
I have modified the extension found here: Github Gist, for Swift 3 which I have tested in the context of an extension for UIImage.

func tint(with color: UIColor) -> UIImage
{
   UIGraphicsBeginImageContext(self.size)
   guard let context = UIGraphicsGetCurrentContext() else { return self }

   // flip the image
   context.scaleBy(x: 1.0, y: -1.0)
   context.translateBy(x: 0.0, y: -self.size.height)

   // multiply blend mode
   context.setBlendMode(.multiply)

   let rect = CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height)
   context.clip(to: rect, mask: self.cgImage!)
   color.setFill()
   context.fill(rect)

   // create UIImage
   guard let newImage = UIGraphicsGetImageFromCurrentImageContext() else { return self }
   UIGraphicsEndImageContext()

   return newImage
}


答: Do you want to define the circle's center position using the POINT class? If this is what you want, you throw away the self.x/self.y inside CIRCLE and do self.center = POINT(x,y).

Title: Class inside a class in Python


问:
Stay open menu after checked item
I have created a menu in which dynamically added submenus and several items with setCheckable. I would like to stay open menu when I click on point 1/2/3.

```<code>SubMenu subMenu = menu.addSubMenu(Menu.NONE, Menu.NONE, 1101, "select");
subMenu.add("point 1").setCheckable(true);
subMenu.add("point 2").setCheckable(true);
subMenu.add("point 3").setCheckable(true);
</code>```

Now, when I choose a position, the menu is hidden.

答:
I don't know exactly how to keep main menu whiling selecting sub menu. But i have an alternative idea.

You can call menu click event Programatically once the sub menu clicked. So your main menu will get pop up once the sub menu clicked

Code to call main menu Programatically

MenuItem actionRestart = (MenuItem) findViewById(R.id.action_restart);
onOptionsItemSelected(actionRestart);

Hope it will hep you...

Title: Stay open menu after checked item

Body:
I have created a menu in which dynamically added submenus and several items with setCheckable. I would like to stay open menu when I click on point 1/2/3.

SubMenu subMenu = menu.addSubMenu(Menu.NONE, Menu.NONE, 1101, "select");
subMenu.add("point 1").setCheckable(true);
subMenu.add("point 2").setCheckable(true);
subMenu.add("point 3").setCheckable(true);

Now, when I choose a position, the menu is hidden.


问:
Does python-requests support HTTP2 and asynchronous calls?
I would like to use python-requests in my server to send PUSH notification to Apple push server, my questions:

Does python-requests support asynchronous calls ?

Does python-request support HTTP2 ?

Thanks

答:
It doesn't support HTTP/2 now (Release v2.18.1).
As in the doc (http://docs.python-requests.org/en/master/):

Requests allows you to send organic, grass-fed HTTP/1.1 requests, without the need for manual labor.

But you can try Hyper if you need to send HTTP/2 requests:
https://hyper.readthedocs.io/en/latest/.

hyper supports Python 3.4 and Python 2.7.9, and can speak HTTP/2 and HTTP/1.1.


问:
Create matrix from vector's rolling window
I would like to do something like this question but in R.

Given:

```<code>> my_vector
[1] 1 2 3 4 5 6
</code>```

And window_size = 3, I would like to get the following matrix:

```<code>> my_matrix
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    2    3    4
[3,]    3    4    5
[4,]    4    5    6
</code>```

As you can see, every row of the matrix is a window of the vector.

Is there any efficient way to do it in R without for loop?

答:
This can be done using rollapply in zoo:

```<code>library(zoo)

rollapply(my_vector, 3, c)
</code>```

giving:

```<code>     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    2    3    4
[3,]    3    4    5
[4,]    4    5    6
</code>```

Note: The input used above, in reproducible form, is:

```<code>my_vector <- 1:6
</code>```

Body:
I would like to do something like this question but in R.

Given:

> my_vector
[1] 1 2 3 4 5 6

And window_size = 3, I would like to get the following matrix:

> my_matrix
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    2    3    4
[3,]    3    4    5
[4,]    4    5    6

As you can see, every row of the matrix is a window of the vector.

Is there any efficient way to do it in R without for loop?

Body:
This can be done using rollapply in zoo:

library(zoo)

rollapply(my_vector, 3, c)

giving:

     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    2    3    4
[3,]    3    4    5
[4,]    4    5    6

Note: The input used above, in reproducible form, is:

my_vector <- 1:6


问:
HTML Attachments opened in Apple device not showing some images
I am wondering if someone can help me with a problem I am encountering with iPhone/iPad. I have an email the generates a report as an HTML attachment. In that HTML attachment, there are two images. One is a static image that pulls down a logo using a normal HTML img tag.

The other is dynamic. It also uses the normal HTML img tag, however it calls out to a web api with some information identifying the user.

```<code><img src="http://MyApiServerName.com/api/User/{id}/{OtherParm}" >
</code>```

The Web API uses information on the user to return appropriate images to them. For some reason the dynamic image does not show up with the attachment is opened on an iPad/iPhone.

The image works just fine when the attachment is opened from a computer. I thought maybe something might be blocking images, however then I would expect the static image not to display as well. I verified that the "Load Remote Images" setting is turned on.

I am at a loss here. Is there something with iOS that prevents dynamically generated images from showing in HTML attachments?

Thanks

答:
Ok, I can't explain why the above is not working, but I did find something that does. Instead of using the following URL

```<code><img src="http://MyApiServerName.com/api/User/{id}/{OtherParm}" >
</code>```

use

```<code><img src="http://MyApiServerName.com/api/User/{id}/{OtherParm.jpg}/" >
</code>```

The final param needs to end with ".jpg/". If the slash is not there, you will get a 404 error.

Then in the API method, you simply strip off the .jpg part of "OtherParm" to get the intended value for "OtherParm".

Body:
I am wondering if someone can help me with a problem I am encountering with iPhone/iPad. I have an email the generates a report as an HTML attachment. In that HTML attachment, there are two images. One is a static image that pulls down a logo using a normal HTML img tag.

The other is dynamic. It also uses the normal HTML img tag, however it calls out to a web api with some information identifying the user.

The Web API uses information on the user to return appropriate images to them. For some reason the dynamic image does not show up with the attachment is opened on an iPad/iPhone.

The image works just fine when the attachment is opened from a computer. I thought maybe something might be blocking images, however then I would expect the static image not to display as well. I verified that the "Load Remote Images" setting is turned on.

I am at a loss here. Is there something with iOS that prevents dynamically generated images from showing in HTML attachments?

Thanks

Body:
Ok, I can't explain why the above is not working, but I did find something that does. Instead of using the following URL

<img src="http://MyApiServerName.com/api/User/{id}/{OtherParm}" >

use

<img src="http://MyApiServerName.com/api/User/{id}/{OtherParm.jpg}/" >

The final param needs to end with ".jpg/". If the slash is not there, you will get a 404 error.

Then in the API method, you simply strip off the .jpg part of "OtherParm" to get the intended value for "OtherParm".


问:
Informix server with SQLI protocol and DRDA Protocol at same time
In order to make IBM Data Server client to connect to my Informix server, I need to configure it to use the DRDA protocol.
My question is: will I be able to keep the old SQLI protocol too after configuring the DRDA protocol?</p>

答: Yes. You need to make sure both SQLI and DRDA protocols are configured in the ONCONFIG file and the SQLHOSTS file. You'll also need to make sure that you are using different port numbers for each of the protocol listeners.</p>


问:
How to set Datepicker default index is string value
I want to show datepicker default index value is string but I am not able to do that. Please suggest any idea. Thanks in advance.

I want to show picker like this:

答:
Here is an example how to do it in ViewCell. You can use similar idea with View</p>

```<code>   public class TimePickerInCellPage : ContentPage
    {
        private ListView _listView;

        public TimePickerInCellPage()
        {
            _listView = new ListView
            {
                RowHeight = 80,
                SeparatorColor = Color.Blue,
                SeparatorVisibility = SeparatorVisibility.Default
            };

            _listView.ItemsSource = new List<TaskTime>() {
                 new TaskTime { Id=1, StartTime=TimeSpan.FromHours(3) } ,
                 new TaskTime { Id=1, StartTime=TimeSpan.FromHours(5) } ,
                 new TaskTime { Id=1, StartTime=TimeSpan.FromHours(7) } ,
            };
            _listView.ItemTemplate = new DataTemplate(typeof(MyCell));

            Content = new StackLayout
            {
                VerticalOptions = LayoutOptions.FillAndExpand,
                Children = { _listView }
            };
        }

    }

    public class TaskTime
    {
        public int Id { get; set; }
        public string Task { get; set; }
        public TimeSpan StartTime { get; set; }
    }

    class MyCell : ViewCell
    {
        private readonly DatePicker _myTimePicker;
        //private readonly TimePicker _myTimePicker;
        public MyCell()
        {
            //_myTimePicker = new TimePicker()
            _myTimePicker = new DatePicker()
            {
                HorizontalOptions = LayoutOptions.EndAndExpand
            };
            //_myTimePicker.Format = "HH:mm:ss";
            _myTimePicker.Format = "dd:MM:yy HH:mm:ss";

            _myTimePicker.SetBinding(TimePicker.TimeProperty, "StartTime");
            _myTimePicker.PropertyChanged += MyTimePicker_PropertyChanged;
            //_myTimePicker.Focused += _myTimePicker_Focused;

            var viewLayout = new StackLayout()
            {
                HorizontalOptions = LayoutOptions.StartAndExpand,
                Orientation = StackOrientation.Horizontal,
                Padding = new Thickness(20),
                Children = { _myTimePicker }
            };
            View = viewLayout;
        }

        bool firstTimeSet; //set when initial binding happens
        //private void _myTimePicker_Focused(object sender, FocusEventArgs e)
        //{
        //    firstTimeSet=true;
        //}

        private void MyTimePicker_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            //if (e.PropertyName == TimePicker.TimeProperty.PropertyName)
            if (e.PropertyName == DatePicker.DateProperty.PropertyName)
            {
                if (!firstTimeSet)
                    firstTimeSet = true;
                else
                {
                    int x = 0;
                    string s = _myTimePicker.Date.ToString("dd/MM/yy HH:mm:ss");
                }
            }
        }
    }
</code>```

Body:
Here is an example how to do it in ViewCell. You can use similar idea with View

   public class TimePickerInCellPage : ContentPage
    {
        private ListView _listView;

        public TimePickerInCellPage()
        {
            _listView = new ListView
            {
                RowHeight = 80,
                SeparatorColor = Color.Blue,
                SeparatorVisibility = SeparatorVisibility.Default
            };

            _listView.ItemsSource = new List<TaskTime>() {
                 new TaskTime { Id=1, StartTime=TimeSpan.FromHours(3) } ,
                 new TaskTime { Id=1, StartTime=TimeSpan.FromHours(5) } ,
                 new TaskTime { Id=1, StartTime=TimeSpan.FromHours(7) } ,
            };
            _listView.ItemTemplate = new DataTemplate(typeof(MyCell));

            Content = new StackLayout
            {
                VerticalOptions = LayoutOptions.FillAndExpand,
                Children = { _listView }
            };
        }

    }

    public class TaskTime
    {
        public int Id { get; set; }
        public string Task { get; set; }
        public TimeSpan StartTime { get; set; }
    }

    class MyCell : ViewCell
    {
        private readonly DatePicker _myTimePicker;
        //private readonly TimePicker _myTimePicker;
        public MyCell()
        {
            //_myTimePicker = new TimePicker()
            _myTimePicker = new DatePicker()
            {
                HorizontalOptions = LayoutOptions.EndAndExpand
            };
            //_myTimePicker.Format = "HH:mm:ss";
            _myTimePicker.Format = "dd:MM:yy HH:mm:ss";

            _myTimePicker.SetBinding(TimePicker.TimeProperty, "StartTime");
            _myTimePicker.PropertyChanged += MyTimePicker_PropertyChanged;
            //_myTimePicker.Focused += _myTimePicker_Focused;

            var viewLayout = new StackLayout()
            {
                HorizontalOptions = LayoutOptions.StartAndExpand,
                Orientation = StackOrientation.Horizontal,
                Padding = new Thickness(20),
                Children = { _myTimePicker }
            };
            View = viewLayout;
        }

        bool firstTimeSet; //set when initial binding happens
        //private void _myTimePicker_Focused(object sender, FocusEventArgs e)
        //{
        //    firstTimeSet=true;
        //}

        private void MyTimePicker_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            //if (e.PropertyName == TimePicker.TimeProperty.PropertyName)
            if (e.PropertyName == DatePicker.DateProperty.PropertyName)
            {
                if (!firstTimeSet)
                    firstTimeSet = true;
                else
                {
                    int x = 0;
                    string s = _myTimePicker.Date.ToString("dd/MM/yy HH:mm:ss");
                }
            }
        }
    }


问:
Python (2.7.13) - I have a string that looks like an array
I'm trapping an error but cannot extract what I want out of the returned message.
Here's the code:

```<code>  except purestorage.PureHTTPError as response:
     print "LUN Creation failed:"

     print dir(response)
     print "args:{}".format(response.args)
     print "code:{}".format(response.code)
     print "headers:{}".format(response.headers)
     print "message:{}".format(response.message)
     print "reason:{}".format(response.reason)
     print "rest_version:{}".format(response.rest_version)
     print "target:{}".format(response.target )
     print "text:{}".format(response.text)
</code>```

Here's the output:

```<code>LUN Creation failed:
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__getitem__', '__getslice__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__', '__unicode__', '__weakref__', 'args', 'code', 'headers', 'message', 'reason', 'rest_version', 'target', 'text']
args:()
code:400
headers:{'Content-Length': '113', 'Set-Cookie': 'session=....; Expires=Wed, 05-Jul-2017 16:28:26 GMT; HttpOnly; Path=/', 'Server': 'nginx/1.4.6 (Ubuntu)', 'Connection': 'keep-alive', 'Date': 'Wed, 05 Jul 2017 15:58:26 GMT', 'Content-Type': 'application/json'}
message:
reason:BAD REQUEST
rest_version:1.8
target:array1
text:[{"pure_err_key": "err.friendly", "code": 0, "ctx": "lun-name", "pure_err_code": 1, "msg": "Volume already exists."}]
</code>```

I want to pull out msg and pure_err_code but the text isn't a list.
The [{ ... }] is confusing me.  The response.text[0] is [ and response.text['msg'] throws an index error so this is acting like a string (afaIk).

答:
You have JSON data. The response headers even tell you this:

```<code>'Content-Type': 'application/json'
</code>```

Use the json module to decode this:

```<code>error_info = json.loads(response.text)
</code>```

error_info is then a list containing a single dictionary in this case (suggesting there could be 0 or more results). You could loop, or assume that there is always 1 result, at which point you can use [0] to extract just that one dictionary

```<code>print(error_info[0]['pure_err__key'])
print(error_info[0]['msg'])
</code>```

Body:
I'm trapping an error but cannot extract what I want out of the returned message.
Here's the code:

  except purestorage.PureHTTPError as response:
     print "LUN Creation failed:"

     print dir(response)
     print "args:{}".format(response.args)
     print "code:{}".format(response.code)
     print "headers:{}".format(response.headers)
     print "message:{}".format(response.message)
     print "reason:{}".format(response.reason)
     print "rest_version:{}".format(response.rest_version)
     print "target:{}".format(response.target )
     print "text:{}".format(response.text)

Here's the output:

LUN Creation failed:
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__getitem__', '__getslice__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__', '__unicode__', '__weakref__', 'args', 'code', 'headers', 'message', 'reason', 'rest_version', 'target', 'text']
args:()
code:400
headers:{'Content-Length': '113', 'Set-Cookie': 'session=....; Expires=Wed, 05-Jul-2017 16:28:26 GMT; HttpOnly; Path=/', 'Server': 'nginx/1.4.6 (Ubuntu)', 'Connection': 'keep-alive', 'Date': 'Wed, 05 Jul 2017 15:58:26 GMT', 'Content-Type': 'application/json'}
message:
reason:BAD REQUEST
rest_version:1.8
target:array1
text:[{"pure_err_key": "err.friendly", "code": 0, "ctx": "lun-name", "pure_err_code": 1, "msg": "Volume already exists."}]

I want to pull out msg and pure_err_code but the text isn't a list.
The [{ ... }] is confusing me.  The response.text[0] is [ and response.text['msg'] throws an index error so this is acting like a string (afaIk).

Body:
You have JSON data. The response headers even tell you this:

'Content-Type': 'application/json'

Use the json module to decode this:

error_info = json.loads(response.text)

error_info is then a list containing a single dictionary in this case (suggesting there could be 0 or more results). You could loop, or assume that there is always 1 result, at which point you can use [0] to extract just that one dictionary

print(error_info[0]['pure_err__key'])
print(error_info[0]['msg'])


问:
Xamarin button text change in code behind
Here my code sample

```<code>  <controls:SwitchboardButton Grid.Row="0"   Grid.Column="0" Label="Test">
    <controls:SwitchboardButton.GestureRecognizers>
      <TapGestureRecognizer   Tapped="CameraButtonTapped" />
    </controls:SwitchboardButton.GestureRecognizers>
  </controls:SwitchboardButton>
</code>```

This is code behind

```<code>    public async void CameraButtonTapped(object sender, EventArgs args)
    {
        await Navigation.PushAsync(new TensePage());
    }
</code>```

i want to know how to change button text when click button. i want to do this Code behind

答:
assign a name to your button

```<code><controls:SwitchboardButton x:Name="btnSwitch" Grid.Row="0"   Grid.Column="0" Label="Test">
</code>```

then in the code behind:

```<code>public async void CameraButtonTapped(object sender, EventArgs args)
{
    btnSwitch.Text = "Some New Text";

    await Navigation.PushAsync(new TensePage());
}
</code>```

Body:
Here my code sample

  <controls:SwitchboardButton Grid.Row="0"   Grid.Column="0" Label="Test">
    <controls:SwitchboardButton.GestureRecognizers>
      <TapGestureRecognizer   Tapped="CameraButtonTapped" />
    </controls:SwitchboardButton.GestureRecognizers>
  </controls:SwitchboardButton>

This is code behind

    public async void CameraButtonTapped(object sender, EventArgs args)
    {
        await Navigation.PushAsync(new TensePage());
    }

i want to know how to change button text when click button. i want to do this Code behind

Body:
assign a name to your button

<controls:SwitchboardButton x:Name="btnSwitch" Grid.Row="0"   Grid.Column="0" Label="Test">

then in the code behind:

public async void CameraButtonTapped(object sender, EventArgs args)
{
    btnSwitch.Text = "Some New Text";

    await Navigation.PushAsync(new TensePage());
}


问:
Retrofit2 in Android Fragment how to implement correctly?
I'm using Retrofit 2 to consume an API. I have a service (interface) which returns a list:

```<code>@GET("atenciones")
Call<List<Atencion>> getAtenciones(@Query("medico_id") int id, @Query("date1") String date1, @Query("date2") String date2)
</code>```

Where should I do the request? In the MainActivity which contains the Fragment and send the result list using Bundle? or should do the request in the Fragment? this is a list not a single object. Which is the correct way?

Edit

Try to call retrofit in Fragment, this is my code:

```<code>public class FragmentRendicion extends Fragment {

private LinearLayoutManager layoutManager;
View rootView;
APIService api;

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

    rootView = inflater.inflate(R.layout.fragment_rendicion, container, false);
    api= ApiUtils.getAPIService();
        getAtenciones();
    return rootView;
}

private void getAtenciones() {
//using static parameters
    Call<List<Atencion>> call= api.getAtenciones(293,"2014-10-13","2014-10-13");
    call.enqueue(new Callback<List<Atencion>>() {
        @Override
        public void onResponse(Call<List<Atencion>> call, Response<List<Atencion>> response) {
            System.out.println("estamos aquiiii "+response.message());
            List<Atencion> atenciones= response.body();
            layoutManager= new LinearLayoutManager(getActivity());
            RecyclerView recycler= (RecyclerView)rootView.findViewById(R.id.rvRendicion);
            recycler.setLayoutManager(layoutManager);
            RvRendicionAdapter rvAdapter= new RvRendicionAdapter(atenciones);
            recycler.setAdapter(rvAdapter);

        }

        @Override
        public void onFailure(Call<List<Atencion>> call, Throwable t) {
            System.out.println("FALLOOOOO:  "+t.getMessage());//HERE RETUNRS NULL
        }
    });

}
}
</code>```

Can someone tell me is if it correct way to call retrofit2 in fragment?

答:
It depends on the structure of your code but since you are using fragments my best guess is you should do it in the Fragment.

In the onResponseOK of the Retrofit call you will have something like this:

```<code>@Override
public void onResponseOK(Response<List<Atencion>> response) {
    ...
    //access data here
}
</code>```

In the callback you get your list. Pass the list to the adapter of your (I suppose) Recycler/Listview. Access the list like this:

```<code>List<Atencion> myList = response.body();
</code>```

Body:
I'm using Retrofit 2 to consume an API. I have a service (interface) which returns a list:

@GET("atenciones")
Call<List<Atencion>> getAtenciones(@Query("medico_id") int id, @Query("date1") String date1, @Query("date2") String date2)

Where should I do the request? In the MainActivity which contains the Fragment and send the result list using Bundle? or should do the request in the Fragment? this is a list not a single object. Which is the correct way?

Edit

Try to call retrofit in Fragment, this is my code:

public class FragmentRendicion extends Fragment {

private LinearLayoutManager layoutManager;
View rootView;
APIService api;

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

    rootView = inflater.inflate(R.layout.fragment_rendicion, container, false);
    api= ApiUtils.getAPIService();
        getAtenciones();
    return rootView;
}

private void getAtenciones() {
//using static parameters
    Call<List<Atencion>> call= api.getAtenciones(293,"2014-10-13","2014-10-13");
    call.enqueue(new Callback<List<Atencion>>() {
        @Override
        public void onResponse(Call<List<Atencion>> call, Response<List<Atencion>> response) {
            System.out.println("estamos aquiiii "+response.message());
            List<Atencion> atenciones= response.body();
            layoutManager= new LinearLayoutManager(getActivity());
            RecyclerView recycler= (RecyclerView)rootView.findViewById(R.id.rvRendicion);
            recycler.setLayoutManager(layoutManager);
            RvRendicionAdapter rvAdapter= new RvRendicionAdapter(atenciones);
            recycler.setAdapter(rvAdapter);

        }

        @Override
        public void onFailure(Call<List<Atencion>> call, Throwable t) {
            System.out.println("FALLOOOOO:  "+t.getMessage());//HERE RETUNRS NULL
        }
    });

}
}

Can someone tell me is if it correct way to call retrofit2 in fragment?

Body:
It depends on the structure of your code but since you are using fragments my best guess is you should do it in the Fragment.

In the onResponseOK of the Retrofit call you will have something like this:

@Override
public void onResponseOK(Response<List<Atencion>> response) {
    ...
    //access data here
}

In the callback you get your list. Pass the list to the adapter of your (I suppose) Recycler/Listview. Access the list like this:

List<Atencion> myList = response.body();


问:
How can I create Min stl priority_queue?
The default stl priority queue is a Max one (Top function returns the largest element).

Say, for simplicity, that it is a priority queue of int values.

答:
We can do this using several ways.

Using template comparator parameter

```<code>    int main()
    {
      priority_queue<int, vector<int>, greater<int> > pq;

      pq.push(40);
      pq.push(320);
      pq.push(42);
      pq.push(65);
      pq.push(12);

      cout<<pq.top()<<endl;
      return 0;
    }
</code>```

Using used defined compartor class

```<code>     struct comp
     {
        bool operator () (int lhs, int rhs)
        {
           return lhs > rhs;
        }
     };

    int main()
    {
       priority_queue<int, vector<int>, comp> pq;

       pq.push(40);
       pq.push(320);
       pq.push(42);
       pq.push(65);
       pq.push(12);

       cout<<pq.top()<<endl;

       return 0;
    }
</code>```

Body:
We can do this using several ways.

Using template comparator parameter

    int main()
    {
      priority_queue<int, vector<int>, greater<int> > pq;

      pq.push(40);
      pq.push(320);
      pq.push(42);
      pq.push(65);
      pq.push(12);

      cout<<pq.top()<<endl;
      return 0;
    }

Using used defined compartor class

     struct comp
     {
        bool operator () (int lhs, int rhs)
        {
           return lhs > rhs;
        }
     };

    int main()
    {
       priority_queue<int, vector<int>, comp> pq;

       pq.push(40);
       pq.push(320);
       pq.push(42);
       pq.push(65);
       pq.push(12);

       cout<<pq.top()<<endl;

       return 0;
    }


问:
Putting the mysql statement in django python shell
guys. I hope that someone of you can help me in that problem.

How can I express this MySQL statement:

```<code>SELECT AES_DECRYPT(column, (SELECT AES_DECRYPT(column2, 'aeskey') FROM table2)) FROM table WHERE id=1;
</code>```

in django python shell (you know, with interactive shell)?

Thank you, have a good day.

答:
Django allows you to create your own database functions

```<code>class AESDecrypt(Func):

    function = 'AES_DECRYPT'
</code>```

If you do not override the template attribute then when this function is used it generates SQL like AES_DECRYPT(arg1, arg2). This can then be used like so (I haven't tested this so may need some tweaking)

```<code>MyModel.objects.filter(
    id=1
).annotate(
    decrypted_aes_key=AESDecrypt('column2', key)
).annotate(
    decrypted_column=AESDecrypt('column', F('decrypted_aes_key'))
).values(
    'decrypted_column'
)
</code>```

Body:
guys. I hope that someone of you can help me in that problem.

How can I express this MySQL statement:

SELECT AES_DECRYPT(column, (SELECT AES_DECRYPT(column2, 'aeskey') FROM table2)) FROM table WHERE id=1;

in django python shell (you know, with interactive shell)?

Thank you, have a good day.

Body:
Django allows you to create your own database functions

class AESDecrypt(Func):

    function = 'AES_DECRYPT'

If you do not override the template attribute then when this function is used it generates SQL like AES_DECRYPT(arg1, arg2). This can then be used like so (I haven't tested this so may need some tweaking)

MyModel.objects.filter(
    id=1
).annotate(
    decrypted_aes_key=AESDecrypt('column2', key)
).annotate(
    decrypted_column=AESDecrypt('column', F('decrypted_aes_key'))
).values(
    'decrypted_column'
)


问:
How can I implement single table inheritance using Laravel's Eloquent?
Currently I have a model class named Post.

```<code>class Post extends Eloquent {

    protected $table = 'posts';
    protected $fillable = array('user_id', 'title', 'description', 'views');

    /*
     * Relationships
     */

    public function user()
    {
        return $this->belongsTo('User');
    }

    public function tags()
    {
        return $this->belongsToMany('Tag', 'post_tags');
    }

    public function reactions()
    {
        return $this->hasMany('Reaction');
    }

    public function votes()
    {
        return $this->hasMany('PostVote');
    }

    //Scopes and functions...
}
</code>```

I would like to divide posts into two different types; articles and questions. I thought the best way to do this is by inheritance, so Article and Question would extend Post. What is the best way to do this and where to start?

答:
from Laravel 5.2, Global Scope is available:

```<code>class Article extends Post
{
    protected $table = 'posts';

    protected static function boot()
    {
        parent::boot();

        static::addGlobalScope('article', function (Builder $builder) {
            $builder->where('type', 'article');
        });

        static::creating(function ($article) {
            $article->type = 'article'
        });
    }
}
</code>```

where type = 'article' is added to all query of Article just like SoftDeletes.

```<code>>>> App\Article::where('id', 1)->toSql()
=> "select * from `posts` where `id` = ? and `type` = ?"
</code>```

Actually laravel provide SoftDeletes trait using this feature.

Body:
Currently I have a model class named Post.

class Post extends Eloquent {

    protected $table = 'posts';
    protected $fillable = array('user_id', 'title', 'description', 'views');

    /*
     * Relationships
     */

    public function user()
    {
        return $this->belongsTo('User');
    }

    public function tags()
    {
        return $this->belongsToMany('Tag', 'post_tags');
    }

    public function reactions()
    {
        return $this->hasMany('Reaction');
    }

    public function votes()
    {
        return $this->hasMany('PostVote');
    }

    //Scopes and functions...
}

I would like to divide posts into two different types; articles and questions. I thought the best way to do this is by inheritance, so Article and Question would extend Post. What is the best way to do this and where to start?

Body:
from Laravel 5.2, Global Scope is available:

class Article extends Post
{
    protected $table = 'posts';

    protected static function boot()
    {
        parent::boot();

        static::addGlobalScope('article', function (Builder $builder) {
            $builder->where('type', 'article');
        });

        static::creating(function ($article) {
            $article->type = 'article'
        });
    }
}

where type = 'article' is added to all query of Article just like SoftDeletes.

>>> App\Article::where('id', 1)->toSql()
=> "select * from `posts` where `id` = ? and `type` = ?"

Actually laravel provide SoftDeletes trait using this feature.


问:
Programmatically 'unselect' a jQuery UI selectable widget
Is there a way to programmatically 'unselect' any and all selected elements for a given $("#selectable").selectable() widget?

答:
The following command works at http://jqueryui.com/demos/selectable/

```<code>$('#selectable .ui-selected').removeClass('ui-selected')
</code>```

Since a class's existence defines if an item is selected, simply removing the item will deselect it.

Note, you can also take advantage of toggleClass and addClass functions.

EDIT:

Try this too: $('#selectable').trigger('unselected'). That might also trigger all the css changes as well, and this way the unselected event also gets triggered for whatever else may be hooked to it.

Body:
The following command works at http://jqueryui.com/demos/selectable/

$('#selectable .ui-selected').removeClass('ui-selected')

Since a class's existence defines if an item is selected, simply removing the item will deselect it.

Note, you can also take advantage of toggleClass and addClass functions.

EDIT:

Try this too: $('#selectable').trigger('unselected'). That might also trigger all the css changes as well, and this way the unselected event also gets triggered for whatever else may be hooked to it.


问:
How can I pass build args with a remote image in docker-compose.yml?
I would like to pull a remote image from a private registry. The image's dockerfile contains some args whose values would be populated via docker-compose.yml. For example:

```<code>version: '3.0'

services:
    api:
        image: remoteApiImage
    web:
        image: remoteWebImage
        build:
            args:
                baseurl: http://remoteApiImage:80
</code>```

Currently, this does not work as build requires a context. However, if I set a context, it expects a local Dockerfile. Even setting to . without a local Dockerfile will pull the remote image, but the build args are not passed properly.

Is this possible?

Note: I am using Windows Server 2016 containers. Not sure that is relevant to the issue.

答:
As johnharris85 comment suggests, what you are trying to do is not possible. You cannot pull and image and then rebuild it (without the Dockerfile).

If you are trying to specify arguments to an image then you would d this via environment variables. Otherwise, if you have the sources Dockerfile for the image, you can use the ARG function to specify arguments while rebuilding it yourself.

build and image in the docker-compose.yml context are mutually exclusive.

Body:
I would like to pull a remote image from a private registry. The image's dockerfile contains some args whose values would be populated via docker-compose.yml. For example:

version: '3.0'

services:
    api:
        image: remoteApiImage
    web:
        image: remoteWebImage
        build:
            args:
                baseurl: http://remoteApiImage:80

Currently, this does not work as build requires a context. However, if I set a context, it expects a local Dockerfile. Even setting to . without a local Dockerfile will pull the remote image, but the build args are not passed properly.

Is this possible?

Note: I am using Windows Server 2016 containers. Not sure that is relevant to the issue.


答:
It seems that your response.text is a JSON, so first parse it and then access your data:

```<code>import json

data = json.loads(response.text)
print(data[0]["pure_err_code"])
print(data[0]["msg"])
# etc.
</code>```

Title: Python (2.7.13) - I have a string that looks like an array

Body:
It seems that your response.text is a JSON, so first parse it and then access your data:

import json

data = json.loads(response.text)
print(data[0]["pure_err_code"])
print(data[0]["msg"])
# etc.


问:
Split a list in several files scala
I have the following list,

```<code>10,44,22
10,47,12
15,38,3
15,41,30
16,44,15
16,47,18
22,38,21
22,41,42
34,44,40
34,47,36
40,38,39
40,41,42
45,38,27
45,41,30
46,44,45
46,47,48
</code>```

Then I am creating one file with it is content with the following code:

```<code>  val fstream:FileWriter = new FileWriter("patSPO.csv")
  var out:BufferedWriter = new BufferedWriter(fstream)

  val sl = listSPO.sortBy(l => (l.sub, l.pre))
  for ( a <- 0 to listSPO.size-1){
    out.write(sl(a).sub.toString+","+sl(a).pre.toString+","+sl(a).obj.toString+"\n")
  }
  out.close()
</code>```

However I want to divide the content in a n files, then I try the following for 4 files:

```<code>  val fstream:FileWriter = new FileWriter("patSPO.csv")
  val fstream1:FileWriter = new FileWriter("patSPO1.csv")
  val fstream2:FileWriter = new FileWriter("patSPO2.csv")
  val fstream3:FileWriter = new FileWriter("patSPO3.csv")
  val fstream4:FileWriter = new FileWriter("patSPO4.csv")
  var out:BufferedWriter = new BufferedWriter(fstream)
  var out1:BufferedWriter = new BufferedWriter(fstream1)
  var out2:BufferedWriter = new BufferedWriter(fstream2)
  var out3:BufferedWriter = new BufferedWriter(fstream3)
  var out4:BufferedWriter = new BufferedWriter(fstream4)
  val b :Int = listSPO.size/4
  val sl = listSPO.sortBy(l => (l.sub, l.pre))
  for ( a <- 0 to listSPO.size-1){
    out.write(sl(a).sub.toString+","+sl(a).pre.toString+","+sl(a).obj.toString+"\n")
  }
  for ( a <- 0 to b-1){
    out1.write(sl(a).sub.toString+","+sl(a).pre.toString+","+sl(a).obj.toString+"\n")
  }
  for ( a <- b to (b*2)-1){
    out2.write(sl(a).sub.toString+","+sl(a).pre.toString+","+sl(a).obj.toString+"\n")
  }
  for ( a <- b*2 to (b*3)-1){
    out3.write(sl(a).sub.toString+","+sl(a).pre.toString+","+sl(a).obj.toString+"\n")
  }
  for ( a <- b*3 to (b*4)-1){
    out4.write(sl(a).sub.toString+","+sl(a).pre.toString+","+sl(a).obj.toString+"\n")
  }

  out.close()
  out1.close()
  out2.close()
  out3.close()
  out4.close()
</code>```

Then my question is if exist a general code where I put the number of files to generate, for example 32, and not to write 32 times the out, the for and the fstream?

答:
Assuming the objects in the list have this type (otherwise, relpace SPO in the below code with your type):

```<code>case class SPO(sub: Int, pre: Int, obj: Int)
</code>```

This should do it:

```<code>val sl = listSPO.sortBy(l => (l.sub, l.pre))

val files = 5 // whatever number you want

// helper function to write a single list - similar to your implementation but shorter
def writeListToFile(name: String, list: List[SPO]): Unit = {
  val writer = new BufferedWriter(new FileWriter(name))
  list.foreach(spo => writer.write(s"${spo.sub},${spo.pre},${spo.obj}\n"))
  writer.close()
}

sl.grouped(sl.size / files) // split into sublists
  .zipWithIndex             // add index of sublists for file name
  .foreach {
    case (sublist, 0) => writeListToFile(s"pasSPO.csv", sublist) // if indeed you want the first file name NOT to include the index
    case (sublist, index) => writeListToFile(s"pasSPO$index.csv", sublist)
  }
</code>```

Title: Split a list in several files scala

Body:
I have the following list,

10,44,22
10,47,12
15,38,3
15,41,30
16,44,15
16,47,18
22,38,21
22,41,42
34,44,40
34,47,36
40,38,39
40,41,42
45,38,27
45,41,30
46,44,45
46,47,48

Then I am creating one file with it is content with the following code:

  val fstream:FileWriter = new FileWriter("patSPO.csv")
  var out:BufferedWriter = new BufferedWriter(fstream)

  val sl = listSPO.sortBy(l => (l.sub, l.pre))
  for ( a <- 0 to listSPO.size-1){
    out.write(sl(a).sub.toString+","+sl(a).pre.toString+","+sl(a).obj.toString+"\n")
  }
  out.close()

However I want to divide the content in a n files, then I try the following for 4 files:

  val fstream:FileWriter = new FileWriter("patSPO.csv")
  val fstream1:FileWriter = new FileWriter("patSPO1.csv")
  val fstream2:FileWriter = new FileWriter("patSPO2.csv")
  val fstream3:FileWriter = new FileWriter("patSPO3.csv")
  val fstream4:FileWriter = new FileWriter("patSPO4.csv")
  var out:BufferedWriter = new BufferedWriter(fstream)
  var out1:BufferedWriter = new BufferedWriter(fstream1)
  var out2:BufferedWriter = new BufferedWriter(fstream2)
  var out3:BufferedWriter = new BufferedWriter(fstream3)
  var out4:BufferedWriter = new BufferedWriter(fstream4)
  val b :Int = listSPO.size/4
  val sl = listSPO.sortBy(l => (l.sub, l.pre))
  for ( a <- 0 to listSPO.size-1){
    out.write(sl(a).sub.toString+","+sl(a).pre.toString+","+sl(a).obj.toString+"\n")
  }
  for ( a <- 0 to b-1){
    out1.write(sl(a).sub.toString+","+sl(a).pre.toString+","+sl(a).obj.toString+"\n")
  }
  for ( a <- b to (b*2)-1){
    out2.write(sl(a).sub.toString+","+sl(a).pre.toString+","+sl(a).obj.toString+"\n")
  }
  for ( a <- b*2 to (b*3)-1){
    out3.write(sl(a).sub.toString+","+sl(a).pre.toString+","+sl(a).obj.toString+"\n")
  }
  for ( a <- b*3 to (b*4)-1){
    out4.write(sl(a).sub.toString+","+sl(a).pre.toString+","+sl(a).obj.toString+"\n")
  }

  out.close()
  out1.close()
  out2.close()
  out3.close()
  out4.close()

Then my question is if exist a general code where I put the number of files to generate, for example 32, and not to write 32 times the out, the for and the fstream?

Body:
Assuming the objects in the list have this type (otherwise, relpace SPO in the below code with your type):

case class SPO(sub: Int, pre: Int, obj: Int)

This should do it:

val sl = listSPO.sortBy(l => (l.sub, l.pre))

val files = 5 // whatever number you want

// helper function to write a single list - similar to your implementation but shorter
def writeListToFile(name: String, list: List[SPO]): Unit = {
  val writer = new BufferedWriter(new FileWriter(name))
  list.foreach(spo => writer.write(s"${spo.sub},${spo.pre},${spo.obj}\n"))
  writer.close()
}

sl.grouped(sl.size / files) // split into sublists
  .zipWithIndex             // add index of sublists for file name
  .foreach {
    case (sublist, 0) => writeListToFile(s"pasSPO.csv", sublist) // if indeed you want the first file name NOT to include the index
    case (sublist, index) => writeListToFile(s"pasSPO$index.csv", sublist)
  }


问:
Python not showing the [matplotlib] window with openCV results
I'm working on OpenCV 2.4.9 . Below is my code -

```<code>import cv2
import numpy as np
from   matplotlib import pyplot as plt

BLUE = [255,0,0]

img1 = cv2.imread( 'sachin.png' )

replicate  = cv2.copyMakeBorder( img1, 10, 10, 10, 10, cv2.BORDER_REPLICATE )
reflect    = cv2.copyMakeBorder( img1, 10, 10, 10, 10, cv2.BORDER_REFLECT )
reflect101 = cv2.copyMakeBorder( img1, 10, 10, 10, 10, cv2.BORDER_REFLECT_101 )
wrap       = cv2.copyMakeBorder( img1, 10, 10, 10, 10, cv2.BORDER_WRAP )
constant   = cv2.copyMakeBorder( img1, 10, 10, 10, 10, cv2.BORDER_CONSTANT, value = BLUE )

plt.subplot(231), plt.imshow( img1,       'gray' ), plt.title( 'ORIGINAL' )
plt.subplot(232), plt.imshow( replicate,  'gray' ), plt.title( 'REPLICATE')
plt.subplot(233), plt.imshow( reflect,    'gray' ), plt.title( 'REFLECT' )
plt.subplot(234), plt.imshow( reflect101, 'gray' ), plt.title( 'REFLECT_101' )
plt.subplot(235), plt.imshow( wrap,       'gray' ), plt.title( 'WRAP' )
plt.subplot(236), plt.imshow( constant,   'gray' ), plt.title( 'CONSTANT' )

plt.show()
</code>```

When I run the above code I got the following error -

```<code>Traceback (most recent call last):
  File "border.py", line 3, in <module>
    from matplotlib import pyplot as plt
ImportError: No module named matplotlib
</code>```

After googling, I found that Matplotlib module was missing then I installed it from the following commands -
sudo python get-pip.py to install pip. sudo python get-pip.py to install matplotlib.
After when I run the code no error was reported and the code ran successfully but no windows are displayed. Can anyone tell me where I'm going wrong?

答: You need to put plt.figure() before you generate all your plots.</p>

Body:
I'm working on OpenCV 2.4.9 . Below is my code -

import cv2
import numpy as np
from   matplotlib import pyplot as plt

BLUE = [255,0,0]

img1 = cv2.imread( 'sachin.png' )

replicate  = cv2.copyMakeBorder( img1, 10, 10, 10, 10, cv2.BORDER_REPLICATE )
reflect    = cv2.copyMakeBorder( img1, 10, 10, 10, 10, cv2.BORDER_REFLECT )
reflect101 = cv2.copyMakeBorder( img1, 10, 10, 10, 10, cv2.BORDER_REFLECT_101 )
wrap       = cv2.copyMakeBorder( img1, 10, 10, 10, 10, cv2.BORDER_WRAP )
constant   = cv2.copyMakeBorder( img1, 10, 10, 10, 10, cv2.BORDER_CONSTANT, value = BLUE )

plt.subplot(231), plt.imshow( img1,       'gray' ), plt.title( 'ORIGINAL' )
plt.subplot(232), plt.imshow( replicate,  'gray' ), plt.title( 'REPLICATE')
plt.subplot(233), plt.imshow( reflect,    'gray' ), plt.title( 'REFLECT' )
plt.subplot(234), plt.imshow( reflect101, 'gray' ), plt.title( 'REFLECT_101' )
plt.subplot(235), plt.imshow( wrap,       'gray' ), plt.title( 'WRAP' )
plt.subplot(236), plt.imshow( constant,   'gray' ), plt.title( 'CONSTANT' )

plt.show()

When I run the above code I got the following error -

Traceback (most recent call last):
  File "border.py", line 3, in <module>
    from matplotlib import pyplot as plt
ImportError: No module named matplotlib

After googling, I found that Matplotlib module was missing then I installed it from the following commands -
sudo python get-pip.py to install pip. sudo python get-pip.py to install matplotlib.
After when I run the code no error was reported and the code ran successfully but no windows are displayed. Can anyone tell me where I'm going wrong?


问:
SQL - all patients who had only dental visits in 2010
I have a T-SQL query that's giving me the most recent office visit in 2010 that wasn't a dental visit. The relevant part of the query is:

```<code>AND pv.PatientVisitId IN (
    SELECT Max(pv1.PatientVisitID)
        FROM PatientVisit pv1
            JOIN DoctorFacility df1 ON pv1.FacilityID = df1.DoctorFacilityID
            JOIN PatientVisitResource pvr1 ON pv1.PatientVisitId = pvr1.PatientVisitId
                JOIN DoctorFacility dfr ON pvr1.ResourceId = dfr.DoctorFacilityId
        WHERE pv1.PatientProfileID = pp.PatientProfileID
            AND pv1.Visit < '2011-01-01'
            AND df1.ListName NOT LIKE '%Dental%'
    )
</code>```

Now, I want to flip that around to get the most recent office visit for the patients who only had dental appointments. I keep hitting the wall here, though. Can anyone bust me through to the other side? :-)

答: probably numerous was to do this, but the first way that pops into my head is to compare the count(1) of patientvisit to the count(1) of patientvisit where df1.listname like '%Dental%', if those are equal, then they've only been to the dentist.</p>

Body:
I have a T-SQL query that's giving me the most recent office visit in 2010 that wasn't a dental visit. The relevant part of the query is:

AND pv.PatientVisitId IN (
    SELECT Max(pv1.PatientVisitID)
        FROM PatientVisit pv1
            JOIN DoctorFacility df1 ON pv1.FacilityID = df1.DoctorFacilityID
            JOIN PatientVisitResource pvr1 ON pv1.PatientVisitId = pvr1.PatientVisitId
                JOIN DoctorFacility dfr ON pvr1.ResourceId = dfr.DoctorFacilityId
        WHERE pv1.PatientProfileID = pp.PatientProfileID
            AND pv1.Visit < '2011-01-01'
            AND df1.ListName NOT LIKE '%Dental%'
    )

Now, I want to flip that around to get the most recent office visit for the patients who only had dental appointments. I keep hitting the wall here, though. Can anyone bust me through to the other side? :-)


问:
PHP SoapServer: Set port address location
I'm using PHP's builtin SoapServer class to implement a Web service. I need to set the location attribute in the following segment of the WSDL code:

```<code><wsdl:service name="serviceName">
  <wsdl:port name="serviceNameSoap" binding="tns:serviceNameSoap">
    <soap:address location="MY_URL_HERE" />
  </wsdl:port>
  <wsdl:port name="serviceNameSoap12" binding="tns:serviceNameSoap12">
    <soap12:address location="MY_URL_HERE" />
  </wsdl:port>
</wsdl:service>
</code>```

What is the best way to do this programmatically?

答:
Another way is to override the location of our web service from client side, for example:</p>

```<code>$soapClient->__setLocation('http://www.example.com/soapservice');
</code>```

Body:
I'm using PHP's builtin SoapServer class to implement a Web service. I need to set the location attribute in the following segment of the WSDL code:

<wsdl:service name="serviceName">
  <wsdl:port name="serviceNameSoap" binding="tns:serviceNameSoap">
    <soap:address location="MY_URL_HERE" />
  </wsdl:port>
  <wsdl:port name="serviceNameSoap12" binding="tns:serviceNameSoap12">
    <soap12:address location="MY_URL_HERE" />
  </wsdl:port>
</wsdl:service>

What is the best way to do this programmatically?

Body:
Another way is to override the location of our web service from client side, for example:

$soapClient->__setLocation('http://www.example.com/soapservice');


问:
Sharepoint 2013 calculated field as hyperlink renders as text
I have a column in Sharepoint 2013 and set the type to 'Calculated'. I have set the data return type to integer (pic attached) so that the field is hyperlink.

All worked fine for over a year in all environments (dev and production) and browsers (chrome, firefox, IE) until recently when users reportted the hyperlink was not clickable anymore and displayed as text (pic attached). Inspecting the element, reveals the value of  is treated as text.

I have spent some time simplifying the formula, removing fields and having a simple  element to navigate to google, but have not found a solution. I suspect there may been a Sharepoint update which handles the formula differently creating text inside the  element surrounding it with double quotes.

答:
After research I have found the cause and the solution to my problem.

Cause

SharePoint update removed the ability of calculated fields to be set us markups and is explained in Handling HTML markup in SharePoint calculated fields.

Solution

I have found a solution with JSLink. After opening link above, there are some examples using JSLink. With a bit of play-around, I managed to achieve having the calculated field as a hyperlink. The steps are simple.

Create a js file with code - in my case I create a hyperlink which posts to another list with values from current item.

Copy link location of js file.

Reference js file on web part on view, under section Miscellaneous.

Voila!

Note: in the script, the field name must be the internal field name, that slowed me down quite a bit. to get the internal field name, open list settings, hover over desired field and on the bottom left of your browser you get the internal field name (Field=Internal field name here).

JSExample can be found here.

Another helpful read here.


问:
AliasMatch everything except home page to "content" folder
I am putting all of my website's content (aside from the home page) into a "content" folder at the root of the site. This is Apache 2.4.25.

I want http://www.example.com to serve the DirectoryIndex (i.e. index.html) at C:/DocumentRoot/. The following works fine for that.

```<code><Directory "C:/DocumentRoot/website">
    Options None
    AllowOverride None
    Require all granted
</Directory>
</code>```

I then want to have http://www.example.com/anything1/anything2 serve the DirectoryIndex at C:/DocumentRoot/content/anything1/anything2. After adding the following, accessing http://www.example.com gives a Forbidden error, though the AliasMatch works.

```<code>AliasMatch "^/(.+)$" "C:/DocumentRoot/website/content/$1"
<Directory "C:/DocumentRoot/website/content/">
    Require all granted
</Directory>
</code>```

Any idea what's happening or have a better/working alternative?

答:
A change to the AliasMatch so it ignores the DirectoryIndex (index.html) allows it to work as expected.

```<code>AliasMatch "^/(?!index.html)(.+)$" "C:/DocumentRoot/website/content/$1"
</code>```

(?!index.html) ensures that the implicit index.html is not matched. The (.+) picks up anything else and pulls it from the content folder.

Body:
I am putting all of my website's content (aside from the home page) into a "content" folder at the root of the site. This is Apache 2.4.25.

I want http://www.example.com to serve the DirectoryIndex (i.e. index.html) at C:/DocumentRoot/. The following works fine for that.

<Directory "C:/DocumentRoot/website">
    Options None
    AllowOverride None
    Require all granted
</Directory>

I then want to have http://www.example.com/anything1/anything2 serve the DirectoryIndex at C:/DocumentRoot/content/anything1/anything2. After adding the following, accessing http://www.example.com gives a Forbidden error, though the AliasMatch works.

AliasMatch "^/(.+)$" "C:/DocumentRoot/website/content/$1"
<Directory "C:/DocumentRoot/website/content/">
    Require all granted
</Directory>

Any idea what's happening or have a better/working alternative?

Body:
A change to the AliasMatch so it ignores the DirectoryIndex (index.html) allows it to work as expected.

AliasMatch "^/(?!index.html)(.+)$" "C:/DocumentRoot/website/content/$1"

(?!index.html) ensures that the implicit index.html is not matched. The (.+) picks up anything else and pulls it from the content folder.


答:
Your response is json so something like this will help you:</p>

```<code>import json

a = '[{"pure_err_key": "err.friendly", "code": 0, "ctx": "lun-name", "pure_err_code": 1, "msg": "Volume already exists."}]'

h = json.loads(a)

print(h[0]['code']) #prints 0
</code>```

Body:
I'm trapping an error but cannot extract what I want out of the returned message.
Here's the code:

  except purestorage.PureHTTPError as response:
     print "LUN Creation failed:"

     print dir(response)
     print "args:{}".format(response.args)
     print "code:{}".format(response.code)
     print "headers:{}".format(response.headers)
     print "message:{}".format(response.message)
     print "reason:{}".format(response.reason)
     print "rest_version:{}".format(response.rest_version)
     print "target:{}".format(response.target )
     print "text:{}".format(response.text)

Here's the output:

LUN Creation failed:
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__getitem__', '__getslice__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__', '__unicode__', '__weakref__', 'args', 'code', 'headers', 'message', 'reason', 'rest_version', 'target', 'text']
args:()
code:400
headers:{'Content-Length': '113', 'Set-Cookie': 'session=....; Expires=Wed, 05-Jul-2017 16:28:26 GMT; HttpOnly; Path=/', 'Server': 'nginx/1.4.6 (Ubuntu)', 'Connection': 'keep-alive', 'Date': 'Wed, 05 Jul 2017 15:58:26 GMT', 'Content-Type': 'application/json'}
message:
reason:BAD REQUEST
rest_version:1.8
target:array1
text:[{"pure_err_key": "err.friendly", "code": 0, "ctx": "lun-name", "pure_err_code": 1, "msg": "Volume already exists."}]

I want to pull out msg and pure_err_code but the text isn't a list.
The [{ ... }] is confusing me.  The response.text[0] is [ and response.text['msg'] throws an index error so this is acting like a string (afaIk).

Body:
Your response is json so something like this will help you:

import json

a = '[{"pure_err_key": "err.friendly", "code": 0, "ctx": "lun-name", "pure_err_code": 1, "msg": "Volume already exists."}]'

h = json.loads(a)

print(h[0]['code']) #prints 0


问:
Using destructuring assignment and the rest syntax for default variables
The following is an attempt to set the default value for an argument, based on the first argument:

function tree(values, ...[[curr] = values]) {
    console.log(curr);
}

tree(['foo']); // foo
tree(['foo'], ['bar']); // bar ```

It appears to work (actually it isn't quite what I want, but I want to understand this first).

What is going on here?

答:
The spread syntax is spreading an anonymous array with the contents of curr…

No. Nothing is being spreaded into an array literal.

The spread syntax is capturing the rest of the arguments into an anonymous array instance which is being destructured…

Yes.

…into the first value of either: the supplied array if present, or values.

Not sure I understand. The captured array is destructured to the target [[curr] = values], which takes out the first element or - if not present - the values default, and assigns that to the target [curr].

And as @FelixKling commented, you really should not do that, but use

```<code>function tree(values, [curr] = values) {
    console.log(curr);
}
</code>```

Body:
The following is an attempt to set the default value for an argument, based on the first argument:

function tree(values, ...[[curr] = values]) {
    console.log(curr);
}

tree(['foo']); // foo
tree(['foo'], ['bar']); // bar

It appears to work (actually it isn't quite what I want, but I want to understand this first).

What is going on here?

Body:
The spread syntax is spreading an anonymous array with the contents of curr…

No. Nothing is being spreaded into an array literal.

The spread syntax is capturing the rest of the arguments into an anonymous array instance which is being destructured…

Yes.

…into the first value of either: the supplied array if present, or values.

Not sure I understand. The captured array is destructured to the target [[curr] = values], which takes out the first element or - if not present - the values default, and assigns that to the target [curr].

And as @FelixKling commented, you really should not do that, but use

function tree(values, [curr] = values) {
    console.log(curr);
}


问:
Equivalent of query in grpc
Using HTTP, to paginate sequelize data, req.query.limit and req.query.offset are used. I'm using grpc and query doesn't exist. How can I go about this to implement pagination?

Products.findAll({ limit: 50, offset: 0 }).then((prod) => {
      //
      });
From above, I don't want to hard code the limit and offset. Any suggestion?

答: Information that would be contained in the query parameters in HTTP requests should generally be sent in the request message(s) in gRPC.</p>

Title: Equivalent of query in grpc


问:
Case insensitive string matching in awk
Assume a multi-line text file file in which some lines start with whitespaces.

```<code>$ cat file
foo Baz
  baz QUX
    QUx Quux
BaZ Qux
BazaaR
</code>```

Further assume that I wish to convert all those lines that start with a keyword (e.g. "baz") to lowercase letters, irrespective if (a) that keyword is written in lower- or uppercase letters (or any combination thereof) itself, and (b) that keyword is preceeded by whitespaces.

```<code>$ cat file | sought_command
foo Baz        # not to lowercase (line does not start with keyword)
  baz qux      # to lowercase
    QUx Quux
baz qux        # to lowercase
BazaaR         # not to lowercase (line does not start with keyword, but merely with a word containing the keyword)
</code>```

I believe that awk is the tool to do it, but I am uncertain how to implement the case-insensitivity for the keyword matching.

```<code>$ cat file | awk '{ if($1 ~ /^ *baz/) print tolower($0); else print $0}'
foo Baz
  baz qux
    QUx Quux
BaZ Qux       # ERROR HERE: was not replaced, b/c keyword not recognized.
BazaaR
</code>```

EDIT 1:
Adding IGNORECASE=1 appears to resolve the case-insensitivity, but now incorrectly converts the last line to lowercase.

```<code>$ cat file | awk '{IGNORECASE=1; if($1~/^ *baz/) print tolower($0); else print $0}'
foo Baz
  baz qux
    QUx Quux
baz qux
bazaar       # ERROR HERE: should not be converted to lowercase, as keyword not present (emphasis on word!).
</code>```

答:
Add word-boundary after search string

```<code>$ awk '{IGNORECASE=1; if($1~/^ *baz\>/) print tolower($0); else print $0}' ip.txt
foo Baz
  baz qux
    QUx Quux
baz qux
BazaaR
</code>```

Can be re-written as:

```<code>awk 'BEGIN{IGNORECASE=1} /^ *baz\>/{$0=tolower($0)} 1' ip.txt
</code>```

Since line anchor is used, no need to match with $1. The 1 at end will print the record, including any changes done

IGNORECASE and \> are gawk specific features. \y can be also used to match word boundary

With GNU sed

```<code>$ sed 's/^[[:blank:]]*baz\b.*/\L&/I' ip.txt
foo Baz
  baz qux
    QUx Quux
baz qux
BazaaR
</code>```

[[:blank:]] will match space or tab characters

\L& will lowercase the line

\b is word boundary

I flag to match case-insensitively

Title: Case insensitive string matching in awk

Body:
Assume a multi-line text file file in which some lines start with whitespaces.

$ cat file
foo Baz
  baz QUX
    QUx Quux
BaZ Qux
BazaaR

Further assume that I wish to convert all those lines that start with a keyword (e.g. "baz") to lowercase letters, irrespective if (a) that keyword is written in lower- or uppercase letters (or any combination thereof) itself, and (b) that keyword is preceeded by whitespaces.

$ cat file | sought_command
foo Baz        # not to lowercase (line does not start with keyword)
  baz qux      # to lowercase
    QUx Quux
baz qux        # to lowercase
BazaaR         # not to lowercase (line does not start with keyword, but merely with a word containing the keyword)

I believe that awk is the tool to do it, but I am uncertain how to implement the case-insensitivity for the keyword matching.

$ cat file | awk '{ if($1 ~ /^ *baz/) print tolower($0); else print $0}'
foo Baz
  baz qux
    QUx Quux
BaZ Qux       # ERROR HERE: was not replaced, b/c keyword not recognized.
BazaaR

EDIT 1:
Adding IGNORECASE=1 appears to resolve the case-insensitivity, but now incorrectly converts the last line to lowercase.

$ cat file | awk '{IGNORECASE=1; if($1~/^ *baz/) print tolower($0); else print $0}'
foo Baz
  baz qux
    QUx Quux
baz qux
bazaar       # ERROR HERE: should not be converted to lowercase, as keyword not present (emphasis on word!).

Body:
Add word-boundary after search string

$ awk '{IGNORECASE=1; if($1~/^ *baz\>/) print tolower($0); else print $0}' ip.txt
foo Baz
  baz qux
    QUx Quux
baz qux
BazaaR

Can be re-written as:

awk 'BEGIN{IGNORECASE=1} /^ *baz\>/{$0=tolower($0)} 1' ip.txt

Since line anchor is used, no need to match with $1. The 1 at end will print the record, including any changes done

IGNORECASE and \> are gawk specific features. \y can be also used to match word boundary

With GNU sed

$ sed 's/^[[:blank:]]*baz\b.*/\L&/I' ip.txt
foo Baz
  baz qux
    QUx Quux
baz qux
BazaaR

[[:blank:]] will match space or tab characters

\L& will lowercase the line

\b is word boundary

I flag to match case-insensitively


问:
Searching ALL ROWS in a Group using IIF Expression
I am working on a report that displays patient names (as groups with drilldowns) and several fields related to their visits.  I have created a column in the report to display whether or not a specific value appears in the 'LocationID' column.  The expression I used is

=IIF(Fields!LocationID.Value="WELL","Y","N")

I thought this was working great, it displays Y or N next to each name to let me know if 'WELL' was in their 'LocationID'. I checked several to ensure that this was going to work and discovered that there was a LocationID code of 'WHS' and since I have the rows ordered by Name and LocationID if there was a WHS visit it shows up at the top of the group and my expression is only seeing this top item.  How can this expression be written differently so that it searches the entire result of each group?  Depending on the date range a patient may have one visit or they may have ten.  I need to check all visits that are returned.  Perhaps there is a better method.  Thanks in advance.

答:
I agree with jimmy8ball that the easiest way to solve most issues like this is to push some logic back into the SQL layer.

However, if you really want to do this via SSRS functionality, then you could implement a substring search against a lookupset. Assuming you have a patient id in your dataset that is unique for each patient (I hope your group isn't on the name) then...

```<code>=Iif(InStr(Join(Lookupset(Fields!patientid.Value, Fields!patientid.Value, Fields!LocationsID.Value, "dataset"), ","), "WELL") > 0, "Y", "N")
</code>```

Which says, "Search through the dataset for all rows related to my patientid, join every location into a comma deliminated string, search the string for the text "WELL" and return "Y" if it's found.

Obviously if you have locations in your dataset like "WELLY", these will become false positives and you'll have to implement some more nested logic.  Try appending a value (perhaps !) to the lookupset return field so that you can search for "WELL!" or some other terminator character.

Body:
I agree with jimmy8ball that the easiest way to solve most issues like this is to push some logic back into the SQL layer.

However, if you really want to do this via SSRS functionality, then you could implement a substring search against a lookupset. Assuming you have a patient id in your dataset that is unique for each patient (I hope your group isn't on the name) then...

=Iif(InStr(Join(Lookupset(Fields!patientid.Value, Fields!patientid.Value, Fields!LocationsID.Value, "dataset"), ","), "WELL") > 0, "Y", "N")

Which says, "Search through the dataset for all rows related to my patientid, join every location into a comma deliminated string, search the string for the text "WELL" and return "Y" if it's found.

Obviously if you have locations in your dataset like "WELLY", these will become false positives and you'll have to implement some more nested logic.  Try appending a value (perhaps !) to the lookupset return field so that you can search for "WELL!" or some other terminator character.


问:
flutter android fingerprint integration
I am looking for some guidance when using flutter over a platform channel to integrate with android fingerprint authentication.  I have the android part working and the flutter app with call the method, but I can not seem to get just a pop-up of fingerprint authentication like I do in swift, which works fine in the same flutter app, in order for it to pass results to the flutter app and let the flutter app continue on. If anyone has any examples or some guidance it would be greatly appreciated.</p>

答: Try the local_auth plugin -- it comes with usage instructions and an example app.</p>

Title: flutter android fingerprint integration


问:
keep values after submit
I know how I can keep my form where I have a select list is not deleted after a submit?

This is the line I use to fill the select list:

```<code><% = select: search,: style, [[All, ""]] + Proyect.all (: group => "style",: order => "style"). collect {| a | [a. style a.estilo]}%>
</code>```

please help me

Thanks in advance

答:
yeah. was very simple.

Solved with the folowing parameters added to the current line:

```<code>{:selected=>params[:search][:style]}
</code>```

thus leaving

```<code><% = select: search,: style, [[All, ""]] + Proyect.all (: group => "style",: order => "style"). collect {| a | [a. style a.estilo]},{:selected=>params[:search][:style]}%>
</code>```

thanks anyway

-------------------ANNEX---------

That's right, but my solution, half good solution, because I have the problem that if the parameter still not been created?

How to do something like this:

```<code>{: selected => params [: search] [: style] if params [: search] [: style]! = nil}%>
</code>```

being as follows:

```<code><% = select: search,: style, [[All, ""]] + Proyect.all (: group => "style",: order => "style"). collect {| a | [a. ]},{: a.estilo style selected => params [: search] [: style] if params [: search] [: style]! = nil}%>
</code>```

any ideas?

Title: keep values after submit

Body:
I know how I can keep my form where I have a select list is not deleted after a submit?

This is the line I use to fill the select list:

<% = select: search,: style, [[All, ""]] + Proyect.all (: group => "style",: order => "style"). collect {| a | [a. style a.estilo]}%>

please help me

Thanks in advance

Body:
yeah. was very simple.

Solved with the folowing parameters added to the current line:

{:selected=>params[:search][:style]}

thus leaving

<% = select: search,: style, [[All, ""]] + Proyect.all (: group => "style",: order => "style"). collect {| a | [a. style a.estilo]},{:selected=>params[:search][:style]}%>

thanks anyway

-------------------ANNEX---------

That's right, but my solution, half good solution, because I have the problem that if the parameter still not been created?

How to do something like this:

{: selected => params [: search] [: style] if params [: search] [: style]! = nil}%>

being as follows:

<% = select: search,: style, [[All, ""]] + Proyect.all (: group => "style",: order => "style"). collect {| a | [a. ]},{: a.estilo style selected => params [: search] [: style] if params [: search] [: style]! = nil}%>

any ideas?


问:
Pure Javascript - Click and scroll to Div inside div
I have the following HTML, with scrollbar:

```<code><div id="parent">
      <div id="child1">Something</div>
      <div id="child2">Something</div>
      <div id="child3">Something</div>
      <div id="child4">Something</div>
      <div id="child5">Something</div>
      <div id="child6">Something</div>
      <div id="child7">Something</div>
      <div id="child8">Something</div>
      <div id="child9">Something</div>
</div>
</code>```

My question is this:

How can I, in pure javascript, position the scroll of the div 'parent' in one of the childs?

答:
You can use the scrollIntoView function of JavaScript like this:

```<code>document.getElementById('child9').scrollIntoView()
</code>```

Try it online

Body:
I have the following HTML, with scrollbar:

Something

Something

Something

Something

Something

Something

Something

Something

Something

My question is this:

How can I, in pure javascript, position the scroll of the div 'parent' in one of the childs?

Body:
You can use the scrollIntoView function of JavaScript like this:

document.getElementById('child9').scrollIntoView()

Try it online