问:
Optimized JSON serialiser / deserialiser as an extension method?
I'd like to serialize any object as easily as possible to JSON, and then convert it back to the type=safe object simply.  Can anyone tell me what I'm doing wrong in the "FromJSONString" extension method?

Edit

For your convenience, a complete and functional extension method is below. Do let me know if you see errors.

```<code>     public static string ToJSONString(this object obj)
    {
        using (var stream = new MemoryStream())
        {
            var ser = new DataContractJsonSerializer(obj.GetType());

            ser.WriteObject(stream, obj);

            return Encoding.UTF8.GetString(stream.ToArray());
        }
    }
    public static T FromJSONString<T>(this string obj)
    {
        using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(obj)))
        {
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
            T ret = (T)ser.ReadObject(stream);
            return ret;
        }
    }
</code>```

答:
You have to provide the JSON string to the MemoryStream to be decoded. Specifically, you must change:

```<code>   MemoryStream stream1 = new MemoryStream();
</code>```

to actually retrieve the string bytes:

```<code>   MemoryStream stream1 = new MemoryStream(Encoding.UTF8.GetBytes(obj))
</code>```

That being said, I would also make sure to do proper memory cleanup and dispose my objects... also, rather than using the StreamReader (which should also be disposed), simply re-encode the memory stream as a UTF-8 string. See below for cleaned up code.

```<code>   public static String ToJSONString(this Object obj)
   {
     using (var stream = new MemoryStream())
     {
       var ser = new DataContractJsonSerializer(obj.GetType());

       ser.WriteObject(stream, obj);

       return Encoding.UTF8.GetString(stream.ToArray());
     }
   }

   public static T FromJSONString<T>(this string obj)
   {
     using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(obj)))
     {
       DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
       T ret = (T)ser.ReadObject(stream);
       return ret;
     }
   }
</code>```

Body:
I'd like to serialize any object as easily as possible to JSON, and then convert it back to the type=safe object simply.  Can anyone tell me what I'm doing wrong in the "FromJSONString" extension method?

Edit

For your convenience, a complete and functional extension method is below. Do let me know if you see errors.

     public static string ToJSONString(this object obj)
    {
        using (var stream = new MemoryStream())
        {
            var ser = new DataContractJsonSerializer(obj.GetType());

            ser.WriteObject(stream, obj);

            return Encoding.UTF8.GetString(stream.ToArray());
        }
    }
    public static T FromJSONString<T>(this string obj)
    {
        using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(obj)))
        {
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
            T ret = (T)ser.ReadObject(stream);
            return ret;
        }
    }

Body:
You have to provide the JSON string to the MemoryStream to be decoded. Specifically, you must change:

   MemoryStream stream1 = new MemoryStream();

to actually retrieve the string bytes:

   MemoryStream stream1 = new MemoryStream(Encoding.UTF8.GetBytes(obj))

That being said, I would also make sure to do proper memory cleanup and dispose my objects... also, rather than using the StreamReader (which should also be disposed), simply re-encode the memory stream as a UTF-8 string. See below for cleaned up code.

   public static String ToJSONString(this Object obj)
   {
     using (var stream = new MemoryStream())
     {
       var ser = new DataContractJsonSerializer(obj.GetType());

       ser.WriteObject(stream, obj);

       return Encoding.UTF8.GetString(stream.ToArray());
     }
   }

   public static T FromJSONString<T>(this string obj)
   {
     using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(obj)))
     {
       DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
       T ret = (T)ser.ReadObject(stream);
       return ret;
     }
   }


来源: stackexchange

问:
De-duplicating and transposing columns data in pandas & python
I have an data frame that looks like this

```<code>Column1-Column2
a      - 12
b      - t1
c      - t3
d      - 798
a      - 87
b      - g1
a      - 478
c      - f1
d      - 906
</code>```

I would like to get a data frame that is like this:

```<code>Columns:
a, b, c, d
Rows:
12, t1, t3, 798
87, g1, -, -
478, -, f1, 906
</code>```

Basically, I would like to de-dup columns and populate the associated row data.

Thanks so much!

答:
Assuming your rows always have 'a' column value, you can do this like this:

```<code>#standard imports
import pandas as pd

initial = pd.DataFrame(
    {
        'Column1' : [
            'a',
            'b',
            'c',
            'd',
            'a',
            'b',
            'a',
            'c',
            'd'
        ],
        'Column2':[
            '12',
            't1',
            't3',
            '798',
            '87',
            'g1',
            '478',
            'f1',
            '906'
        ]
    }
)

pivoted = initial.pivot(columns='Column1', values='Column2')

target = pivoted.groupby(pivoted.apply(lambda x: 1 if x[0]!=None else 0, axis=1).cumsum())[pivoted.columns].agg(lambda x: ''.join([el for el in x if el!=None]))
</code>```

If you can have missing 'a' values, then it gets trickier. That's why it's so important to give representative examples in your questions.

EDIT:

Iterative approach, if you can have non-existing 'a' values in a row:

```<code>#use `initial` dataframe from answer above
target = pd.DataFrame(columns=['a', 'b', 'c', 'd'])
newrow = dict()
for index, row in initial.iterrows():
    if row['Column1'] in newrow:
        target=target.append(newrow, ignore_index=True)
        newrow=dict()
    newrow[row['Column1']]=row['Column2']

target=target.append(newrow, ignore_index=True)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have an data frame that looks like this

Column1-Column2
a      - 12
b      - t1
c      - t3
d      - 798
a      - 87
b      - g1
a      - 478
c      - f1
d      - 906

I would like to get a data frame that is like this:

Columns:
a, b, c, d
Rows:
12, t1, t3, 798
87, g1, -, -
478, -, f1, 906

Basically, I would like to de-dup columns and populate the associated row data.

Thanks so much!

Body:
Assuming your rows always have 'a' column value, you can do this like this:

#standard imports
import pandas as pd

initial = pd.DataFrame(
    {
        'Column1' : [
            'a',
            'b',
            'c',
            'd',
            'a',
            'b',
            'a',
            'c',
            'd'
        ],
        'Column2':[
            '12',
            't1',
            't3',
            '798',
            '87',
            'g1',
            '478',
            'f1',
            '906'
        ]
    }
)

pivoted = initial.pivot(columns='Column1', values='Column2')

target = pivoted.groupby(pivoted.apply(lambda x: 1 if x[0]!=None else 0, axis=1).cumsum())[pivoted.columns].agg(lambda x: ''.join([el for el in x if el!=None]))

If you can have missing 'a' values, then it gets trickier. That's why it's so important to give representative examples in your questions.

EDIT:

Iterative approach, if you can have non-existing 'a' values in a row:

#use `initial` dataframe from answer above
target = pd.DataFrame(columns=['a', 'b', 'c', 'd'])
newrow = dict()
for index, row in initial.iterrows():
    if row['Column1'] in newrow:
        target=target.append(newrow, ignore_index=True)
        newrow=dict()
    newrow[row['Column1']]=row['Column2']

target=target.append(newrow, ignore_index=True)


问:
jQuery plugin - issue with separating all instances
While practising jQuery plugins development with jQuery boilerplate I tried to create a carousel that will be both drag and hover enabled, based on the screen type. However after runing the plugin for more than one DOM element I found out that I didn't seperate it completely. The draggable instance is shared betweeen the carousels and it globally forces each one of them to move at the same time.

To be honest I don't know where I should be looking for an issue. It's my first project with that boilerplate and I feel a little bit lost at the moment.

Can you be so kind and take a look at my code?

https://codepen.io/Nikolaus91/pen/LOoERJ

```<code>(function($, window, document, undefined) {
// undefined is used here as the undefined global
// variable in ECMAScript 3 and is mutable (i.e. it can
// be changed by someone else). undefined isn't really
// being passed in so we can ensure that its value is
// truly undefined. In ES5, undefined can no longer be
// modified.

// window and document are passed through as local
// variables rather than as globals, because this (slightly)
// quickens the resolution process and can be more
// efficiently minified (especially when both are
// regularly referenced in your plugin).

// Create the defaults once
var pluginName = "finiteCarousel",
defaults = {
  singleRowClass: "finite-carousel__inner",
  singleSlideClass: "finite-carousel__slide"
};

// The actual plugin constructor
function Plugin(element, options) {
this.element = element;

// jQuery has an extend method that merges the
// contents of two or more objects, storing the
// result in the first object. The first object
// is generally empty because we don't want to alter
// the default options for future instances of the plugin
this.options = $.extend({}, defaults, options);

this._defaults = defaults;
this._name = pluginName;

this.init();
}

Plugin.prototype = {
init: function() {
  // Place initialization logic here
  // You already have access to the DOM element and
  // the options via the instance, e.g. this.element
  // and this.options
  //console.clear();
  console.log("Initiating");

  this.buildCache();
  console.log(this);
  console.log(this.$element);
  console.log(this.$container);
  console.log(this.$slides);

  this.buildDraggable();

  if (typeof Modernizr == "object") {
    if (!Modernizr.touchevents) {
      console.log("Binding mouse events");
      this.bindEvents();
      console.log(this.$draggable);
      //this.$draggable[0].disable();
    }
  }

  //console.log("Touchevents: " + Modernizr.touchevents);
},
// Cache DOM nodes for performance
buildCache: function() {
  /*
            Create variable(s) that can be accessed by other plugin
            functions. For example, "this.$element = $(this.element);"
            will cache a jQuery reference to the elementthat initialized
            the plugin. Cached variables can then be used in other methods.
        */
  this.$element = $(this.element);
  this.$container = this.$element.find("." + defaults.singleRowClass);
  this.$slides = this.$element.find("." + defaults.singleSlideClass);

  this.$totalWidth = 0;
  this.$lastX = 0;
  this.$diffX;
  this.$currentX;
},
// Build draggable instance
buildDraggable: function() {
  var plugin = this;
  var isDragging = false;

  // Count all slides outer width
  plugin.$slides.each(function(index, elem) {
    plugin.$totalWidth += $(elem).outerWidth();
  });
  console.log("\nWidth of all slides: " + plugin.$totalWidth);

  // Build draggable instance
  plugin.$draggable = Draggable.create('<div />', {
    type: "x",
    trigger: plugin.$container,
    throwProps: true,
    edgeResistance: 0.95,
    onDrag: updateProgress,
    onThrowUpdate: updateProgress,
    onThrowComplete: function() {
      isDragging = false;
    },
    onPress: function() {
      //console.clear();
      //console.log(this);
      //console.log(plugin.$draggable[0]);
      plugin.$draggable[0].update();
      plugin.$lastX = plugin.$draggable[0].x;
      updatePosition(plugin.$draggable[0]);
      isDragging = true;
      TweenMax.killTweensOf(plugin.$draggable[0].target);
    },
    onComplete: function() {
      console.log("On Complete");
    }
  });

  function updateProgress() {
    plugin.$diffX = plugin.$draggable[0].x - plugin.$lastX;
    TweenMax.set("." + defaults.singleSlideClass, {
      x: "+=" + plugin.$diffX
    });
    plugin.$lastX = plugin.$draggable[0].x;
  }
  // Updates the position of all slides
  function updatePosition(draggableInstance) {
    plugin.$currentX = draggableInstance.target._gsTransform.x;
    plugin.$lastX = draggableInstance.target._gsTransform.x;

    plugin.$slides.each(function(index, elem) {
      TweenMax.set(elem, { x: plugin.$currentX });
      //currentX += $(elem).outerWidth();
    });
  }

  $(window).resize(applyBorders(plugin.$draggable[0]));
  applyBorders(plugin.$draggable[0]);
  // Apply borders to our carousel
  function applyBorders(draggableInstance) {
    var minx = plugin.$container.outerWidth() - plugin.$totalWidth;
    var maxx = 0;

    draggableInstance.applyBounds({ minX: minx, maxX: maxx });

    updatePosition(draggableInstance);
  }
},

// Bind mouse events
bindEvents: function() {
  var plugin = this;

  var isMouseOver = false;
  var direction;
  var mouseX, mouseY;
  var isDragging = false;
  var animateX;
  var animation = TweenMax.to({}, 0, {});
  var animationTimescale = 1;

  plugin.$container.on("mouseleave", function() {
    console.log("Mouse left");
    isMouseOver = false;
    TweenMax.killTweensOf(animation);
  });

  plugin.$container.on("mousemove", function(e) {
    var container = this;
    var rect = container.getBoundingClientRect();

    //console.log(rect);

    mouseX = e.pageX - rect.left;
    if (mouseX < rect.width / 5) {
      direction = 1;
      animationTimescale = Math.abs(mouseX / (rect.width / 25) - 5);
      isMouseOver = true;
    } else if (mouseX > rect.width - rect.width / 5) {
      direction = -1;
      animationTimescale = Math.abs(
        (rect.width - mouseX) / (rect.width / 25) - 5
      );
      isMouseOver = true;
    } else {
      isMouseOver = false;
    }
    //console.log(animationTimescale);
    animateX = rect.width / 5;

    if (!animation.isActive()) {
      animateSlides();
    } else {
      animation.timeScale(animationTimescale);
    }
  });

  function animateSlides() {
    if (
      plugin.$draggable[0].target._gsTransform.x < 0 ||
      plugin.$draggable[0].target._gsTransform.x >
        plugin.$container.outerWidth() - plugin.$totalWidth
    ) {
      if (isMouseOver && !isDragging) {
        animation = TweenMax.to(plugin.$draggable[0].target, 0.3, {
          ease: Linear.easeNone,
          x: "+=" + animateX * direction,
          modifiers: { x: checkBounds },
          onComplete: animateSlides,
          onUpdate: updateSlides
        });
      }
    }

    animation.timeScale(animationTimescale);
  }

  // Uses modifiers plugin to make sure slides remain within bound
  function checkBounds(value) {
    if (value > 0) {
      TweenMax.killTweensOf(plugin.$draggable[0].target);
      return 0;
    } else if (
      value <
      plugin.$container.outerWidth() - plugin.$totalWidth
    ) {
      TweenMax.killTweensOf(plugin.$draggable[0].target);
      return plugin.$container.outerWidth() - plugin.$totalWidth;
    }
    return value;
  }

  // Updates slides along with proxy element
  function updateSlides() {
    plugin.$diffX =
      plugin.$draggable[0].target._gsTransform.x - plugin.$lastX;
    TweenMax.set(plugin.$slides, { x: "+=" + plugin.$diffX });
    plugin.$lastX = plugin.$draggable[0].target._gsTransform.x;
    }
  } // end Bind events
};

// A really lightweight plugin wrapper around the constructor,
// preventing against multiple instantiations
$.fn[pluginName] = function(options) {
console.clear();
return this.each(function() {
  console.log('Creating');
  if (!$.data(this, "plugin_" + pluginName)) {
    $.data(this, "plugin_" + pluginName, new Plugin(this, options));
  }
  });
};
})(jQuery, window, document);

$(".finite-carousel").finiteCarousel();
</code>```

答:
Everything was working fine, I had a spelling mistake on line 283, where I was calling all carousel elements globally:

```<code>    TweenMax.set("." + defaults.singleSlideClass), {
      x: "+=" + plugin.$diffX
    });
</code>```

and I had to change it to:

```<code>TweenMax.set(plugin.$slides, {
      x: "+=" + plugin.$diffX
    });
</code>```

where:

```<code>var plugin = this;
plugin.$slides = this.$element.find("." + defaults.singleSlideClass);
</code>```

Body:
While practising jQuery plugins development with jQuery boilerplate I tried to create a carousel that will be both drag and hover enabled, based on the screen type. However after runing the plugin for more than one DOM element I found out that I didn't seperate it completely. The draggable instance is shared betweeen the carousels and it globally forces each one of them to move at the same time.

To be honest I don't know where I should be looking for an issue. It's my first project with that boilerplate and I feel a little bit lost at the moment.

Can you be so kind and take a look at my code?

https://codepen.io/Nikolaus91/pen/LOoERJ

(function($, window, document, undefined) {
// undefined is used here as the undefined global
// variable in ECMAScript 3 and is mutable (i.e. it can
// be changed by someone else). undefined isn't really
// being passed in so we can ensure that its value is
// truly undefined. In ES5, undefined can no longer be
// modified.

// window and document are passed through as local
// variables rather than as globals, because this (slightly)
// quickens the resolution process and can be more
// efficiently minified (especially when both are
// regularly referenced in your plugin).

// Create the defaults once
var pluginName = "finiteCarousel",
defaults = {
  singleRowClass: "finite-carousel__inner",
  singleSlideClass: "finite-carousel__slide"
};

// The actual plugin constructor
function Plugin(element, options) {
this.element = element;

// jQuery has an extend method that merges the
// contents of two or more objects, storing the
// result in the first object. The first object
// is generally empty because we don't want to alter
// the default options for future instances of the plugin
this.options = $.extend({}, defaults, options);

this._defaults = defaults;
this._name = pluginName;

this.init();
}

Plugin.prototype = {
init: function() {
  // Place initialization logic here
  // You already have access to the DOM element and
  // the options via the instance, e.g. this.element
  // and this.options
  //console.clear();
  console.log("Initiating");

  this.buildCache();
  console.log(this);
  console.log(this.$element);
  console.log(this.$container);
  console.log(this.$slides);

  this.buildDraggable();

  if (typeof Modernizr == "object") {
    if (!Modernizr.touchevents) {
      console.log("Binding mouse events");
      this.bindEvents();
      console.log(this.$draggable);
      //this.$draggable[0].disable();
    }
  }

  //console.log("Touchevents: " + Modernizr.touchevents);
},
// Cache DOM nodes for performance
buildCache: function() {
  /*
            Create variable(s) that can be accessed by other plugin
            functions. For example, "this.$element = $(this.element);"
            will cache a jQuery reference to the elementthat initialized
            the plugin. Cached variables can then be used in other methods.
        */
  this.$element = $(this.element);
  this.$container = this.$element.find("." + defaults.singleRowClass);
  this.$slides = this.$element.find("." + defaults.singleSlideClass);

  this.$totalWidth = 0;
  this.$lastX = 0;
  this.$diffX;
  this.$currentX;
},
// Build draggable instance
buildDraggable: function() {
  var plugin = this;
  var isDragging = false;

  // Count all slides outer width
  plugin.$slides.each(function(index, elem) {
    plugin.$totalWidth += $(elem).outerWidth();
  });
  console.log("\nWidth of all slides: " + plugin.$totalWidth);

  // Build draggable instance
  plugin.$draggable = Draggable.create('
', {
    type: "x",
    trigger: plugin.$container,
    throwProps: true,
    edgeResistance: 0.95,
    onDrag: updateProgress,
    onThrowUpdate: updateProgress,
    onThrowComplete: function() {
      isDragging = false;
    },
    onPress: function() {
      //console.clear();
      //console.log(this);
      //console.log(plugin.$draggable[0]);
      plugin.$draggable[0].update();
      plugin.$lastX = plugin.$draggable[0].x;
      updatePosition(plugin.$draggable[0]);
      isDragging = true;
      TweenMax.killTweensOf(plugin.$draggable[0].target);
    },
    onComplete: function() {
      console.log("On Complete");
    }
  });

  function updateProgress() {
    plugin.$diffX = plugin.$draggable[0].x - plugin.$lastX;
    TweenMax.set("." + defaults.singleSlideClass, {
      x: "+=" + plugin.$diffX
    });
    plugin.$lastX = plugin.$draggable[0].x;
  }
  // Updates the position of all slides
  function updatePosition(draggableInstance) {
    plugin.$currentX = draggableInstance.target._gsTransform.x;
    plugin.$lastX = draggableInstance.target._gsTransform.x;

    plugin.$slides.each(function(index, elem) {
      TweenMax.set(elem, { x: plugin.$currentX });
      //currentX += $(elem).outerWidth();
    });
  }

  $(window).resize(applyBorders(plugin.$draggable[0]));
  applyBorders(plugin.$draggable[0]);
  // Apply borders to our carousel
  function applyBorders(draggableInstance) {
    var minx = plugin.$container.outerWidth() - plugin.$totalWidth;
    var maxx = 0;

    draggableInstance.applyBounds({ minX: minx, maxX: maxx });

    updatePosition(draggableInstance);
  }
},

// Bind mouse events
bindEvents: function() {
  var plugin = this;

  var isMouseOver = false;
  var direction;
  var mouseX, mouseY;
  var isDragging = false;
  var animateX;
  var animation = TweenMax.to({}, 0, {});
  var animationTimescale = 1;

  plugin.$container.on("mouseleave", function() {
    console.log("Mouse left");
    isMouseOver = false;
    TweenMax.killTweensOf(animation);
  });

  plugin.$container.on("mousemove", function(e) {
    var container = this;
    var rect = container.getBoundingClientRect();

    //console.log(rect);

    mouseX = e.pageX - rect.left;
    if (mouseX < rect.width / 5) {
      direction = 1;
      animationTimescale = Math.abs(mouseX / (rect.width / 25) - 5);
      isMouseOver = true;
    } else if (mouseX > rect.width - rect.width / 5) {
      direction = -1;
      animationTimescale = Math.abs(
        (rect.width - mouseX) / (rect.width / 25) - 5
      );
      isMouseOver = true;
    } else {
      isMouseOver = false;
    }
    //console.log(animationTimescale);
    animateX = rect.width / 5;

    if (!animation.isActive()) {
      animateSlides();
    } else {
      animation.timeScale(animationTimescale);
    }
  });

  function animateSlides() {
    if (
      plugin.$draggable[0].target._gsTransform.x < 0 ||
      plugin.$draggable[0].target._gsTransform.x >
        plugin.$container.outerWidth() - plugin.$totalWidth
    ) {
      if (isMouseOver && !isDragging) {
        animation = TweenMax.to(plugin.$draggable[0].target, 0.3, {
          ease: Linear.easeNone,
          x: "+=" + animateX * direction,
          modifiers: { x: checkBounds },
          onComplete: animateSlides,
          onUpdate: updateSlides
        });
      }
    }

    animation.timeScale(animationTimescale);
  }

  // Uses modifiers plugin to make sure slides remain within bound
  function checkBounds(value) {
    if (value > 0) {
      TweenMax.killTweensOf(plugin.$draggable[0].target);
      return 0;
    } else if (
      value <
      plugin.$container.outerWidth() - plugin.$totalWidth
    ) {
      TweenMax.killTweensOf(plugin.$draggable[0].target);
      return plugin.$container.outerWidth() - plugin.$totalWidth;
    }
    return value;
  }

  // Updates slides along with proxy element
  function updateSlides() {
    plugin.$diffX =
      plugin.$draggable[0].target._gsTransform.x - plugin.$lastX;
    TweenMax.set(plugin.$slides, { x: "+=" + plugin.$diffX });
    plugin.$lastX = plugin.$draggable[0].target._gsTransform.x;
    }
  } // end Bind events
};

// A really lightweight plugin wrapper around the constructor,
// preventing against multiple instantiations
$.fn[pluginName] = function(options) {
console.clear();
return this.each(function() {
  console.log('Creating');
  if (!$.data(this, "plugin_" + pluginName)) {
    $.data(this, "plugin_" + pluginName, new Plugin(this, options));
  }
  });
};
})(jQuery, window, document);

$(".finite-carousel").finiteCarousel();

Body:
Everything was working fine, I had a spelling mistake on line 283, where I was calling all carousel elements globally:

    TweenMax.set("." + defaults.singleSlideClass), {
      x: "+=" + plugin.$diffX
    });

and I had to change it to:

TweenMax.set(plugin.$slides, {
      x: "+=" + plugin.$diffX
    });

where:

var plugin = this;
plugin.$slides = this.$element.find("." + defaults.singleSlideClass);


问:
is this a valid class variable ? $this->$variablename
I am referencing to a variable like this

```<code>$this->variablename
</code>```

but I have seen accessing variable like this:

```<code>$this->$variablename
</code>```

for example in a google script

```<code>public function __get($key)
{
    $keyTypeName = $this->keyType($key);
    $keyDataType = $this->dataType($key);
    if (isset($this->$keyTypeName) && !isset($this->processed[$key])) {
      if (isset($this->modelData[$key])) {
        $val = $this->modelData[$key];
      } else if (isset($this->$keyDataType) &&
          ($this->$keyDataType == 'array' || $this->$keyDataType == 'map')) {
        $val = array();
      } else {
        $val = null;
      }
   }
}
</code>```

in this example it is $this->$keyTypeName, is this an error or valid code?. In php 7 it is giving error.

答:
They are variable's variable

```<code>$this->$keyTypeName
This is accessed as $$keyTypeName
</code>```

while

```<code>$this->keyTypeName
this is accessed as $keyTypeName
</code>```

Body:
I am referencing to a variable like this

$this->variablename

but I have seen accessing variable like this:

$this->$variablename

for example in a google script

public function __get($key)
{
    $keyTypeName = $this->keyType($key);
    $keyDataType = $this->dataType($key);
    if (isset($this->$keyTypeName) && !isset($this->processed[$key])) {
      if (isset($this->modelData[$key])) {
        $val = $this->modelData[$key];
      } else if (isset($this->$keyDataType) &&
          ($this->$keyDataType == 'array' || $this->$keyDataType == 'map')) {
        $val = array();
      } else {
        $val = null;
      }
   }
}

in this example it is $this->$keyTypeName, is this an error or valid code?. In php 7 it is giving error.

Body:
They are variable's variable

$this->$keyTypeName
This is accessed as $$keyTypeName

while

$this->keyTypeName
this is accessed as $keyTypeName


问:
Conditional formatting pandas
How do I colour in cells below 1 as green and cells between 0 and 0.5 yellow for Column C.

Current output:

```<code>   A    B    C
0 TT    WW   -5
1 AA    WW   0
2 DD    WW   5
</code>```

Desired:

The following code for me just writes to Excel with no colour change.

```<code>import pandas as pd
import numpy as np

df = pd.read_excel("C:\\13\\13\\13.xlsx")
def highlight_vals(val, min=-1111, max=1, color='green'):
    if min < val < max:
        return 'background-color: %s' % color
    else:
        return ''
df.style.applymap(highlight_vals, subset=['C'])

def highlight_vals(val, min=0, max=0.5, color='yellow'):
    if min < val < max:
        return 'background-color: %s' % color
    else:
        return ''
df.style.applymap(highlight_vals, subset=['C'])

writer = pd.ExcelWriter("C:\\13\\13\\zz.xlsx")
df.to_excel(writer, startrow=0, startcol=0, index = False)

writer.save()
</code>```

答:
This should work:

```<code>import pandas as pd
import numpy as np

df = pd.read_excel("C:\\13\\13\\13.xlsx")
def highlight_vals(val, min=-1111, max=1, color='green'):
    if min <= val <= max:
        return 'background-color: %s' % color
    else:
        return ''
style_1 = df.style.applymap(highlight_vals, subset=['C'])

def highlight_vals(val, min=0, max=0.5, color='yellow'):
    if min <= val <= max:
        return 'background-color: %s' % color
    else:
        return ''
style_2 = df.style.applymap(highlight_vals, subset=['C'])

style_1.use(style_2.export())

writer = pd.ExcelWriter("C:\\13\\13\\zz.xlsx")
style_1.to_excel(writer, startrow=0, startcol=0, index = False)

writer.save()
</code>```

I kept both Styler objects, applied one on another and saved the resulting one to Excel instead of a dataframe. Also note that I fixed your conditions. Otherwise, you won't get yellow color because of min < val

ContentLicense: CC BY-SA 4.0

Title: Conditional formatting pandas

Body:
How do I colour in cells below 1 as green and cells between 0 and 0.5 yellow for Column C.

Current output:

   A    B    C
0 TT    WW   -5
1 AA    WW   0
2 DD    WW   5

Desired:

The following code for me just writes to Excel with no colour change.

import pandas as pd
import numpy as np

df = pd.read_excel("C:\\13\\13\\13.xlsx")
def highlight_vals(val, min=-1111, max=1, color='green'):
    if min < val < max:
        return 'background-color: %s' % color
    else:
        return ''
df.style.applymap(highlight_vals, subset=['C'])

def highlight_vals(val, min=0, max=0.5, color='yellow'):
    if min < val < max:
        return 'background-color: %s' % color
    else:
        return ''
df.style.applymap(highlight_vals, subset=['C'])

writer = pd.ExcelWriter("C:\\13\\13\\zz.xlsx")
df.to_excel(writer, startrow=0, startcol=0, index = False)

writer.save()

Body:
This should work:

import pandas as pd
import numpy as np

df = pd.read_excel("C:\\13\\13\\13.xlsx")
def highlight_vals(val, min=-1111, max=1, color='green'):
    if min <= val <= max:
        return 'background-color: %s' % color
    else:
        return ''
style_1 = df.style.applymap(highlight_vals, subset=['C'])

def highlight_vals(val, min=0, max=0.5, color='yellow'):
    if min <= val <= max:
        return 'background-color: %s' % color
    else:
        return ''
style_2 = df.style.applymap(highlight_vals, subset=['C'])

style_1.use(style_2.export())

writer = pd.ExcelWriter("C:\\13\\13\\zz.xlsx")
style_1.to_excel(writer, startrow=0, startcol=0, index = False)

writer.save()

I kept both Styler objects, applied one on another and saved the resulting one to Excel instead of a dataframe. Also note that I fixed your conditions. Otherwise, you won't get yellow color because of min < val


问:
Joining two tables when dates mismatch
I have Two tables Customer and Customer Address. Join criteria is on CustomerNo and Date. When date is not matching or not available on Customer Address table, I want to join with latest date available on the Customer Address

```<code>   Customer Table              Customer Address Table
    CustomerNo    Date        CustomerNo      Date       Addr
    123          1/1/2017     123            1/1/2017   sample1
    123          2/1/2017     123            2/1/2017   sample2
    123          2/11/2017
    123          3/1/2017
</code>```

Expected output

```<code>         Final Table

CustomerNo       Date      Addr
123             1/1/2017   sample1
123             2/1/2017   sample2
122             2/11/2017  sample2
123             3/1/2017   sample2
</code>```

When Dates are not available in Customer Address , match with last available date.

Thanks in advance.

答:
```<code>SELECT * FROM customer  c FULL OUTER JOIN address  a ON c.date=A.date WHERE a.date!=NULL
</code>```

or try this

```<code> SELECT * FROM customer  c FULL OUTER JOIN address  a ON c.date=A.date
</code>```

try this query .if any make comment.

Title: Joining two tables when dates mismatch

Body:
I have Two tables Customer and Customer Address. Join criteria is on CustomerNo and Date. When date is not matching or not available on Customer Address table, I want to join with latest date available on the Customer Address

   Customer Table              Customer Address Table
    CustomerNo    Date        CustomerNo      Date       Addr
    123          1/1/2017     123            1/1/2017   sample1
    123          2/1/2017     123            2/1/2017   sample2
    123          2/11/2017
    123          3/1/2017

Expected output

         Final Table

CustomerNo       Date      Addr
123             1/1/2017   sample1
123             2/1/2017   sample2
122             2/11/2017  sample2
123             3/1/2017   sample2

When Dates are not available in Customer Address , match with last available date.

Thanks in advance.

Body:
SELECT * FROM customer  c FULL OUTER JOIN address  a ON c.date=A.date WHERE a.date!=NULL

or try this

 SELECT * FROM customer  c FULL OUTER JOIN address  a ON c.date=A.date

try this query .if any make comment.


问:
How to create a DataFrame out of rows while retaining existing schema?
If I call map or mapPartition and my function receives rows from PySpark what is the natural way to create either a local PySpark or Pandas DataFrame? Something that combines the rows and retains the schema?

Currently I do something like:

```<code>def combine(partition):
    rows = [x for x in partition]
    dfpart = pd.DataFrame(rows,columns=rows[0].keys())
    pandafunc(dfpart)

mydf.mapPartition(combine)
</code>```

答:
It's actually possible to convert Spark rows to Pandas inside executors & finally create Spark DataFrame out of those output using mapPartitions. See my gist in Github

```<code># Convert function to use in mapPartitions
def rdd_to_pandas(rdd_):
    # convert rows to dict
    rows = (row_.asDict() for row_ in rdd_)
    # create pandas dataframe
    pdf = pd.DataFrame(rows)

    # Rows/Pandas DF can be empty depending on patiition logic.
    # Make sure to check it here, otherwise it will throw untrackable error
    if len(pdf) > 0:
        #
        # Do something with pandas DataFrame
        #
        pass

    return pdf.to_dict(orient='records')

# Create Spark DataFrame from resulting RDD
rdf = spark.createDataFrame(df.rdd.mapPartitions(rdd_to_pandas))
</code>```

Body:
If I call map or mapPartition and my function receives rows from PySpark what is the natural way to create either a local PySpark or Pandas DataFrame? Something that combines the rows and retains the schema?

Currently I do something like:

def combine(partition):
    rows = [x for x in partition]
    dfpart = pd.DataFrame(rows,columns=rows[0].keys())
    pandafunc(dfpart)

mydf.mapPartition(combine)

Body:
It's actually possible to convert Spark rows to Pandas inside executors & finally create Spark DataFrame out of those output using mapPartitions. See my gist in Github

# Convert function to use in mapPartitions
def rdd_to_pandas(rdd_):
    # convert rows to dict
    rows = (row_.asDict() for row_ in rdd_)
    # create pandas dataframe
    pdf = pd.DataFrame(rows)

    # Rows/Pandas DF can be empty depending on patiition logic.
    # Make sure to check it here, otherwise it will throw untrackable error
    if len(pdf) > 0:
        #
        # Do something with pandas DataFrame
        #
        pass

    return pdf.to_dict(orient='records')

# Create Spark DataFrame from resulting RDD
rdf = spark.createDataFrame(df.rdd.mapPartitions(rdd_to_pandas))


问:
What does parantheses mean in this case?
What do parentheses mean in the following code? Do these parentheses have a certain meaning?

```<code>function disableSubmit () {
  ...
}
</code>```

And also what do the parentheses mean if there is an e in between? For example,

```<code>function (e){
  ...
}
</code>```

答:
Parentheses represent arguments to the function. Empty parentheses means there are no arguments.

Also, in your second function, you have written it incorrectly (unless you are embedding the function as a parameter to another.) You need to name it like you did the first, like so

```<code>function someFunction(e){}
</code>```

Body:
What do parentheses mean in the following code? Do these parentheses have a certain meaning?

function disableSubmit () {
  ...
}

And also what do the parentheses mean if there is an e in between? For example,

function (e){
  ...
}

Body:
Parentheses represent arguments to the function. Empty parentheses means there are no arguments.

Also, in your second function, you have written it incorrectly (unless you are embedding the function as a parameter to another.) You need to name it like you did the first, like so

function someFunction(e){}


问:
SQL Server principal "dbo" does not exist,
I am getting the following error

```<code>Cannot execute as the database principal because the principal "dbo"
does not exist, this type of principal cannot be impersonated,
or you do not have permission.
</code>```

I read about ALTER AUTHORIZATION, but I have no idea what database this is happening in. This error is getting spit out very frequently, and grows the error log by about 1GB every day.

答:
Selected answer and some others are all good. I just want give a more SQL pure explanation. It comes to same solution that there is no (valid) database owner.

Database owner account dbo which is mentioned in error is always created with database. So it seems strange that it doesn't exist but you can check with two selects (or one but let's keep it simple).

```<code>SELECT [name],[sid]
FROM [DB_NAME].[sys].[database_principals]
WHERE [name] = 'dbo'
</code>```

which shows SID of dbo user in DB_NAME database and

```<code>SELECT [name],[sid]
FROM [sys].[syslogins]
</code>```

to show all logins (and their SIDs) for this SQL server instance. Notice it didn't write any db_name prefix, that's because every database has same information in that view.

So in case of error above there will not be login with SID that is assigned to database dbo user.

As explained above that usually happens when restoring database from another computer (where database and dbo user were created by different login). And you can fix it by changing ownership to existing login.

Body:
I am getting the following error

Cannot execute as the database principal because the principal "dbo"
does not exist, this type of principal cannot be impersonated,
or you do not have permission.

I read about ALTER AUTHORIZATION, but I have no idea what database this is happening in. This error is getting spit out very frequently, and grows the error log by about 1GB every day.

Body:
Selected answer and some others are all good. I just want give a more SQL pure explanation. It comes to same solution that there is no (valid) database owner.

Database owner account dbo which is mentioned in error is always created with database. So it seems strange that it doesn't exist but you can check with two selects (or one but let's keep it simple).

SELECT [name],[sid]
FROM [DB_NAME].[sys].[database_principals]
WHERE [name] = 'dbo'

which shows SID of dbo user in DB_NAME database and

SELECT [name],[sid]
FROM [sys].[syslogins]

to show all logins (and their SIDs) for this SQL server instance. Notice it didn't write any db_name prefix, that's because every database has same information in that view.

So in case of error above there will not be login with SID that is assigned to database dbo user.

As explained above that usually happens when restoring database from another computer (where database and dbo user were created by different login). And you can fix it by changing ownership to existing login.


问:
GWT + Spring MVC (RESTful web services)
I've been thinking all the day about how I can setup Spring MVC 3.0 (more specifically REST capabilities), with GWT. That is, I don't wanna use GWT RPC anymore, the communication will be made through REST. The problem is that I'm very new with the Spring Framework, and the only tutorials I found, they were using JSP, that's exactly where I get stuck... Is there a way to play with Spring without JSP page, only using the GWT view?</p>

答:
I assume what your trying to do is have a Spring controller return JSON or XML data?

There are two ways to do this:

use a ContentNegotiatingViewResolver

use HttpMessageConverters in combination with the @ResponseBody annotation

Both methods are covered in some detail here : http://hillert.blogspot.com/2011/01/rest-with-spring-contentnegotiatingview.html

The spring people cover the @RequestBody method here: http://blog.springsource.com/2010/01/25/ajax-simplifications-in-spring-3-0/

Here is the blog post covering the ContentNegotiatingViewResolver : http://blog.springsource.com/2009/03/08/rest-in-spring-3-mvc/

Sample code can be found at : https://src.springframework.org/svn/spring-samples/mvc-ajax/trunk/

I hope this helps.

ContentLicense: CC BY-SA 2.5

Title: GWT + Spring MVC (RESTful web services)


问:
Using javascript within HTML and only internal CSS
I'm working on a page to put on my firewall that displays various output depending on category I'm blocking.

I've spent about the last day trying to understand why the simple javascript I'm attempting to use is not resulting in my case statements properly rendering the results I want to see.

I can't use any external CSS in this case, and forgive the crazy colors. I like to use them to tell where all my
s are positioned while hacking together things like this.

Is the issue that my

答:
</p>

```<code>  //var cat = "<category/>";
        var cat = "C1"
  switch(cat)
  {
   case 'C1':
   var blockReason = "R1";
   break;
   case 'C2':
   var blockReason = "R2";
   break;
   case 'C3':
   var blockReason = "R3";
   break;
   case 'C4':
   var blockReason = "R4"
  }

    document.getElementById("blockReason").innerHTML = "<b>Block Reason: </b>"
  }
</script>
</code>```


问:
Put JButton over JLabel in a specific spot?
I am fairly new to JFrame and I'm trying to make a game and am stuck on the game menu. I have a background image and would like to place a button over top on a specific spot on the image. I tried putting the jlabel and jbutton in different jpanels and it doesn't help if anything it makes it worse.

This is my current code.

```<code>    import java.awt.BorderLayout;
    import java.io.IOException;
    import javax.swing.*;
    import javax.swing.WindowConstants;

    public class JavaApplication1 {

public static void main(String[] args) throws IOException {
    JFrame myFrame = new JFrame("Memory Game");
    myFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

    ImageIcon ii = new
    ImageIcon("C:\\Users\\Nancy\\Desktop\\Game\\start_pg.png");
    JLabel img = new JLabel(ii);

    JPanel image = new JPanel();

    ImageIcon btn = new
    ImageIcon("C:\\Users\\Nancy\\Desktop\\Game\\start_btn.png");
    JButton srt_btn = new JButton(btn);
    srt_btn.setSize(140, 75);
    srt_btn.setOpaque(false);
    srt_btn.setContentAreaFilled(false);
    srt_btn.setBorderPainted(false);
    srt_btn.setBorder(null);

    img.add(BorderLayout.SOUTH, srt_btn);
    image.add(BorderLayout.NORTH, img);

    myFrame.add(image);
    myFrame.pack();
    myFrame.setVisible(true);
}
}
</code>```

答: I found the solution, and it was using: button.setLocation(x,y) thanks :)

Body:
I am fairly new to JFrame and I'm trying to make a game and am stuck on the game menu. I have a background image and would like to place a button over top on a specific spot on the image. I tried putting the jlabel and jbutton in different jpanels and it doesn't help if anything it makes it worse.

This is my current code.

    import java.awt.BorderLayout;
    import java.io.IOException;
    import javax.swing.*;
    import javax.swing.WindowConstants;

    public class JavaApplication1 {

public static void main(String[] args) throws IOException {
    JFrame myFrame = new JFrame("Memory Game");
    myFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

    ImageIcon ii = new
    ImageIcon("C:\\Users\\Nancy\\Desktop\\Game\\start_pg.png");
    JLabel img = new JLabel(ii);

    JPanel image = new JPanel();

    ImageIcon btn = new
    ImageIcon("C:\\Users\\Nancy\\Desktop\\Game\\start_btn.png");
    JButton srt_btn = new JButton(btn);
    srt_btn.setSize(140, 75);
    srt_btn.setOpaque(false);
    srt_btn.setContentAreaFilled(false);
    srt_btn.setBorderPainted(false);
    srt_btn.setBorder(null);

    img.add(BorderLayout.SOUTH, srt_btn);
    image.add(BorderLayout.NORTH, img);

    myFrame.add(image);
    myFrame.pack();
    myFrame.setVisible(true);
}
}


问:
i can't dismiss the custom dialog
i'm trying to create a custom dialog with one button (TRY AGAIN)
this dialog testing if there is a internet connection or not. when user clicks (TRY AGAIN) button and if there is no internet connection custom dialog will showing again , and when there is internet connection dialog will dismissed

```<code> private void showDialog() {
        myDialog = new Dialog(getActivity());
        myDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        assert myDialog.getWindow() != null;
        myDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        myDialog.setContentView(R.layout.alert_dialog);
        text.setText(getResources().getText(R.string.nointernent));
        myDialog.setCancelable(false);
        Button tyragain = myDialog.findViewById(R.id.tryagainbtn);
        tyragain.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
              if (!isNetworkConnected()) {
                    showDialog();
                }
                else{
                    myDialog.dismiss();

                }
            }
        });

        myDialog.show();
}
</code>```

/**/

```<code>public  boolean isNetworkConnected() {
    ConnectivityManager connectionManager = (ConnectivityManager) getActivity().getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
    if (connectionManager == null) {
        return false;
    }
    NetworkInfo networkInfo = connectionManager.getActiveNetworkInfo();
    if (networkInfo == null) {
        return false;
    }
    return networkInfo.isConnected();
}
</code>```

答:
finally i solved my problem by added myDialog.isShowing()

```<code>if (!isNetworkConnected() && myDialog.isShowing()) {
                    showDialog();

                }
                else{
                    myDialog.dismiss();
                    refreshContent();
                }
</code>```

Title: i can't dismiss the custom dialog

Body:
i'm trying to create a custom dialog with one button (TRY AGAIN)
this dialog testing if there is a internet connection or not. when user clicks (TRY AGAIN) button and if there is no internet connection custom dialog will showing again , and when there is internet connection dialog will dismissed

 private void showDialog() {
        myDialog = new Dialog(getActivity());
        myDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        assert myDialog.getWindow() != null;
        myDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        myDialog.setContentView(R.layout.alert_dialog);
        text.setText(getResources().getText(R.string.nointernent));
        myDialog.setCancelable(false);
        Button tyragain = myDialog.findViewById(R.id.tryagainbtn);
        tyragain.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
              if (!isNetworkConnected()) {
                    showDialog();
                }
                else{
                    myDialog.dismiss();

                }
            }
        });

        myDialog.show();
}

/**/

public  boolean isNetworkConnected() {
    ConnectivityManager connectionManager = (ConnectivityManager) getActivity().getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
    if (connectionManager == null) {
        return false;
    }
    NetworkInfo networkInfo = connectionManager.getActiveNetworkInfo();
    if (networkInfo == null) {
        return false;
    }
    return networkInfo.isConnected();
}

Body:
finally i solved my problem by added myDialog.isShowing()

if (!isNetworkConnected() && myDialog.isShowing()) {
                    showDialog();

                }
                else{
                    myDialog.dismiss();
                    refreshContent();
                }


问:
Server Side GET
I want to merge a list into a show template on the server side.

How would I make a GET request to a list or a view from a show?  Do I have to call another library in the show to make a server side call or does couch have a native way to do this.  If a library, what is it?  I wish I could use couch.js server side basically.

答: At this time, CouchDB does not have server-side functions like this. The requirement for _show and _list functions is a complete sandbox. The show or list must always return the same output for the same input. (This is to support HTTP caching.)</p>

Title: Server Side GET


问:
How to make an HTTP get() on a local json file using rxjs?
I am trying to make a request to my local JSON file using Ionic typescript, and retrieve all of the game objects in my JSON file. Here is what I have so far:

```<code>import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { map } from 'rxjs/operators/map';
import { catchError } from 'rxjs/operators/catchError';
import { Observable } from "rxjs/Observable";
import { Game } from "../../models/Game";

import { Http, Response, RequestOptions, Headers } from '@angular/http';

/*
  Generated class for the GamesProvider provider.

  See https://angular.io/guide/dependency-injection for more info on providers
  and Angular DI.
*/
@Injectable()
export class GamesProvider {
  constructor(public http: HttpClient) {

  }

  public getGames(): Observable<Array<Game>> {

      return this.http.get('/assets/games.json').pipe(
        map((res: Response) => res.json().games),
        catchError(this.handleError)
      );
  }

  public handleError(error: any) {
      // log error
      // could be something more sofisticated
      let errorMsg = error.message || `Yikes! There was a problem with our hyperdrive device and we couldn't retrieve your data!`
      console.error(errorMsg);

      // throw an application level error
      return Observable.throw(errorMsg);
  }
}
</code>```

I am getting a result that looks like this when I call the getGames() function:

```<code>operator
    :CatchOperator {caught: Observable, selector: ƒ}
    source
    :Observable {_isScalar: false, source: Observable, operator: MapOperator}
    _isScalar
    :false
    __proto__
    :Object
</code>```

What I am expecting is an Observable Array of Game objects.

Game.ts:

```<code>export class Game {
    gameid: number
    genres: string
    images: string
    name: string
    developer: string
    publisher: string
    date: string
    description: string
    players: number
}
</code>```

This is what my JSON file looks like:

```<code>{
    "games":[
  {
    "Id": 1,
    "name": "007: GoldenEye",
    "genres": "Action/First-Person Shooter",
    "date": "25-Aug-97",
    "images": "007: GoldenEye.png",
    "developer": "Rare",
    "publisher": "Nintendo",
    "description": "A video game released for the Nintendo 64.",
    "players": 4
  },
  {
    "Id": 2,
    "name": "007: The World Is Not Enough",
    "genres": "Action/First-Person Shooter",
    "date": "1-Nov-00",
    "images": "007: The World Is Not Enough.png",
    "developer": "Eurocom",
    "publisher": "Electronic Arts",
    "description": "A video game released for the Nintendo 64.",
    "players": 4
  },
...
...
...
 ]
}
</code>```

答:
I believe instead of the pipe you need map (and just get rid of pipe)

```<code>return this.http.get('/assets/games.json').map(
(res: Response) => res.json().games).catch(this.handleError);
</code>```

Check the docs: https://angular.io/guide/http you could also do it with a subscribe

Body:
I am trying to make a request to my local JSON file using Ionic typescript, and retrieve all of the game objects in my JSON file. Here is what I have so far:

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { map } from 'rxjs/operators/map';
import { catchError } from 'rxjs/operators/catchError';
import { Observable } from "rxjs/Observable";
import { Game } from "../../models/Game";

import { Http, Response, RequestOptions, Headers } from '@angular/http';

/*
  Generated class for the GamesProvider provider.

  See https://angular.io/guide/dependency-injection for more info on providers
  and Angular DI.
*/
@Injectable()
export class GamesProvider {
  constructor(public http: HttpClient) {

  }

  public getGames(): Observable<Array<Game>> {

      return this.http.get('/assets/games.json').pipe(
        map((res: Response) => res.json().games),
        catchError(this.handleError)
      );
  }

  public handleError(error: any) {
      // log error
      // could be something more sofisticated
      let errorMsg = error.message || `Yikes! There was a problem with our hyperdrive device and we couldn't retrieve your data!`
      console.error(errorMsg);

      // throw an application level error
      return Observable.throw(errorMsg);
  }
}

I am getting a result that looks like this when I call the getGames() function:

operator
    :CatchOperator {caught: Observable, selector: ƒ}
    source
    :Observable {_isScalar: false, source: Observable, operator: MapOperator}
    _isScalar
    :false
    __proto__
    :Object

What I am expecting is an Observable Array of Game objects.

Game.ts:

export class Game {
    gameid: number
    genres: string
    images: string
    name: string
    developer: string
    publisher: string
    date: string
    description: string
    players: number
}

This is what my JSON file looks like:

{
    "games":[
  {
    "Id": 1,
    "name": "007: GoldenEye",
    "genres": "Action/First-Person Shooter",
    "date": "25-Aug-97",
    "images": "007: GoldenEye.png",
    "developer": "Rare",
    "publisher": "Nintendo",
    "description": "A video game released for the Nintendo 64.",
    "players": 4
  },
  {
    "Id": 2,
    "name": "007: The World Is Not Enough",
    "genres": "Action/First-Person Shooter",
    "date": "1-Nov-00",
    "images": "007: The World Is Not Enough.png",
    "developer": "Eurocom",
    "publisher": "Electronic Arts",
    "description": "A video game released for the Nintendo 64.",
    "players": 4
  },
...
...
...
 ]
}

Body:
I believe instead of the pipe you need map (and just get rid of pipe)

return this.http.get('/assets/games.json').map(
(res: Response) => res.json().games).catch(this.handleError);

Check the docs: https://angular.io/guide/http you could also do it with a subscribe


问:
Validation errors when linking authentication with Dialogflow / Google Action
We are trying to get DialogFlow / Google Actions to link to an external OAuth account within a conversation. Upon following the examples we are consistently getting request validation errors that we don't know how to resolve. As far as I can tell we are doing everything by the book.

Our questions:

Why won't DialogFlow kick off the authentication process?

The documented webhook response for requesting the sign-in helper not have the same schema as a standard DialogFlow webhook response. Is the sign-in helper response supposed to be used for something else?...

Things we have tried:

We have configured our app and OAuth credentials per the documentation

We have verified that we can fetch an OAuth token from the service via the OAuth 2.0 playground

We have enabled transactions on the Action.

Our intent code is as follows:

```<code>const { DialogflowApp } = require('actions-on-google');
const { ActionsSdkApp } = require('actions-on-google');

function processV2Request (request, response) {
  ...
  let app = new DialogflowApp({request: request, response: response});
  let sdkapp = new ActionsSdkApp({request: request, response: response});
  const actionHandlers = {
    'pto': () => {
        app.askForSignIn();
    }
    ...
  }
  ...
}
</code>```

When we execute this intent, we receive the following debug error message about a speech field.

```<code>"agentToAssistantJson": {
  "message": "Unexpected apiai response format: Empty speech response",
  "apiResponse": {
    "id": "751e4716-a94d-4d11-908d-3ee193092d9c",
    "timestamp": "2017-12-05T19:52:01.962Z",
    "lang": "en-us",
    "result": {},
    "status": {
      "code": 206,
      "errorType": "partial_content",
      "errorDetails": "Webhook call failed. Error: Failed to parse webhook JSON response: Cannot find field: speech in message google.cloud.dialogflow.v2beta1.WebhookResponse."
    }
  }
}
</code>```

If instead we try using the ActionsSdkApp, sdkapp.askForSignIn(), we get an error message about a conversation_token field.

```<code>"agentToAssistantJson": {
  "message": "Unexpected apiai response format: Empty speech response",
  "apiResponse": {
    "id": "7de79093-6db8-44ee-8717-16b0f317174c",
    "timestamp": "2017-12-05T19:54:29.709Z",
    "lang": "en-us",
    "result": {},
    "status": {
      "code": 206,
      "errorType": "partial_content",
      "errorDetails": "Webhook call failed. Error: Failed to parse webhook JSON response: Cannot find field: conversation_token in message google.cloud.dialogflow.v2beta1.WebhookResponse."
    },
  }
}
</code>```

And if it's helpful, here's our package.json. It's the DialogFlow default as of recently, with a bumped up version of actions-on-google.

```<code>{
  "name": "dialogflowFirebaseFulfillment",
  "description": "This is the default fulfillment for a Dialogflow agents using Cloud Functions for Firebase",
  "version": "0.0.1",
  "private": true,
  "license": "Apache Version 2.0",
  "author": "Google Inc.",
  "engines": {
    "node": "~6.0"
  },
  "scripts": {
    "start": "firebase serve --only functions:dialogflowFirebaseFulfillment",
    "deploy": "firebase deploy --only functions:dialogflowFirebaseFulfillment"
  },
  "dependencies": {
    "actions-on-google": "^1.6.x",
    "firebase-admin": "^4.2.1",
    "firebase-functions": "^0.5.7",
    "apiai": "^4.0.3"
  }
}
</code>```

答: We determined that in addition to having Transactions enabled for the app, you must also change the Development Sandbox toggled to Active:

Body:
We are trying to get DialogFlow / Google Actions to link to an external OAuth account within a conversation. Upon following the examples we are consistently getting request validation errors that we don't know how to resolve. As far as I can tell we are doing everything by the book.

Our questions:

Why won't DialogFlow kick off the authentication process?

The documented webhook response for requesting the sign-in helper not have the same schema as a standard DialogFlow webhook response. Is the sign-in helper response supposed to be used for something else?...

Things we have tried:

We have configured our app and OAuth credentials per the documentation

We have verified that we can fetch an OAuth token from the service via the OAuth 2.0 playground

We have enabled transactions on the Action.

Our intent code is as follows:

const { DialogflowApp } = require('actions-on-google');
const { ActionsSdkApp } = require('actions-on-google');

function processV2Request (request, response) {
  ...
  let app = new DialogflowApp({request: request, response: response});
  let sdkapp = new ActionsSdkApp({request: request, response: response});
  const actionHandlers = {
    'pto': () => {
        app.askForSignIn();
    }
    ...
  }
  ...
}

When we execute this intent, we receive the following debug error message about a speech field.

"agentToAssistantJson": {
  "message": "Unexpected apiai response format: Empty speech response",
  "apiResponse": {
    "id": "751e4716-a94d-4d11-908d-3ee193092d9c",
    "timestamp": "2017-12-05T19:52:01.962Z",
    "lang": "en-us",
    "result": {},
    "status": {
      "code": 206,
      "errorType": "partial_content",
      "errorDetails": "Webhook call failed. Error: Failed to parse webhook JSON response: Cannot find field: speech in message google.cloud.dialogflow.v2beta1.WebhookResponse."
    }
  }
}

If instead we try using the ActionsSdkApp, sdkapp.askForSignIn(), we get an error message about a conversation_token field.

"agentToAssistantJson": {
  "message": "Unexpected apiai response format: Empty speech response",
  "apiResponse": {
    "id": "7de79093-6db8-44ee-8717-16b0f317174c",
    "timestamp": "2017-12-05T19:54:29.709Z",
    "lang": "en-us",
    "result": {},
    "status": {
      "code": 206,
      "errorType": "partial_content",
      "errorDetails": "Webhook call failed. Error: Failed to parse webhook JSON response: Cannot find field: conversation_token in message google.cloud.dialogflow.v2beta1.WebhookResponse."
    },
  }
}

And if it's helpful, here's our package.json. It's the DialogFlow default as of recently, with a bumped up version of actions-on-google.

{
  "name": "dialogflowFirebaseFulfillment",
  "description": "This is the default fulfillment for a Dialogflow agents using Cloud Functions for Firebase",
  "version": "0.0.1",
  "private": true,
  "license": "Apache Version 2.0",
  "author": "Google Inc.",
  "engines": {
    "node": "~6.0"
  },
  "scripts": {
    "start": "firebase serve --only functions:dialogflowFirebaseFulfillment",
    "deploy": "firebase deploy --only functions:dialogflowFirebaseFulfillment"
  },
  "dependencies": {
    "actions-on-google": "^1.6.x",
    "firebase-admin": "^4.2.1",
    "firebase-functions": "^0.5.7",
    "apiai": "^4.0.3"
  }
}


问:
Why is my image so high on the page?
I have two buttons on a webpage, I am trying to make the Clear button be a little lower, to align with the Search button.  Why is the Clear button so high?

Here is a live example: http://www.davidjpotter.com/temp/test.php

```<code><table border=1>
<tr>
<td>
  <button type="submit">Search</button>
  <img src="../images/button-clear.png">
</td>
</tr>
</table>
</code>```

答: This has to do with vertical alignment of the image which is an inline element and it's set to the baseline. Add 'vertical-align:bottom' to line them up.</p>

Title: Why is my image so high on the page?

Body:
I have two buttons on a webpage, I am trying to make the Clear button be a little lower, to align with the Search button.  Why is the Clear button so high?

Here is a live example: http://www.davidjpotter.com/temp/test.php

  <button type="submit">Search</button>


问:
Ruby require 'file' doesn't work but require './file' does. Why?
I have a folder full of ruby files, and when I try and require one file in another that is in the same directory using require 'file' I get a LoadError but when I use require './file' everything works fine. Can somebody explain to me why this happens and if there is any way I can require a file without adding a ./ onto the file?

(Picture of directory):

答:
Though it is very old post I think some extra information will be very useful to beginner.

The best way to think of require is in relation to the UNIX $PATH variable. Just by way of a refresher, the $PATH variable in UNIX is a list of directories where executables can be found. So when you type the name of a program on any UNIX terminal, your computer is looking through the executable files in the directories specified in your $PATH variable. require does something very similar. When, for example, you write require 'set' at the top of your Ruby file, you are telling Ruby to look through a bunch of directories for a library called set.rb (Ruby's set library).

So where does Ruby look for set.rb? Well, once again, Ruby has something very similar to UNIX's $PATH variable. It is the global variable $LOAD_PATH also sometimes known by it's ugly and undescriptive alias $: (which I don't suggest using by the way--short though it may be). It is an array of directory names where Ruby looks when it comes across a require.

There is nice informative post here where you can get more information about require, load and require_relative


问:
the link between fcntl and sockets
I have read about socket, connecting, fcntl, buffers, etc.
But I don't know what the link between the sockets and the fcntl function is.
I only know that sockets are used to make a connection, and fcntl is used to control open files. I don't know how fcntl is used to control files and how it is different from the fopen, fwrite, fclose functions.
So could anyone help with this, because I am stuck.</p>

答:
fcntl system call is used to perform operations on an open file descriptor - getting or setting the file descriptor flags (e.g. changing O_APPEND or O_NONBLOCK status flags).

int fcntl(int fd, int cmd, ... /* arg */ );

An open socket will be referenced by a file descriptor (sockFd in this case):

sockFd = socket (PF_LOCAL, SOCK_DGRAM, 0);

An example - to make the socket non-blocking, use fcntl to change the status of the socket's file descriptor. * Note simplified code:*

int flags = fcntl(sockFd, F_GETFL, 0);   /* get socket's flags */
 flags |= O_NONBLOCK;  /* Add O_NONBLOCK status to socket descriptor's flags */
 status = fcntl(sockFd, F_SETFL, flags); /* Apply the new flags to the socket */

Title: the link between fcntl and sockets


问:
Spring webflux custom authentication for API
I am creating an API for an Angular 5 application. I would like to use JWT for authentication.

I would like to use the features that are provided by spring security so I can easily work with roles.

I managed to disable basic authentication. But when using http.authorizeExchange().anyExchange().authenticated(); I still get a login prompt.

I would like to just give a 403 instead of the prompt. So overriding the login prompt by a "thing"(Is it a filter?) that checks the Authorization header for the token.

The login I just want to do in a controller that will return a JWT token. But what spring security bean I should use for checking user credentials? I can build my own services and repositories, but I would like to use the features provided by spring security as much as possible.

The short version of this question is just:

How can I customize spring security's authentication?

What beans do I have to create?

Where do I have to put the configuration? (I now have a bean of SecurityWebFilterChain)

The only documentation I could find about authentication in webflux with spring security is this: https://docs.spring.io/spring-security/site/docs/5.0.0.BUILD-SNAPSHOT/reference/htmlsingle/#jc-webflux

答:
Thanks Jan you helped me a lot with your example to customize authentication in my Spring Webflux application and secure access to apis.

In my case I just need to read a header to set user roles and I want Spring security to check user authorizations to secure access to my methods.

You gave the key with custom http.securityContextRepository(this.securityContextRepository); in SecurityConfiguration (no need of a custom authenticationManager).

Thanks to this SecurityContextRepository I was able to build and set a custom authentication (simplified below).

```<code>@Override
public Mono<SecurityContext> load(ServerWebExchange serverWebExchange) {
    String role = serverWebExchange.getRequest().getHeaders().getFirst("my-header");
    Authentication authentication =
       new AnonymousAuthenticationToken("authenticated-user", someUser,  AuthorityUtils.createAuthorityList(role) );

    return Mono.just(new SecurityContextImpl(authentication));
}
</code>```

And thus I can secure my methods using these roles:

```<code>@Component
public class MyService {
    @PreAuthorize("hasRole('ADMIN')")
    public Mono<String> checkAdmin() {
        // my secure method
   }
}
</code>```

Body:
Thanks Jan you helped me a lot with your example to customize authentication in my Spring Webflux application and secure access to apis.

In my case I just need to read a header to set user roles and I want Spring security to check user authorizations to secure access to my methods.

You gave the key with custom http.securityContextRepository(this.securityContextRepository); in SecurityConfiguration (no need of a custom authenticationManager).

Thanks to this SecurityContextRepository I was able to build and set a custom authentication (simplified below).

@Override
public Mono<SecurityContext> load(ServerWebExchange serverWebExchange) {
    String role = serverWebExchange.getRequest().getHeaders().getFirst("my-header");
    Authentication authentication =
       new AnonymousAuthenticationToken("authenticated-user", someUser,  AuthorityUtils.createAuthorityList(role) );

    return Mono.just(new SecurityContextImpl(authentication));
}

And thus I can secure my methods using these roles:

@Component
public class MyService {
    @PreAuthorize("hasRole('ADMIN')")
    public Mono<String> checkAdmin() {
        // my secure method
   }
}


问:
Entity Framework generating Script that runs with errors
I am working on a solution using Entity Framework. I use Code First Work Flow to update my database by creating migrations. Everything works fine and now I want to deploy to production. I used Update-Database -script -SourceMigration:InitialModel from Package Manager Console to generate the DB script I want to run on the production database. Here's the part of the script file generated:

```<code>    CREATE TABLE [dbo].[Projects] (
        [Id] [int] NOT NULL IDENTITY,
        [Title] [nvarchar](max),
        [OwnerId] [int] NOT NULL,
        [StartDate] [datetime] NOT NULL,
        [EndDate] [datetime] NOT NULL,
        [ProjectStatus] [int] NOT NULL,
        CONSTRAINT [PK_dbo.Projects] PRIMARY KEY ([Id])
    )

    INSERT [dbo].[__MigrationHistory]([MigrationId], [ContextKey], [Model],
    [ProductVersion])
    VALUES (N'201711231319470_AddProjectTableToDB',
    N'ErdisERP_AmpleAdminTheme.Migrations.Configuration', A Large Random
    String, N'6.1.3-40302')
    More SQL codes...
</code>```

Here's the error produced Msg 208, Level 16, State 1, Line 10
Invalid object name 'dbo.__MigrationHistory'.

P.S: I am just starting out ASP.NET MVC5. I'll appreciate any pointers. Thank you.

答:
It appears you do not have the __MigrationHistory table. When you use -SourceMigration:InitialModel EF will use that as a starting point. If you want to tell EF to use a blank database as the starting point, use $InitialDatabase which will also include code to create __MigrationHistory :

```<code>Update-Database -Script -SourceMigration: $InitialDatabase
</code>```

Body:
I am working on a solution using Entity Framework. I use Code First Work Flow to update my database by creating migrations. Everything works fine and now I want to deploy to production. I used Update-Database -script -SourceMigration:InitialModel from Package Manager Console to generate the DB script I want to run on the production database. Here's the part of the script file generated:

    CREATE TABLE [dbo].[Projects] (
        [Id] [int] NOT NULL IDENTITY,
        [Title] [nvarchar](max),
        [OwnerId] [int] NOT NULL,
        [StartDate] [datetime] NOT NULL,
        [EndDate] [datetime] NOT NULL,
        [ProjectStatus] [int] NOT NULL,
        CONSTRAINT [PK_dbo.Projects] PRIMARY KEY ([Id])
    )

    INSERT [dbo].[__MigrationHistory]([MigrationId], [ContextKey], [Model],
    [ProductVersion])
    VALUES (N'201711231319470_AddProjectTableToDB',
    N'ErdisERP_AmpleAdminTheme.Migrations.Configuration', A Large Random
    String, N'6.1.3-40302')
    More SQL codes...

Here's the error produced Msg 208, Level 16, State 1, Line 10
Invalid object name 'dbo.__MigrationHistory'.

P.S: I am just starting out ASP.NET MVC5. I'll appreciate any pointers. Thank you.

Body:
It appears you do not have the __MigrationHistory table. When you use -SourceMigration:InitialModel EF will use that as a starting point. If you want to tell EF to use a blank database as the starting point, use $InitialDatabase which will also include code to create __MigrationHistory :

Update-Database -Script -SourceMigration: $InitialDatabase


问:
duplicate value's in another table
I have two tables: table1 and table2.

I have a .csv file which contains a lot of duplicates and I place them in table2. So I have a clean table1 with no duplicates and another table with all the duplicates from table1. How can I do this? I have this code which only places the .csv file into table1 (with duplicates):

I have placed the values in an array this works:

```<code>$sql = "INSERT INTO table1 (aanhef,achternaam,email,bedrag)
VALUES('$aanhef','$achternaam','$email','$bedrag')";

mysql_query($sql); "
</code>```

答:
```<code>$data=file_get_contents('testing.csv');

$data=explode(',',$data);

$uniqueValues = array_unique($data);
$duplicateValues = array_diff_assoc($data, $uniqueValues);
print_r($uniqueValues);
echo '</br>';
print_r($duplicateValues);
</code>```

This code splits a csv file into 2 arrays, the ones which have the duplicates and the ones that have only unique values as you asked. After that you can parse the array and execute your sql queries.

Title: duplicate value's in another table

Body:
I have two tables: table1 and table2.

I have a .csv file which contains a lot of duplicates and I place them in table2. So I have a clean table1 with no duplicates and another table with all the duplicates from table1. How can I do this? I have this code which only places the .csv file into table1 (with duplicates):

I have placed the values in an array this works:

$sql = "INSERT INTO table1 (aanhef,achternaam,email,bedrag)
VALUES('$aanhef','$achternaam','$email','$bedrag')";

mysql_query($sql); "

Body:
$data=file_get_contents('testing.csv');

$data=explode(',',$data);

$uniqueValues = array_unique($data);
$duplicateValues = array_diff_assoc($data, $uniqueValues);
print_r($uniqueValues);
echo '</br>';
print_r($duplicateValues);

This code splits a csv file into 2 arrays, the ones which have the duplicates and the ones that have only unique values as you asked. After that you can parse the array and execute your sql queries.


问:
Using Either correctly
So I have the following function:

```<code>chk2 :: [(Integer,Integer)] -> Either [(Integer,Integer)] (Integer,Integer)
chk2 i@((n,_):_)
  | chkp (prod $ lgst i)==True = Right $ lgst i
  | lgst i==i!!0 = Left $ chk2 $ (4-2,4-2):next i
  | otherwise = Left $ chk2 $ next i
  where prod (a,b) = a*b
        lgst = foldl1 (\(a,b) (c,d) -> if prod (a,b) > prod (c,d) then (a,b) else (c,d))
        next t = map (\(a,b) -> if (a,b)==lgst t then (a-1,b+1) else (a,b)) t
</code>```

along with this error:

```<code>runhugs: Error occurred
ERROR "4/4.hs":14 - Type error in explicitly typed binding
*** Term           : chk2
*** Type           : [(Integer,Integer)] -> Either (Either [(Integer,Integer (Integer,Integer)) (Integer,Integer)
*** Does not match : [(Integer,Integer)] -> Either [(Integer,Integer)] (Integer,Integer)
</code>```

I'm trying to get this function to either end up with an (a,b) i.e. first guard or [(a,b)] i.e. the latter two guards. The basic problem is in the latter two guards.. if I take out the recursion, everything works fine, but I'm not sure how to define the type signature when returning the function itself.

答:
The problem is with how you recurse.

According to the type of chk2, chk2 $ next i is of type Either [(Integer,Integer)] (Integer,Integer).  Left is of type b -> Either b a, so  Left $ chk2 $ next i is of type Either (Either [(Integer,Integer)] (Integer,Integer)) a for some unspecified type a.

Left $ chk2 $ (4-2,4-2):next i has a similar problem.

To fix, you need to decide how you want to handle the recursive value.

Easy fix:

```<code>  | lgst i==i!!0 = chk2 $ (4-2,4-2):next i
  | otherwise = chk2 $ next i
</code>```

However, I doubt this is what you want, since it means all your results will be Right.
I'm not sure how to do what you want, because I'm not sure what you want.

What does a list result mean?  What does a non-list result mean?

What you probably want to do is pattern match the result of the recursion, transforming Right pair -> Left [pair], perhaps appending some other result to the front.

As an example, I'll construct a recursive function with a similar type signature.  Let foo be a function that takes a list of integers, and:

if the first element of the list is the maximum of the whole list, returns that element

otherwise, return a subsequence of the list, where each is the maximum of all the elements between it and the next element in the subsequence (or the end)

To do this:

```<code>foo :: [Integer] -> Either [Integer] Integer
foo [] = Left []
foo (x:xs) = case foo xs of
  Left ys -> if all (<=x) ys
              then Right x
              else let (_,ys') = break (>x) ys in Left (x:ys')
  Right y -> if x >= y
              then Right x
              else Left [x,y]
</code>```

Note how I use case to pattern match on the result of the recursive call to foo.

Title: Using Either correctly

Body:
So I have the following function:

chk2 :: [(Integer,Integer)] -> Either [(Integer,Integer)] (Integer,Integer)
chk2 i@((n,_):_)
  | chkp (prod $ lgst i)==True = Right $ lgst i
  | lgst i==i!!0 = Left $ chk2 $ (4-2,4-2):next i
  | otherwise = Left $ chk2 $ next i
  where prod (a,b) = a*b
        lgst = foldl1 (\(a,b) (c,d) -> if prod (a,b) > prod (c,d) then (a,b) else (c,d))
        next t = map (\(a,b) -> if (a,b)==lgst t then (a-1,b+1) else (a,b)) t

along with this error:

runhugs: Error occurred
ERROR "4/4.hs":14 - Type error in explicitly typed binding
*** Term           : chk2
*** Type           : [(Integer,Integer)] -> Either (Either [(Integer,Integer (Integer,Integer)) (Integer,Integer)
*** Does not match : [(Integer,Integer)] -> Either [(Integer,Integer)] (Integer,Integer)

I'm trying to get this function to either end up with an (a,b) i.e. first guard or [(a,b)] i.e. the latter two guards. The basic problem is in the latter two guards.. if I take out the recursion, everything works fine, but I'm not sure how to define the type signature when returning the function itself.

Body:
The problem is with how you recurse.

According to the type of chk2, chk2 $ next i is of type Either [(Integer,Integer)] (Integer,Integer).  Left is of type b -> Either b a, so  Left $ chk2 $ next i is of type Either (Either [(Integer,Integer)] (Integer,Integer)) a for some unspecified type a.

Left $ chk2 $ (4-2,4-2):next i has a similar problem.

To fix, you need to decide how you want to handle the recursive value.

Easy fix:

  | lgst i==i!!0 = chk2 $ (4-2,4-2):next i
  | otherwise = chk2 $ next i

However, I doubt this is what you want, since it means all your results will be Right.
I'm not sure how to do what you want, because I'm not sure what you want.

What does a list result mean?  What does a non-list result mean?

What you probably want to do is pattern match the result of the recursion, transforming Right pair -> Left [pair], perhaps appending some other result to the front.

As an example, I'll construct a recursive function with a similar type signature.  Let foo be a function that takes a list of integers, and:

if the first element of the list is the maximum of the whole list, returns that element

otherwise, return a subsequence of the list, where each is the maximum of all the elements between it and the next element in the subsequence (or the end)

To do this:

foo :: [Integer] -> Either [Integer] Integer
foo [] = Left []
foo (x:xs) = case foo xs of
  Left ys -> if all (<=x) ys
              then Right x
              else let (_,ys') = break (>x) ys in Left (x:ys')
  Right y -> if x >= y
              then Right x
              else Left [x,y]

Note how I use case to pattern match on the result of the recursive call to foo.


问:
Vertical Blue, Green, or Gray lines in Android Studio
I am seeing these vertical blue and green lines on the right border of the Android Studio:

What do these lines mean? Is there a way to remove them as they are a little annoying. I don't remember seeing them in previous versions of Android Studio.

答:
It's look like git is initialize/contain in your project.
If you update git initialize code then you can see those different blue/green color as per add/update/deletion of code.

delete '.git' folder from your project root directory and restart your android studio.

Note: '.git' folder is hidden folder.


问:
How to convert DispatchTimeInterval to NSTimeInterval (or Double)?
I need to subtract a DispatchTimeInterval from an NSTimeInterval (or Double).

Is there a standard way to convert a DispatchTimeInterval to an NSTimeInterval?

答:
DispatchTimeInterval is a enum:

```<code>public enum DispatchTimeInterval : Equatable {
    case seconds(Int)
    case milliseconds(Int)
    case microseconds(Int)
    case nanoseconds(Int)
    case never
}
</code>```

You can initialize DispatchTimeInterval using:

```<code>    let tenSeconds: DispatchTimeInterval = .seconds(10)
    let tenNanoseconds: DispatchTimeInterval = .nanoseconds(10)
</code>```

To get values from enum you need to match value with a case values in enum

```<code>    if case .seconds(let value) = tenSeconds {
        print("DispatchTimeInterval is seconds \(value)")
    } else if case .nanoseconds(let value) = tenNanoseconds {
        print("DispatchTimeInterval is seconds \(value)")
    }
</code>```

Converting function might be look following:

```<code>func toDouble(_ interval: DispatchTimeInterval) -> Double? {
        var result: Double? = 0

        switch interval {
        case .seconds(let value):
            result = Double(value)
        case .milliseconds(let value):
            result = Double(value)*0.001
        case .microseconds(let value):
            result = Double(value)*0.000001
        case .nanoseconds(let value):
            result = Double(value)*0.000000001

        case .never:
            result = nil
        }

        return result
    }
</code>```

More about Enumeration see in Apple Documentation

UPDATE:

Create extension to DispatchTimeInterval

```<code>extension DispatchTimeInterval {
    func toDouble() -> Double? {
        var result: Double? = 0

        switch self {
        case .seconds(let value):
            result = Double(value)
        case .milliseconds(let value):
            result = Double(value)*0.001
        case .microseconds(let value):
            result = Double(value)*0.000001
        case .nanoseconds(let value):
            result = Double(value)*0.000000001

        case .never:
            result = nil
        }

        return result
    }
}
</code>```

Body:
DispatchTimeInterval is a enum:

public enum DispatchTimeInterval : Equatable {
    case seconds(Int)
    case milliseconds(Int)
    case microseconds(Int)
    case nanoseconds(Int)
    case never
}

You can initialize DispatchTimeInterval using:

    let tenSeconds: DispatchTimeInterval = .seconds(10)
    let tenNanoseconds: DispatchTimeInterval = .nanoseconds(10)

To get values from enum you need to match value with a case values in enum

    if case .seconds(let value) = tenSeconds {
        print("DispatchTimeInterval is seconds \(value)")
    } else if case .nanoseconds(let value) = tenNanoseconds {
        print("DispatchTimeInterval is seconds \(value)")
    }

Converting function might be look following:

func toDouble(_ interval: DispatchTimeInterval) -> Double? {
        var result: Double? = 0

        switch interval {
        case .seconds(let value):
            result = Double(value)
        case .milliseconds(let value):
            result = Double(value)*0.001
        case .microseconds(let value):
            result = Double(value)*0.000001
        case .nanoseconds(let value):
            result = Double(value)*0.000000001

        case .never:
            result = nil
        }

        return result
    }

More about Enumeration see in Apple Documentation

UPDATE:

Create extension to DispatchTimeInterval

extension DispatchTimeInterval {
    func toDouble() -> Double? {
        var result: Double? = 0

        switch self {
        case .seconds(let value):
            result = Double(value)
        case .milliseconds(let value):
            result = Double(value)*0.001
        case .microseconds(let value):
            result = Double(value)*0.000001
        case .nanoseconds(let value):
            result = Double(value)*0.000000001

        case .never:
            result = nil
        }

        return result
    }
}


问:
Apache NiFi : custom properties file, read its properties dynamically
I am trying to use the "nifi.variable.registry.properties" in nifi.properties files to put my custom variables which will be used by my controller services. This is working fine for all the variables.

My requirement that is there any way I can use this variable or a conf file supplied to this variable, to evaluate or run some script to derive the value of the property?

e.g.
nifi.variable.registry.properties=my_path/to_conf/conf.file

my_path/to_conf/conf.file contents:

```<code>db_user: <my_db_user>
db_password: <my_db_password>
</code>```

.
.

Now, I don't want the password to be written as above. I need something like this:

```<code>db_password: <my_script_to_decode_pass_from_password_keyfile>
</code>```

Basically, I have a keyfile and encrypted password, a script to decrypt it based on the key. I want to use that script (which can be run) as a value of this property. So whenever this variable is used in controller services, the said script will execute and decrypt the password and assign it to "db_password" and it will be used further.

If above is not possible; then can I give that script (what format of output?) as a value to "nifi.variable.registry.properties" directly, so it runs and evaluates the password?

答:
Currently it isn't possible to do what you are describing...

NiFi does have support for encrypted configuration, but currently it only supports encrypted properties in nifi.properties and a couple of other config files like login-identity-providers.xml:

https://nifi.apache.org/docs/nifi-docs/html/administration-guide.html#encrypted-passwords-in-configuration-files

It might be possible to extend this feature to encrypt values inside files specified with nifi.variable.registry.properties.

Body:
I am trying to use the "nifi.variable.registry.properties" in nifi.properties files to put my custom variables which will be used by my controller services. This is working fine for all the variables.

My requirement that is there any way I can use this variable or a conf file supplied to this variable, to evaluate or run some script to derive the value of the property?

e.g.
nifi.variable.registry.properties=my_path/to_conf/conf.file

my_path/to_conf/conf.file contents:

db_user: <my_db_user>
db_password: <my_db_password>

.
.

Now, I don't want the password to be written as above. I need something like this:

db_password: <my_script_to_decode_pass_from_password_keyfile>

Basically, I have a keyfile and encrypted password, a script to decrypt it based on the key. I want to use that script (which can be run) as a value of this property. So whenever this variable is used in controller services, the said script will execute and decrypt the password and assign it to "db_password" and it will be used further.

If above is not possible; then can I give that script (what format of output?) as a value to "nifi.variable.registry.properties" directly, so it runs and evaluates the password?


问:
formatting numbers in input with ngModel
I've got an input linked to the object that contains relevant data:

```<code>  <input type="text" [(ngModel)]="element.number" name="someName">
</code>```

element is an object with property number. number is of type number and it is always whole number.

I'd like to display a formated value of input (transform seconds into a more human readable format). Lets say element.number is 140, than the displayed value is 00:02:20. If the element.number is 22, than the displayed value is 00:00:22. If element.number is 3670, than the displayed value is  01:01:10 and so on.

If the user than edits 00:00:22 to 00:01:44 than element.number gets updated to 104.

For all the logic the app needs, element.number must be an integer. How should I go around this? Is there some pipe I can use on expressions? Should I split the input into 3 input fields?

答:
I think you need to look more in the html5 formats. Try this:

```<code><input type="time" step="1" />
</code>```

Works in:

https://html5test.com/compare/feature/form.time.step.html

Body:
I've got an input linked to the object that contains relevant data:

  <input type="text" [(ngModel)]="element.number" name="someName">

element is an object with property number. number is of type number and it is always whole number.

I'd like to display a formated value of input (transform seconds into a more human readable format). Lets say element.number is 140, than the displayed value is 00:02:20. If the element.number is 22, than the displayed value is 00:00:22. If element.number is 3670, than the displayed value is  01:01:10 and so on.

If the user than edits 00:00:22 to 00:01:44 than element.number gets updated to 104.

For all the logic the app needs, element.number must be an integer. How should I go around this? Is there some pipe I can use on expressions? Should I split the input into 3 input fields?

Body:
I think you need to look more in the html5 formats. Try this:

<input type="time" step="1" />

Works in:

https://html5test.com/compare/feature/form.time.step.html


问:
Parsing Status Code and Header in Ajax jQuery
I was trying to parse status code and Header in AJAX jQuery. The plan was to use the Location Header value to redirect when status code is 301. But, it seems parsing is not happening:

```<code>// Sign UP API
function Sign_up(email, pwd1, pwd2) {
  $.ajax({
    url: "/api/v1/users/"+email+"/"+pwd1+"/"+pwd2,
    type: 'POST',
    dataType:"json",
  }).done(function(rs, textStatus, xhr) {
    alert(xhr.getResponseHeader('Location'));
    alert(xhr.status);
  });
}
</code>```

This signup function is called on a button click. I can see request going to server and proper status code and and Headers are returned. But no alert are shown on the webpage.

答:
You can use statusCode option:

Example from $.ajax docs

```<code>$.ajax({
  statusCode: {
    404: function() {
      alert( "page not found" );
    }
  }
});
</code>```

Body:
I was trying to parse status code and Header in AJAX jQuery. The plan was to use the Location Header value to redirect when status code is 301. But, it seems parsing is not happening:

// Sign UP API
function Sign_up(email, pwd1, pwd2) {
  $.ajax({
    url: "/api/v1/users/"+email+"/"+pwd1+"/"+pwd2,
    type: 'POST',
    dataType:"json",
  }).done(function(rs, textStatus, xhr) {
    alert(xhr.getResponseHeader('Location'));
    alert(xhr.status);
  });
}

This signup function is called on a button click. I can see request going to server and proper status code and and Headers are returned. But no alert are shown on the webpage.

Body:
You can use statusCode option:

Example from $.ajax docs

$.ajax({
  statusCode: {
    404: function() {
      alert( "page not found" );
    }
  }
});


问:
Adding dateframe to PDF using Reportlab python
I am trying to display my date frame in a pdf using Lab Report. I have figured out so far what I want but I do not know how to add the index so this is missing. My pdf looks like this:
My data frame:

```<code>            00-04  04-08  08-12  12-16  16-20  20-24
2017-12-09  17671  16443  14300  15317  16398  16398
2017-12-10  16632  17611  16486  10562  10562  13014
2017-12-11  11355      0      0      0   8569  11697
</code>```

My code:

```<code>from reportlab.lib.styles import getSampleStyleSheet
from reportlab.platypus import *
from reportlab.lib import colors
import pandas as pd
import random

PATH_OUT = "C:\\"

elements = []
styles = getSampleStyleSheet()
doc = SimpleDocTemplate("Analysis_Lists.pdf", pagesize=A3, rightMargin=30,leftMargin=30, topMargin=30,bottomMargin=18)
elements.append(Paragraph("Wind Park Available Flex Neg", styles['Title']))

data = [[random.random() for i in range(1,4)] for j in range (1,8)]
df = resultado(lista,df_output,labels)
lista = [df.columns[:,].values.astype(str).tolist()] + df.values.tolist()

ts = [('ALIGN', (1,1), (-1,-1), 'CENTER'),
     ('LINEABOVE', (0,0), (-1,0), 1, colors.black),
     ('LINEBELOW', (0,0), (-1,0), 1, colors.black),
     ('FONT', (0,0), (-1,0), 'Times-Bold'),
     ('LINEBELOW', (0,-1), (-1,-1), 1, colors.black),
     ('BACKGROUND',(1,1),(-2,-2),colors.white),
     ('TEXTCOLOR',(0,0),(1,-1),colors.black)]

table = Table(lista, style=ts)
s = getSampleStyleSheet()
s = s["BodyText"]
s.wordWrap = 'CJK'
Explanation = [["The lost HT flex in the last week for 50 Hz SRL is ."],
["The lost HT flex in the last week for Tennet SRL is "],
["The lost HT flex in the last week for Amprion SRL is "],
]

data2 = [[Paragraph(cell, s) for cell in row] for row in Explanation]
e=Table(data2,spaceAfter=20)

elements.append(table)
elements.append(e)
</code>```

I have added columns and values but not sure how to add an index and my index is DateTime stamp:

```<code>l = df.index[:,].strftime('%Y/%m/%d')
l = l.tolist()
l = [u'2017/12/09', u'2017/12/10', u'2017/12/11']
</code>```

Can someone give me a hint how to continue with this process? I am not familiar with reportlab. Any help or suggestion would be great I have read Report Lab user guide

答:
As mentioned in the comments, I think the PDF problem is a "Red-Herring". I think the true issue is just getting your index into the columns.

```<code>df_2 = df.reset_index().rename(columns = {'index':'date'})
#.rename is just renaming 'index' into 'date'. you can put anything you want in there
</code>```

and now pass df2 into lista instead of df.

The rest of the code will work as expected.

Body:
I am trying to display my date frame in a pdf using Lab Report. I have figured out so far what I want but I do not know how to add the index so this is missing. My pdf looks like this:
My data frame:

            00-04  04-08  08-12  12-16  16-20  20-24
2017-12-09  17671  16443  14300  15317  16398  16398
2017-12-10  16632  17611  16486  10562  10562  13014
2017-12-11  11355      0      0      0   8569  11697

My code:

from reportlab.lib.styles import getSampleStyleSheet
from reportlab.platypus import *
from reportlab.lib import colors
import pandas as pd
import random

PATH_OUT = "C:\\"

elements = []
styles = getSampleStyleSheet()
doc = SimpleDocTemplate("Analysis_Lists.pdf", pagesize=A3, rightMargin=30,leftMargin=30, topMargin=30,bottomMargin=18)
elements.append(Paragraph("Wind Park Available Flex Neg", styles['Title']))

data = [[random.random() for i in range(1,4)] for j in range (1,8)]
df = resultado(lista,df_output,labels)
lista = [df.columns[:,].values.astype(str).tolist()] + df.values.tolist()

ts = [('ALIGN', (1,1), (-1,-1), 'CENTER'),
     ('LINEABOVE', (0,0), (-1,0), 1, colors.black),
     ('LINEBELOW', (0,0), (-1,0), 1, colors.black),
     ('FONT', (0,0), (-1,0), 'Times-Bold'),
     ('LINEBELOW', (0,-1), (-1,-1), 1, colors.black),
     ('BACKGROUND',(1,1),(-2,-2),colors.white),
     ('TEXTCOLOR',(0,0),(1,-1),colors.black)]

table = Table(lista, style=ts)
s = getSampleStyleSheet()
s = s["BodyText"]
s.wordWrap = 'CJK'
Explanation = [["The lost HT flex in the last week for 50 Hz SRL is ."],
["The lost HT flex in the last week for Tennet SRL is "],
["The lost HT flex in the last week for Amprion SRL is "],
]

data2 = [[Paragraph(cell, s) for cell in row] for row in Explanation]
e=Table(data2,spaceAfter=20)

elements.append(table)
elements.append(e)

I have added columns and values but not sure how to add an index and my index is DateTime stamp:

l = df.index[:,].strftime('%Y/%m/%d')
l = l.tolist()
l = [u'2017/12/09', u'2017/12/10', u'2017/12/11']

Can someone give me a hint how to continue with this process? I am not familiar with reportlab. Any help or suggestion would be great I have read Report Lab user guide

Body:
As mentioned in the comments, I think the PDF problem is a "Red-Herring". I think the true issue is just getting your index into the columns.

df_2 = df.reset_index().rename(columns = {'index':'date'})
#.rename is just renaming 'index' into 'date'. you can put anything you want in there

and now pass df2 into lista instead of df.

The rest of the code will work as expected.