Q: up/down arrow scroll not working up/down arrow scroll not working in jquery scrolify plugin.I want to do the scroll with both page up/down button and in up/down arrow button click.
page up/down arrow working fine as I expect.up/down button click not scroll as page scroll
           if(e.keyCode==33 ) { //working

                if(index>0) {
                    if(atTop()) {
                        e.preventDefault();
                        index--;
                        //index, instant, callbacks
                        animateScroll(index,false,true);
                    }
                }
            } else if(e.keyCode==34) { //working
                if(index<heights.length-1) {
                    if(atBottom()) {
                        e.preventDefault();
                        index++;
                        //index, instant, callbacks
                        animateScroll(index,false,true);
                    }
                }
            }
            if(e.keyCode==38) {  //not working
                if(index>0) {
                    if(atTop()) {
                        e.preventDefault();
                        index--;
                        //index, instant, callbacks
                        animateScroll(index,false,true);
                        console.log('up arrow');
                    }
                }
            } else if(e.keyCode==40) {  //not working
                if(index<heights.length-1) {
                    if(atBottom()) {
                        e.preventDefault();
                        index++;
                        //index, instant, callbacks
                        animateScroll(index,false,true);
                        console.log('down arrow');
                    }
                }
            }

/*!
 * jQuery Scrollify
 * Version 1.0.5
 *
 * Requires:
 * - jQuery 1.7 or higher
 *
 * https://github.com/lukehaas/Scrollify
 *
 * Copyright 2016, Luke Haas
 * Permission is hereby granted, free of charge, to any person obtaining a copy of
 * this software and associated documentation files (the "Software"), to deal in
 * the Software without restriction, including without limitation the rights to
 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
 * the Software, and to permit persons to whom the Software is furnished to do so,
 * subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

 If section being scrolled to is an interstitialSection and the last section on page

 then value to scroll to is current position plus height of interstitialSection

 */

(function (global,factory) {
 "use strict";
 if (typeof define === 'function' && define.amd) {
  // AMD. Register as an anonymous module.
  define(['jquery'], function($) {
   return factory($, global, global.document);
  });
 } else if (typeof module === 'object' && module.exports) {
  // Node/CommonJS
  module.exports = function( root, jQuery ) {
   if ( jQuery === undefined ) {
    // require('jQuery') returns a factory that requires window to
    // build a jQuery instance, we normalize how we use modules
    // that require this pattern but the window provided is a noop
    // if it's defined (how jquery works)
    if ( typeof window !== 'undefined' ) {
     jQuery = require('jquery');
    } else {
     jQuery = require('jquery')(root);
    }
   }
   factory(jQuery, global, global.document);
   return jQuery;
  };
 } else {
  // Browser globals
  factory(jQuery, global, global.document);
 }
}(typeof window !== 'undefined' ? window : this, function ($, window, document, undefined) {
 "use strict";
 var heights = [],
  names = [],
  elements = [],
  overflow = [],
  index = 0,
  currentIndex = 0,
  interstitialIndex = 1,
  hasLocation = false,
  timeoutId,
  timeoutId2,
  $window = $(window),
  top = $window.scrollTop(),
  scrollable = false,
  locked = false,
  scrolled = false,
  manualScroll,
  swipeScroll,
  util,
  disabled = false,
  scrollSamples = [],
  scrollTime = new Date().getTime(),
  firstLoad = true,
  initialised = false,
  wheelEvent = 'onwheel' in document ? 'wheel' : document.onmousewheel !== undefined ? 'mousewheel' : 'DOMMouseScroll',
  settings = {
   //section should be an identifier that is the same for each section
   section: ".section",
   //sectionName: "section-name",
   interstitialSection: "",
   easing: "easeOutExpo",
   scrollSpeed: 500,
   offset : 0,
   scrollbars: true,
   target:"html,body",
   standardScrollElements: false,
   setHeights: true,
   overflowScroll:true,
   before:function() {},
   after:function() {},
   afterResize:function() {},
   afterRender:function() {}
  };
 function animateScroll(index,instant,callbacks) {
  if(currentIndex===index) {
   callbacks = false;
  }
  if(disabled===true) {
   return true;
  }
  if(names[index]) {
   scrollable = false;
   if(callbacks) {
    settings.before(index,elements);
   }
   interstitialIndex = 1;
   if(settings.sectionName && !(firstLoad===true && index===0)) {
    if(history.pushState) {
        try {
       history.replaceState(null, null, names[index]);
        } catch (e) {
         if(window.console) {
          console.warn("Scrollify warning: This needs to be hosted on a server to manipulate the hash value.");
         }
        }

    } else {
     window.location.hash = names[index];
    }
   }
   if(instant) {
    $(settings.target).stop().scrollTop(heights[index]);
    if(callbacks) {
     settings.after(index,elements);
    }
   } else {
    locked = true;
    if( $().velocity ) {
     $(settings.target).stop().velocity('scroll', {
       duration: settings.scrollSpeed,
       easing: settings.easing,
       offset: heights[index],
       mobileHA: false
      });
    } else {
     $(settings.target).stop().animate({
      scrollTop: heights[index]
     }, settings.scrollSpeed,settings.easing);
    }

    if(window.location.hash.length && settings.sectionName && window.console) {
     try {
      if($(window.location.hash).length) {
       console.warn("Scrollify warning: There are IDs on the page that match the hash value - this will cause the page to anchor.");
      }
     } catch (e) {
      console.warn("Scrollify warning:", window.location.hash, "is not a valid jQuery expression.");
     }
    }
    $(settings.target).promise().done(function(){
     currentIndex = index;
     locked = false;
     firstLoad = false;
     if(callbacks) {
      settings.after(index,elements);
     }
    });
   }

  }
 }

 function isAccelerating(samples) {
    function average(num) {
     var sum = 0;

     var lastElements = samples.slice(Math.max(samples.length - num, 1));

          for(var i = 0; i < lastElements.length; i++){
              sum += lastElements[i];
          }

          return Math.ceil(sum/num);
    }

    var avEnd = average(10);
        var avMiddle = average(70);

        if(avEnd >= avMiddle) {
     return true;
    } else {
     return false;
    }
 }
 $.scrollify = function(options) {
  initialised = true;

  $.easing['easeOutExpo'] = function(x, t, b, c, d) {
   return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b;
  };

  manualScroll = {
   /*handleMousedown:function() {
    if(disabled===true) {
     return true;
    }
    scrollable = false;
    scrolled = false;
   },*/
   handleMouseup:function() {
    if(disabled===true) {
     return true;
    }
    scrollable = true;
    if(scrolled) {
     //instant,callbacks
     manualScroll.calculateNearest(false,true);
    }
   },
   handleScroll:function() {
    if(disabled===true) {
     return true;
    }
    if(timeoutId){
     clearTimeout(timeoutId);
    }

    timeoutId = setTimeout(function(){
     scrolled = f;
     if(scrollable===false) {
      return false;
     }
     scrollable = false;

     //instant,callbacks
     manualScroll.calculateNearest(false,false);
    }, 200);
   },
   calculateNearest:function(instant,callbacks) {
    top = $window.scrollTop();
    var i =1,
     max = heights.length,
     closest = 0,
     prev = Math.abs(heights[0] - top),
     diff;
    for(;i<max;i++) {
     diff = Math.abs(heights[i] - top);

     if(diff < prev) {
      prev = diff;
      closest = i;
     }
    }
    if(atBottom() || atTop()) {
     index = closest;
     //index, instant, callbacks
     animateScroll(closest,instant,callbacks);
    }
   },
   /*wheel scroll*/
   wheelHandler:function(e) {

    if(disabled===true) {
     return true;
    } else if(settings.standardScrollElements) {
     if($(e.target).is(settings.standardScrollElements) || $(e.target).closest(settings.standardScrollElements).length) {
      return true;
     }
    }
    if(!overflow[index]) {
     e.preventDefault();
    }
    var currentScrollTime = new Date().getTime();

    e = e || window.event;
    var value = e.originalEvent.wheelDelta || -e.originalEvent.deltaY || -e.originalEvent.detail;
    var delta = Math.max(-1, Math.min(1, value));

    //delta = delta || -e.originalEvent.detail / 3 || e.originalEvent.wheelDelta / 120;

    if(scrollSamples.length > 149){
     scrollSamples.shift();
    }
    //scrollSamples.push(Math.abs(delta*10));
    scrollSamples.push(Math.abs(value));

    if((currentScrollTime-scrollTime) > 200){
     scrollSamples = [];
    }
    scrollTime = currentScrollTime;

    if(locked) {
     return false;
    }

    if(delta<0) {
     if(index<heights.length-1) {
      if(atBottom()) {
       if(isAccelerating(scrollSamples)) {
        e.preventDefault();
        index++;
        locked = true;
        //index, instant, callbacks
        animateScroll(index,false,true);
       } else {
        return false;
       }
      }
     }
    } else if(delta>0) {
     if(index>0) {
      if(atTop()) {
       if(isAccelerating(scrollSamples)) {
        e.preventDefault();
        index--;
        locked = true;
        //index, instant, callbacks
        animateScroll(index,false,true);
       } else {
        return false
       }
      }
     }
    }

   },
   /*end of wheel*/
   keyHandler:function(e) {
    if(disabled===true) {
     return true;
    }
    if(locked===true) {
     return false;
    }
    if(e.keyCode==33 ) {

     if(index>0) {
      if(atTop()) {
       e.preventDefault();
       index--;
       //index, instant, callbacks
       animateScroll(index,false,true);
      }
     }
    } else if(e.keyCode==34) {
     if(index<heights.length-1) {
      if(atBottom()) {
       e.preventDefault();
       index++;
       //index, instant, callbacks
       animateScroll(index,false,true);
      }
     }
    }
    if(e.keyCode==38) {
     if(index>0) {
      if(atTop()) {
       e.preventDefault();
       index--;
       //index, instant, callbacks
       animateScroll(index,false,true);
       console.log('up arrow');
      }
     }
    } else if(e.keyCode==40) {
     if(index<heights.length-1) {
      if(atBottom()) {
       e.preventDefault();
       index++;
       //index, instant, callbacks
       animateScroll(index,false,true);
       console.log('down arrow');
      }
     }
    }
    /*home, end button testing*/
    if(e.keyCode==35) {

      for(index=6;index<1;index--)
      {
       console.log("worked on end button");
      }

    }
    else if(e.keyCode==36) {

      for(index=0;intex<1;index++)
      {
       console.log("worked on home button");
      }

    }
    /*home,end button end*/
   },
   init:function() {
    if(settings.scrollbars) {
     $window.on('mousedown', manualScroll.handleMousedown);
     $window.on('mouseup', manualScroll.handleMouseup);
     $window.on('scroll', manualScroll.handleScroll);
    } else {
     $("body").css({"overflow":"hidden"});
    }
    $window.on(wheelEvent,manualScroll.wheelHandler);
    $(document).bind(wheelEvent,manualScroll.wheelHandler);
    $window.on('keydown', manualScroll.keyHandler);
   }
  };

  swipeScroll = {
   touches : {
    "touchstart": {"y":-1,"x":-1},
    "touchmove" : {"y":-1,"x":-1},
    "touchend"  : false,
    "direction" : "undetermined"
   },
   options:{
    "distance" : 30,
    "timeGap" : 800,
    "timeStamp" : new Date().getTime()
   },
   touchHandler: function(event) {
    if(disabled===true) {
     return true;
    } else if(settings.standardScrollElements) {
     if($(event.target).is(settings.standardScrollElements) || $(event.target).closest(settings.standardScrollElements).length) {
      return true;
     }
    }
    var touch;
    if (typeof event !== 'undefined'){
     if (typeof event.touches !== 'undefined') {
      touch = event.touches[0];
      switch (event.type) {
       case 'touchstart':
        swipeScroll.touches.touchstart.y = touch.pageY;
        swipeScroll.touches.touchmove.y = -1;

        swipeScroll.touches.touchstart.x = touch.pageX;
        swipeScroll.touches.touchmove.x = -1;

        swipeScroll.options.timeStamp = new Date().getTime();
        swipeScroll.touches.touchend = false;
       case 'touchmove':
        swipeScroll.touches.touchmove.y = touch.pageY;
        swipeScroll.touches.touchmove.x = touch.pageX;
        if(swipeScroll.touches.touchstart.y!==swipeScroll.touches.touchmove.y && (Math.abs(swipeScroll.touches.touchstart.y-swipeScroll.touches.touchmove.y)>Math.abs(swipeScroll.touches.touchstart.x-swipeScroll.touches.touchmove.x))) {
         //if(!overflow[index]) {
          event.preventDefault();
         //}
         swipeScroll.touches.direction = "y";
         if((swipeScroll.options.timeStamp+swipeScroll.options.timeGap)<(new Date().getTime()) && swipeScroll.touches.touchend == false) {

          swipeScroll.touches.touchend = true;
          if (swipeScroll.touches.touchstart.y > -1) {

           if(Math.abs(swipeScroll.touches.touchmove.y-swipeScroll.touches.touchstart.y)>swipeScroll.options.distance) {
            if(swipeScroll.touches.touchstart.y < swipeScroll.touches.touchmove.y) {

             swipeScroll.up();

            } else {
             swipeScroll.down();

            }
           }
          }
         }
        }
        break;
       case 'touchend':
        if(swipeScroll.touches[event.type]===false) {
         swipeScroll.touches[event.type] = true;
         if (swipeScroll.touches.touchstart.y > -1 && swipeScroll.touches.touchmove.y > -1 && swipeScroll.touches.direction==="y") {

          if(Math.abs(swipeScroll.touches.touchmove.y-swipeScroll.touches.touchstart.y)>swipeScroll.options.distance) {
           if(swipeScroll.touches.touchstart.y < swipeScroll.touches.touchmove.y) {
            swipeScroll.up();

           } else {
            swipeScroll.down();

           }
          }
          swipeScroll.touches.touchstart.y = -1;
          swipeScroll.touches.touchstart.x = -1;
          swipeScroll.touches.direction = "undetermined";
         }
        }
       default:
        break;
      }
     }
    }
   },
   down: function() {
    if(index<=heights.length-1) {

     if(atBottom() && index<heights.length-1) {

      index++;
      //index, instant, callbacks
      animateScroll(index,false,true);
     } else {
      if(Math.floor(elements[index].height()/$window.height())>interstitialIndex) {

       interstitialScroll(parseInt(heights[index])+($window.height()*interstitialIndex));
       interstitialIndex += 1;

      } else {
       interstitialScroll(parseInt(heights[index])+(elements[index].height()-$window.height()));
      }

     }
    }
   },
   up: function() {
    if(index>=0) {
     if(atTop() && index>0) {

      index--;
      //index, instant, callbacks
      animateScroll(index,false,true);
     } else {

      if(interstitialIndex>2) {

       interstitialIndex -= 1;
       interstitialScroll(parseInt(heights[index])+($window.height()*interstitialIndex));

      } else {

       interstitialIndex = 1;
       interstitialScroll(parseInt(heights[index]));
      }
     }

    }
   },
   init: function() {
    if (document.addEventListener) {
     document.addEventListener('touchstart', swipeScroll.touchHandler, false);
     document.addEventListener('touchmove', swipeScroll.touchHandler, false);
     document.addEventListener('touchend', swipeScroll.touchHandler, false);
    }
   }
  };

  util = {
   refresh:function(withCallback) {
    clearTimeout(timeoutId2);
    timeoutId2 = setTimeout(function() {
     sizePanels();
     calculatePositions(true);
     if(withCallback) {
       settings.afterResize();
     }
    },400);
   },
   handleUpdate:function() {
    util.refresh(false);
   },
   handleResize:function() {
    util.refresh(true);
   }
  };
  settings = $.extend(settings, options);

  sizePanels();

  calculatePositions(false);

  if(true===hasLocation) {
   //index, instant, callbacks
   animateScroll(index,false,true);
  } else {
   setTimeout(function() {
    //instant,callbacks
    manualScroll.calculateNearest(true,false);
   },200);
  }
  if(heights.length) {
   manualScroll.init();
   swipeScroll.init();

   $window.on("resize",util.handleResize);
   if (document.addEventListener) {
    window.addEventListener("orientationchange", util.handleResize, false);
   }
  }
  function interstitialScroll(pos) {
   if( $().velocity ) {
    $(settings.target).stop().velocity('scroll', {
     duration: settings.scrollSpeed,
     easing: settings.easing,
     offset: pos,
     mobileHA: false
    });
   } else {
    $(settings.target).stop().animate({
     scrollTop: pos
    }, settings.scrollSpeed,settings.easing);
   }
  }

  function sizePanels() {
   var selector = settings.section;
   overflow = [];
   if(settings.interstitialSection.length) {
    selector += "," + settings.interstitialSection;
   }
   $(selector).each(function(i) {
    var $this = $(this);

    if(settings.setHeights) {
     if($this.is(settings.interstitialSection)) {
      overflow[i] = false;
     } else {

      if(($this.css("height","auto").outerHeight()<$window.height()) || $this.css("overflow")==="hidden") {
       $this.css({"height":$window.height()});

       overflow[i] = false;
      } else {

       $this.css({"height":$this.height()});

       if(settings.overflowScroll) {
         overflow[i] = true;
       } else {
        overflow[i] = false;
       }
      }

     }

    } else {

     if(($this.outerHeight()<$window.height()) || (settings.overflowScroll===false)) {
      overflow[i] = false;
     } else {
      overflow[i] = true;
     }
    }
   });
  }
  function calculatePositions(resize) {
   var selector = settings.section;
   if(settings.interstitialSection.length) {
    selector += "," + settings.interstitialSection;
   }
   heights = [];
   names = [];
   elements = [];
   $(selector).each(function(i){
     var $this = $(this);
     if(i>0) {
      heights[i] = parseInt($this.offset().top) + settings.offset;
     } else {
      heights[i] = parseInt($this.offset().top);
     }
     if(settings.sectionName && $this.data(settings.sectionName)) {
      names[i] = "#" + $this.data(settings.sectionName).replace(/ /g,"-");
     } else {
      if($this.is(settings.interstitialSection)===false) {
       names[i] = "#" + (i + 1);
      } else {
       names[i] = "#";
       if(i===$(selector).length-1 && i>1) {
        heights[i] = heights[i-1]+parseInt($this.height());
       }
      }
     }
     elements[i] = $this;
     try {
      if($(names[i]).length && window.console) {
       console.warn("Scrollify warning: Section names can't match IDs on the page - this will cause the browser to anchor.");
      }
     } catch (e) {}

     if(window.location.hash===names[i]) {
      index = i;
      hasLocation = true;

     }

   });

   if(true===resize) {
    //index, instant, callbacks
    animateScroll(index,false,false);
   } else {
    settings.afterRender();
   }
  }

  function atTop() {
   if(!overflow[index]) {
    return true;
   }
   top = $window.scrollTop();
   if(top>parseInt(heights[index])) {
    return false;
   } else {
    return true;
   }
  }
  function atBottom() {
   if(!overflow[index]) {
    return true;
   }
   top = $window.scrollTop();

   if(top<parseInt(heights[index])+(elements[index].outerHeight()-$window.height())-28) {

    return false;

   } else {
    return true;
   }
  }
 }

 function move(panel,instant) {
  var z = names.length;
  for(;z>=0;z--) {
   if(typeof panel === 'string') {
    if (names[z]===panel) {
     index = z;
     //index, instant, callbacks
     animateScroll(z,instant,true);
    }
   } else {
    if(z===panel) {
     index = z;
     //index, instant, callbacks
     animateScroll(z,instant,true);
    }
   }
  }
 }
 $.scrollify.move = function(panel) {
  if(panel===undefined) {
   return false;
  }
  if(panel.originalEvent) {
   panel = $(this).attr("href");
  }
  move(panel,false);
 };
 $.scrollify.instantMove = function(panel) {
  if(panel===undefined) {
   return false;
  }
  move(panel,true);
 };
 $.scrollify.next = function() {
  if(index<names.length) {
   index += 1;
   animateScroll(index,false,true);
  }
 };
 $.scrollify.previous = function() {
  if(index>0) {
   index -= 1;
   //index, instant, callbacks
   animateScroll(index,false,true);
  }
 };
 $.scrollify.instantNext = function() {
  if(index<names.length) {
   index += 1;
   //index, instant, callbacks
   animateScroll(index,true,true);
  }
 };
 $.scrollify.instantPrevious = function() {
  if(index>0) {
   index -= 1;
   //index, instant, callbacks
   animateScroll(index,true,true);
  }
 };
 $.scrollify.destroy = function() {
  if(!initialised) {
   return false;
  }
  if(settings.setHeights) {
   $(settings.section).each(function() {
    $(this).css("height","auto");
   });
  }
  $window.off("resize",util.handleResize);
  if(settings.scrollbars) {
   $window.off('mousedown', manualScroll.handleMousedown);
   $window.off('mouseup', manualScroll.handleMouseup);
   $window.off('scroll', manualScroll.handleScroll);
  }
  $window.off(wheelEvent,manualScroll.wheelHandler);
  $window.off('keydown', manualScroll.keyHandler);

  if (document.addEventListener) {
   document.removeEventListener('touchstart', swipeScroll.touchHandler, false);
   document.removeEventListener('touchmove', swipeScroll.touchHandler, false);
   document.removeEventListener('touchend', swipeScroll.touchHandler, false);
  }
  heights = [];
  names = [];
  elements = [];
  overflow = [];
 };
 $.scrollify.update = function() {
  if(!initialised) {
   return false;
  }
  util.handleUpdate();
 };
 $.scrollify.current = function() {
  return elements[index];
 };
 $.scrollify.disable = function() {
  disabled = true;
 };
 $.scrollify.enable = function() {
  disabled = false;
  if (initialised) {
   //instant,callbacks
   manualScroll.calculateNearest(false,false);
  }
 };
 $.scrollify.isDisabled = function() {
  return disabled;
 };
 $.scrollify.setOptions = function(updatedOptions) {
  if(!initialised) {
   return false;
  }
  if(typeof updatedOptions === "object") {
   settings = $.extend(settings, updatedOptions);
   util.handleUpdate();
  } else if(window.console) {
   console.warn("Scrollify warning: Options need to be in an object.");
  }

 };

}));

A: I think you are listening wrong event. Use keydown event this will work.
working fiddle


Q: Animating element with jQuery I have successfully animated a div from bottom to top on window load as fallow:
<script>
      $(function(){
          $('#wrapper').animate({'margin-top': '20px'}, 1000);
      });
</script>

#wrapper {
    float: none;
    margin: 600px auto;
    max-width: 850px;
    min-width: 200px;
    padding: 0 2%;
}

However, I now need to animate the div from right to left instead.
I tried initial css as:
margin-top: 20px;
margin-right: auto;
margin-left: 100%;

and then:
<script>
      $(function(){
          $('#wrapper').animate({'margin-left': 'auto'}, 1000);
      });
</script>

auto doesn't seem to be a valid value, but I need to have the div stop in the center so I tried
getting width of browser window and then dividing it by two and substracting half of the size
of the wrapper but I couldn't get the width of wrapper as I'm using max-width intead of hardcoding the width.
I need to keep the site responsive.
How could I accomplish left to right animation having the div stop once it is centered?

A: Try it with
$("#wrapper").animate({"marginLeft":"50%"}, 1000);

A: $('#wrapper').animate({right: (parseInt($(this).css('right'))-200)+"px"}, 1000);


Q: AlertDialog com ListView em FireBase Olá sou novo em Programação Android. Estou tentando colocar um AlertDialog customizado em uma activity nesse AlertDialog quero colocar uma listView que chame itens presentes no meu banco do FireBase. Mas quando clico para abrir o AlertDialog da Erro e para. Segue o código da classe:
package com.cpcp.jaykl.pesquisacpcp;

import android.content.DialogInterface;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import com.google.firebase.FirebaseApp;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

import java.util.ArrayList;
import java.util.List;
import java.util.zip.Inflater;

public class ListaProdutos extends AppCompatActivity {
private static FirebaseDatabase firebaseDatabase;
DatabaseReference databaseReference;
List<BdProdutos> listProdutos = new ArrayList<BdProdutos>();
ArrayAdapter<BdProdutos> arrayAdapterProdutos;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_lista_produtos);
    inicializarFireBase();
    FloatingActionButton fab = findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view)
        {
            chamaTela();
        }
    });

}
private void inicializarFireBase()//inicializa o fireBase
{
    if(firebaseDatabase == null)
    {
        firebaseDatabase = FirebaseDatabase.getInstance();
    }
    FirebaseApp.initializeApp(ListaProdutos.this);
    databaseReference = firebaseDatabase.getReference();
}

private void chamaTela()
{
    final AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
    LayoutInflater inflater = this.getLayoutInflater();
    final View dialogView = inflater.inflate(R.layout.teste_dialog, null);
    dialogBuilder.setView(dialogView);
    dialogBuilder.setMessage("Testando Tela");

    final ListView listViewTeste = (ListView)findViewById(R.id.listViewTeste);

    databaseReference.child("Produtos").orderByChild("nome").addValueEventListener(new ValueEventListener()
    {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot)
        {
            for (DataSnapshot objSnapshot : dataSnapshot.getChildren())
            {
                BdProdutos bdProdutos = objSnapshot.getValue(BdProdutos.class);
                listProdutos.add(bdProdutos);
                arrayAdapterProdutos = new ArrayAdapter<BdProdutos>(ListaProdutos.this,
                        android.R.layout.simple_list_item_1, listProdutos);
                listViewTeste.setAdapter(arrayAdapterProdutos);
            }

        }

        @Override
        public void onCancelled(DatabaseError databaseError)
        {

        }
    });

    dialogBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener()
    {
        @Override
        public void onClick(DialogInterface dialog, int which)
        {

        }
    });
    AlertDialog b = dialogBuilder.create();
    b.show();
}

}


Q: What does closing a descriptor mean? I thought a descriptor was simply a numerical index in the global file table, so I'm confused by what "close a descriptor" actually means.  Can someone clarify the relationship between processes, descriptors, and open files and explain what it means to open, duplicate, and close descriptors?

A: A descriptor is a kind of a key. When you want to access some room you need to get the key for it. open grants you an access to the room (the file) by giving you a key for it.
To access (read/write) the room (the file) you need the key.
Then to be fair (the number of key in the system is bounded), when you no more need access to the room you should release the key (close the descriptor). Thus, the key is now globally available to other clients...
This is the same for all ressources that a process (a client) want to access. Get a key, use the key, release the key for the ressource. You can have many different sets of keys : keys for files, keys for memory, etc.
The system is the owner of the keys and manage them, process ask system for keys and just use them.
For duplication is just a way to provide key sharing. Two process can use the same key to access the room. If you want to understand what sharing such a key exactly means, you need to understand what an open file exactly is.
In fact, what the system gaves you is not just a simple key as in real life. A descriptor is an entry in a system table that describes the state of a file being manipulated. When you open a file, some data where allocated.

*

*first in the process own space, there is some data initialized to prepare the process to be able to manipulated a file. These data where placed in the process' descriptors table. Your descriptor is exactly an index in that table. That entry refers to a system open-file table.

*second the system tracks all opened files in its opened-file table. In such a table entry you have many data that helps the system to realize operations you need on the file (which file it is, buffer caching structures, current position to the file, current opening mode, etc).

Now in many cases, there is only one process entry associated to a system entry. But this is not always the case! Think about two different processes writing on the same terminal, then in each process you have an descriptor that represents its access to the terminal (in Unix a terminal is just a file), but both of these entries points to the same system table entry which contains data that says which terminal it is, etc.
duplicating a descriptor realize exactly the situation : you have in the same process 2 entries that points the the same system entry. Another way to duplicate descriptors is to fork a process, that clones a process, and that cloning clones process descriptors table... This is the way two process can share the same terminal for example. A first process (maybe a shell) opens the terminal, and then forks to execute a sub-command such that sub-command can access the same terminal.


Q: Import list of strings to tuples Say if I have a text file containing a list of strings eg:
111 234324 john smith
123 123113 edward jones
131 423432 ben david

How could I import the strings from a text file and create a tuple for each line?
So they would read
(131, 234324, "john", "smith")
(123, 123113, "edward", "jones")
(131, 423432, "ben", "david")

and then print each tuple out line by line?
Thanks.

A: This should do it:
result = None
with open('input.txt') as f:
    result = [tuple(line.split()) for line in f]

for t in result:
    print(t)

A: Try this :
# open your_file

for line in your_file:
    t = tuple(line.split())
    print t


Q: How to solve python/pip/pip3 is not recognized as an internal or external command | python command error after changing path? I. Have installed python 3.7.8 on windows 10. But when I run the commands python/pip/pip3 from command prompt it gives an error
python/pip/pip3 is not recognized as an internal or external command | python command error
Thought I have changed the path on user variables as python's location. I have no permissions to change the system path
What can I do now.

A: Make sure you add python to the Windows path environment variable.
Check this resource to find out how to do that.

A: Control Panel -> add/remove programs -> Python -> change-> optional Features (you can click everything) then press next -> Check "Add python to environment variables" -> Install
enter image description here
I followed the link specially the image ....


Q: Creating new variable names, Symbol or ToExpression One can create new variable names by Symbol :
In[1]  Table[Symbol["x"<>ToString[i]], {i,1,5}]
Out[1]  {x1,x2,x3,x4,x5}

But it is also possible to use ToExpression (old friend) :
In[2]  Table[ToExpression["x"<>ToString[i]], {i,1,5}]
Out[2]  {x1,x2,x3,x4,x5}

There is a difference : Symbol will produce an error for incorrect variable names while ToExpression will do something meaningful.
In[3]  Table[Symbol[ToString[i]<>"x"], {i,1,5}]
Out[3]  (* some error message with non-helpful output)

In[4]  Table[ToExpression[ToString[i]<>"x"], {i,1,5}]
Out[4]  {x,2x,3x,4x,5x}

Other than this, I see there is no difference. Is there a situation such that Symbol is more useful than ToExpression ?


Q: Как сделать защиту от ввода неверного ответа (защита от дурака) otv = input('1.Побежать на опережение\n2.Спокойно дойти до остановки.')
if otv == '1':
    print('Вы догнали автобус')
    print('Наконец,ты подъехала к зданию университета и ахнула')
    print('Хелена:\nВот это красота!')
    print('Хелена:\nА этот дизайн!')
    print('Впрочем ты оказалась невнимательна и врезалась в парняс книгами.Ты осмотрела его и сказала:')
if otv == '2':
    print('Ты решила не играть в догонялки с автобусом и потратила время на то,чтобы дождаться следующего')
    print('Наконец,ты подъехала к зданию университета и ахнула')
    print('Хелена:\nВот это красота!')
    print('Хелена:\nА этот дизайн!')
    print('Впрочем ты оказалась невнимательна и врезалась в парня с книгами.Ты осмотрела его и сказала:')

что то по типу этого только надо вставить это в код выше
def main():
    while True:
        try:
            num = int(raw_input("Введите число: "))
            break
        except ValueError:
            print "Вы должны ввести число, попробуйте снова."
main()

A: Если заранее знаем, что нужно вот конкретно для этой задачи получать только натуральные числа, можно около того:
def user_option(messages: list):
    msg = '\n'.join(messages); qty = len(messages)

    while True:
        try:
            val = int(input(msg))
            if not val in range(1, qty + 1):
                raise ValueError
            return val

        except ValueError:
            print('Вводите только числа от 1 до', qty)

val = user_option([
    '1. Побежать на опережение',
    '2. Спокойно дойти до остановки'
])

if val == 1:
    print('1')
elif val == 2:
    print('2')

В цикле будет повторять запрос до тех пор, пока не введут 1 или 2.
Можете попробовать написать функцию, принимающую произвольное количество аргументов вместо списка. *args

A: Вот один из путей решения:
while True:
    try:
        otv = int(input('1.Побежать на опережение\n2.Спокойно дойти до остановки.'))
        break
    except ValueError:
        print("Вы должны ввести число, попробуйте снова.")
if otv == 1:
    print('Вы догнали автобус')
    print('Наконец,ты подъехала к зданию университета и ахнула')
    print('Хелена:\nВот это красота!')
    print('Хелена:\nА этот дизайн!')
    print('Впрочем ты оказалась невнимательна и врезалась в парняс книгами.Ты осмотрела его и сказала:')
if otv == 2:
    print('Ты решила не играть в догонялки с автобусом и потратила время на то,чтобы дождаться следующего')
    print('Наконец,ты подъехала к зданию университета и ахнула')
    print('Хелена:\nВот это красота!')
    print('Хелена:\nА этот дизайн!')
    print('Впрочем ты оказалась невнимательна и врезалась в парня с книгами.Ты осмотрела его и сказала:')


Q: Copying files from one sub directory to another I think I must be missing something obvious. I am in a directory called AmHist, with 2 subdirectories, Assign and Resources. I want to move 2 files from Assign to Resources.
I try
cp LinuxHist Linuxnotes.txt Resources

but for both files I get No such file or directory. If I do
cp Assign/LinuxHist Linuxnotes.txt Resources

it only copies LinuxHist and I get the error again for Linuxnotes.txt on how it doesn't exist. I am very new to linux, so am I missing something basic about relative and absolute paths? I know the basics of Windows command line, so it's not completely alien, but I think I must be missing something big

A: You need to specify the directory name for both source files:
cp Assign/LinuxHist Assign/Linuxnotes.txt Resources

(There are many more ways of writing this, but this is the simplest form of the command to understand).
Now your title has "Copy" but the question says "move".  The cp command will copy.  If, instead you want to move the file then use the mv command:
mv Assign/LinuxHist Assign/Linuxnotes.txt Resources

A: You can go to first your source directory i.e assign by using cd command. After that, you can use this:
mv LinuxHist Linuxnotes.txt ../Resources

This will definitely work.


Q: Error while creating layout template in codigniter I have two layout templates in my project and always loading first template. How to load second template also.
In main Usercontroller how to differentiate them. They are,
Learncontroller.php
class Learncontroller extends Usercontroller{

    public function __construct(){
        parent::__construct();
        $this->load->model("Usermodel","",true);
    }

    public function index(){
        $id=$this->session->userdata('cp_userid');
        $menuActive= "learning";
        $data['menuActive'] = $menuActive;
        $userdetails=$this->Usermodel->getuserdetails($id);
        $data['userdetails']=$userdetails;
        $result=$this->Usermodel->currentlearningcourses($id);
        $data['details']=$result;
        $data['content']=$this->load->view("user/currentlearningcourses",$data,true);

        $data['title']='My Courses';
        //$this->load->view("user/layout",$data);

        $headerContent = $this->load->view("user/layout",$data,true);
        $this->render($headerContent);
    }
}

Unitcontroller.php
class Unitcontroller extends Usercontroller{
    public function __construct(){
        parent::__construct();
        $this->load->model("Usermodel","",true);
    }

    public function courselearn($id){
        $r=$this->Usermodel->getsectiontopic($id);
        $data['topicId']=$id;
        $data['topicQ']=$r;
        $data['video']=$this->input->post("id");
        $data['id']=$id;
        $data['content']=$this->load->view("user/unit_content",$data, true);

        $courselearnheaderContent = $this->load->view("user/courselearn_layout",$data,true);
        $this->render($courselearnheaderContent);
    }
}

Learncontroller and Unitcontroller has separate layouts but always loading protected $layout = 'user/layout';. How to load this 'user/courselearn_layout'; when control comes from Unitcontroller.
Usercontroller.php
protected $layout = 'user/layout';
protected $courselearn_layout = 'user/courselearn_layout';

protected function render($headerContent) {
    $view_data = array( 'headerContent' => $headerContent);
    $this->load->view($this->layout);
}

Always loading first page. How to make load the second page also please help me.


Q: Background position does not animate in full screen Here is my CSS:
div.movement {
  background-image: url('image.png');
  background-repeat: repeat;
  background-size: contain;
  animation: 60s linear 0s infinite alternate moving-background;
}

@keyframes moving-background {
  to {
     background-position: 2000% 0%;
  }
}

The background moves constantly when I load the webpage in regular mode. However, it stops moving as soon as I go fullscreen by pressing F11. I have tried both Chrome and Firefox and both behave in the same way.
Is there any way to animate a background image's position in full-screen mode? I would prefer a CSS-based solution but I am open to using JavaScript as well.


Q: vb6 "regfreecom" autocreate manifest for ocx file I think I need to create a manifest file for MSCOMCTL.ocx to use in my VB6 application (reg free)
I will also need to update/create the .res file Then I will need to use ManifestCreatorII It has been a few years (2017) and I have forgotten the steps and cannot find my old notes.
I ~remember how to work with the NSI to generate the install package. Without this, I cannot get my applications to run on a new Win 10 PC.
My Development PC is a virtual PC running Windows XP (32bit) Service Pack 3. I am programming with Visual Basic 6.0 (SP6).
Working through these experiments taught me that I do NOT really need manifest files for each of the Dependency .ocx files used for the Components in my VB6 programs.
I really only need the one manifest file for the application program as a whole and that is used to create the Resource file for the project.
My problem was first indicated when I installed the NSIS package and ran its VB6 program on a new Win10(64) PC:
Run-time error 339: Component 'MSCOMCTL.OCX' or one of its dependencies not correctly registered: a file is missing or invalid
I got this Error message when I tried to open one of the more recently added forms.
A unique feature of this form is the use of Tabbed Dialogue Controls (TabStrip) which references MSCOMCTL.ocx.
re: https://www.processlibrary.com/en/directory/files/mscomctl/19764/
mscomctl.ocx is an ActiveX Control module that contains common controls used by Windows, such as ImageCombo, ImageList, ListView, ProgressBar, Slider, StatusBar, TabStrip, ToolBar, and TreeView controls.
I created a tiny program, zMSCOMCTL, which has one form containing only two controls (TabStrip and ProgressBar) both from the one MSCOMCTL.ocx Component.
I plagiarized from VB6 code and NSIS of my similar tiny programs (e.g.: zRichTx, zThreeD, zCOMDLG).
When I install and try to run zMSCOMCTL on my new Win10(64) PC,  I get this same error message: Run-time error 339: Component 'MSCOMCTL.OCX' or one of its dependencies not correctly registered: a file is missing or invalid

I downloaded a copy MSCOMCTL.ocx version 6.1.98.46 from https://www.ocxme.com
These instructions are based on: https://originaldll.com/file/mscomctl.ocx/16903.html

*

*Made a backup copy of:   C:\WINDOWS\system32\MSCOMCTL.*

*In the Command Prompt Window:   regsvr32 /u MSCOMCTL.ocx

*Deleted  C:\WINDOWS\system32\MSCOMCTL.*

*Copied the new   MSCOMCTL.ocx  into C:\WINDOWS\system32

*REBOOT

*In the Command Prompt Window:  regsvr32 MSCOMCTL.ocx
FIRST trial method:
A. create MSCOMCTL.ocx.manifest:

*

*In the Command Prompt Window:regsvr42 MSCOMCTL.ocx

*I used NotePad++ to Modify

*

*.sxs. changed to .ocx.

*type="win32" changed to processorArchitecture="x86" type="win32"

*<file name="MSCOMCTL.ocx"> changed to <file name="Dependencies\MSCOMCTL.ocx">
To improve chances of ManifestCreatorv2.0.3 accepting MSCOMCTL.ocx.manifest file instead of requiring ClipBoard copy. (No srtrange characters or blanks)

*

*First, Edit MSCOMCTL.ocx.manifest with Notepad++

*Select All, Copy, Paste into NotePad and Save to MSCOMCTL.ocx.manifest

B. Create zMSCOMCTL.exe.manifest

*

*Open ManifestCreatorv2.0.3:

*The Manifest > Create from Project File (vbp) zMSCOMCTL.vbp

*The Manifest > Append/Merge Manifest - From file MSCOMCTL.ocx.manifest

*The Manifest > Export Manifest - Destination Disk File

*save to zMSCOMCTL.exe.manifest  (Replace)

re: http://www.vbforums.com/showthread.php?845909-VB6-Manifest-Creator-II
C. Create zMSCOMCTL.res

*

*Shut Down VB6 zMSCOMCTL Project or remove zMSCOMCTL.res from Project

*Open ManifestCreatorv2.0.3:

*The Manifest > Create from Project File (vbp) zMSCOMCTL.vbp

*The Manifest > Append/Merge Manifest - From file MSCOMCTL.ocx.manifest

*The Manifest > Export Manifest

*

*[_] Indent Manifest

*[_] Do Not Use Prefixed Name Spaces

*[x] Do Not Export Empty/Blank Attributes

*Destination Resource File - save to zMSCOMCTL.res   (Replace)

D. Make new zMSCOMCTL.exe

*

*Open VB6 zMSCOMCTL Project or Add zMSCOMCTL.res back into Project

*Within VB6 zMSCOMCTL Project, start with full compile: Runs OK

*Within VB6 zMSCOMCTL Project, File -> Make new executable:

Running the new executable: zMSCOMCTL.exe Results in:
This application has failed to start because the application configuration is incorrect. Reinstalling the application may fix this problem.
This is the end of the  FIRST trial method  (which failed)

Re: VB6 RegFreeCom SideBySide SxS Manifest Test for TABCTL32.ocx
Successful Process:

I downloaded UMMM from https://github.com/wqweto/UMMM

[Find_file] [_Clone_or_download_v] Click on the Green Button
Clone with HTTPS
Use Git or checkout with SVN using the web URL.
[https://github.com/wqweto/UMMM.git]
[Open_in_Desktop] [Download_ZIP] Then Click on Download_ZIP Button

*

*I expanded the downloaded UMMM-master.zip file.

*The resulting .\src folder contained files: mdUmmm.bas and Ummm.vbp.

*I copied them to their own UMMM-master Project folder

*I took a quick look at mdUmmm.bas and Ummm.vbp.

*The Ummm.vbp referred to SysWOW64.

*In Notepad, I changed it to System32. Development platform is WinXP(32)

*I opened Ummm.vbp with VB6

*I did a File - Make to create UMMM.exe

*I copied UMMM.exe  to  C:\Program Files\Support Tools\  in %path%

These are the reference links I have found for UMMM Unattended Make My Manifest :

*

*https://github.com/wqweto/UMMM

*Generate manifest files for registration-free COM

*Registration free COM: VB6 Executable referencing VB6 DLL

*https://github.com/wqweto/UMMM/blob/master/Sample.ini

*http://www.vbforums.com/showthread.php?840333-SXS-and-UMMM-with-inter-thread-marshalling

*https://github.com/wqweto/UMMM/issues/9

*https://github.com/wqweto/UMMM/issues/16
The 1st link is where I got my clues to create the .ini file.
The 6th link helped me create a bat file that seems to work!

zMSCOMCTLUMMM.ini
This .ini file, following the Identity line, contains a list of dependency files. They are listed in the .vbp file (e.g.: Object={831FDD16-0C5C-11D2-A9FC-0000F8754DA1}#2.2#0; mscomctl.ocx ).
You can also find them itemized within VB6 Menu > Project > Components ...
On that Components form, you can choose [x] Selected Items Only to more easily view the list.
Highlighting each Component in the list will display, below: (e.g.: Location C:\ ... \MSCOMCTL.OCX )
In the .ini file, I specify the path to the dependency file because it is not stored in the local Project folder.

Identity zMSCOMCTL.exe zMSCOMCTL.exe "MSCOMCTL Test program 1.0"
File C:\WINDOWS\system32\mscomctl.ocx

zMSCOMCTLUMMM.bat

UMMM.exe zMSCOMCTLUMMM.ini .\manifest\zMSCOMCTL.exe.manifest

pause done?

Is there a way to specify File Name= in UMMM (Unattended Make My Manifest) creation of Program.exe.manifest?

I edited the resulting zMSCOMCTL.exe.manifest with Notepad and changed:
From: <file name="..\..\..\..\WINDOWS\system32\MSCOMCTL.ocx">
To: <file name="Dependencies\MSCOMCTL.ocx">

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0" xmlns:asmv3="urn:schemas-microsoft-com:asm.v3">
    <assemblyIdentity name="zMSCOMCTL" processorArchitecture="X86" type="win32" version="1.1.0.24" />
    <description>MSCOMCTL Test program 1.0</description>
    <file name="Dependencies\MSCOMCTL.ocx">
        <typelib tlbid="{831FDD16-0C5C-11D2-A9FC-0000F8754DA1}" version="2.2" flags="control,hasdiskimage" helpdir="" />
        <comClass clsid="{1EFB6596-857C-11D1-B16A-00C0F0283628}" tlbid="{831FDD16-0C5C-11D2-A9FC-0000F8754DA1}" progid="MSComctlLib.TabStrip.2" threadingModel="Apartment" miscStatus="" miscStatusContent="recomposeonresize,cantlinkinside,insideout,activatewhenvisible,setclientsitefirst">
            <progid>MSComctlLib.TabStrip</progid>
        </comClass>
        <comClass clsid="{24B224E0-9545-4A2F-ABD5-86AA8A849385}" tlbid="{831FDD16-0C5C-11D2-A9FC-0000F8754DA1}" threadingModel="Apartment" miscStatus="" miscStatusContent="recomposeonresize,cantlinkinside,insideout,activatewhenvisible,setclientsitefirst" />
        <comClass clsid="{9A948063-66C3-4F63-AB46-582EDAA35047}" tlbid="{831FDD16-0C5C-11D2-A9FC-0000F8754DA1}" threadingModel="Apartment" miscStatus="" miscStatusContent="recomposeonresize,cantlinkinside,insideout,activatewhenvisible,setclientsitefirst" />
        <comClass clsid="{66833FE6-8583-11D1-B16A-00C0F0283628}" tlbid="{831FDD16-0C5C-11D2-A9FC-0000F8754DA1}" progid="MSComctlLib.Toolbar.2" threadingModel="Apartment" miscStatus="" miscStatusContent="recomposeonresize,cantlinkinside,insideout,activatewhenvisible,actslikelabel,alignable,simpleframe,setclientsitefirst">
            <progid>MSComctlLib.Toolbar</progid>
        </comClass>
        <comClass clsid="{7DC6F291-BF55-4E50-B619-EF672D9DCC58}" tlbid="{831FDD16-0C5C-11D2-A9FC-0000F8754DA1}" threadingModel="Apartment" miscStatus="" miscStatusContent="recomposeonresize,cantlinkinside,insideout,activatewhenvisible,actslikelabel,alignable,simpleframe,setclientsitefirst" />
        <comClass clsid="{8B2ADD10-33B7-4506-9569-0A1E1DBBEBAE}" tlbid="{831FDD16-0C5C-11D2-A9FC-0000F8754DA1}" threadingModel="Apartment" miscStatus="" miscStatusContent="recomposeonresize,cantlinkinside,insideout,activatewhenvisible,actslikelabel,alignable,simpleframe,setclientsitefirst" />
        <comClass clsid="{8E3867A3-8586-11D1-B16A-00C0F0283628}" tlbid="{831FDD16-0C5C-11D2-A9FC-0000F8754DA1}" progid="MSComctlLib.SBarCtrl.2" threadingModel="Apartment" miscStatus="" miscStatusContent="recomposeonresize,cantlinkinside,insideout,activatewhenvisible,actslikelabel,alignable,setclientsitefirst">
            <progid>MSComctlLib.SBarCtrl</progid>
        </comClass>
        <comClass clsid="{627C8B79-918A-4C5C-9E19-20F66BF30B86}" tlbid="{831FDD16-0C5C-11D2-A9FC-0000F8754DA1}" threadingModel="Apartment" miscStatus="" miscStatusContent="recomposeonresize,cantlinkinside,insideout,activatewhenvisible,actslikelabel,alignable,setclientsitefirst" />
        <comClass clsid="{585AA280-ED8B-46B2-93AE-132ECFA1DAFC}" tlbid="{831FDD16-0C5C-11D2-A9FC-0000F8754DA1}" threadingModel="Apartment" miscStatus="" miscStatusContent="recomposeonresize,cantlinkinside,insideout,activatewhenvisible,actslikelabel,alignable,setclientsitefirst" />
        <comClass clsid="{35053A22-8589-11D1-B16A-00C0F0283628}" tlbid="{831FDD16-0C5C-11D2-A9FC-0000F8754DA1}" progid="MSComctlLib.ProgCtrl.2" threadingModel="Apartment" miscStatus="" miscStatusContent="recomposeonresize,cantlinkinside,insideout,activatewhenvisible,actslikelabel,alignable,setclientsitefirst">
            <progid>MSComctlLib.ProgCtrl</progid>
        </comClass>
        <comClass clsid="{A0E7BF67-8D30-4620-8825-7111714C7CAB}" tlbid="{831FDD16-0C5C-11D2-A9FC-0000F8754DA1}" threadingModel="Apartment" miscStatus="" miscStatusContent="recomposeonresize,cantlinkinside,insideout,activatewhenvisible,actslikelabel,alignable,setclientsitefirst" />
        <comClass clsid="{C74190B6-8589-11D1-B16A-00C0F0283628}" tlbid="{831FDD16-0C5C-11D2-A9FC-0000F8754DA1}" progid="MSComctlLib.TreeCtrl.2" threadingModel="Apartment" miscStatus="" miscStatusContent="recomposeonresize,cantlinkinside,insideout,activatewhenvisible,setclientsitefirst">
            <progid>MSComctlLib.TreeCtrl</progid>
        </comClass>
        <comClass clsid="{9181DC5F-E07D-418A-ACA6-8EEA1ECB8E9E}" tlbid="{831FDD16-0C5C-11D2-A9FC-0000F8754DA1}" threadingModel="Apartment" miscStatus="" miscStatusContent="recomposeonresize,cantlinkinside,insideout,activatewhenvisible,setclientsitefirst" />
        <comClass clsid="{95F0B3BE-E8AC-4995-9DCA-419849E06410}" tlbid="{831FDD16-0C5C-11D2-A9FC-0000F8754DA1}" threadingModel="Apartment" miscStatus="" miscStatusContent="recomposeonresize,cantlinkinside,insideout,activatewhenvisible,setclientsitefirst" />
        <comClass clsid="{DD2DBE12-F9F8-4E32-B087-DAD1DCEF0783}" tlbid="{831FDD16-0C5C-11D2-A9FC-0000F8754DA1}" threadingModel="Apartment" miscStatus="" miscStatusContent="recomposeonresize,cantlinkinside,insideout,activatewhenvisible,setclientsitefirst" />
        <comClass clsid="{BDD1F04B-858B-11D1-B16A-00C0F0283628}" tlbid="{831FDD16-0C5C-11D2-A9FC-0000F8754DA1}" progid="MSComctlLib.ListViewCtrl.2" threadingModel="Apartment" miscStatus="" miscStatusContent="recomposeonresize,cantlinkinside,insideout,activatewhenvisible,setclientsitefirst">
            <progid>MSComctlLib.ListViewCtrl</progid>
        </comClass>
        <comClass clsid="{996BF5E0-8044-4650-ADEB-0B013914E99C}" tlbid="{831FDD16-0C5C-11D2-A9FC-0000F8754DA1}" threadingModel="Apartment" miscStatus="" miscStatusContent="recomposeonresize,cantlinkinside,insideout,activatewhenvisible,setclientsitefirst" />
        <comClass clsid="{979127D3-7D01-4FDE-AF65-A698091468AF}" tlbid="{831FDD16-0C5C-11D2-A9FC-0000F8754DA1}" threadingModel="Apartment" miscStatus="" miscStatusContent="recomposeonresize,cantlinkinside,insideout,activatewhenvisible,setclientsitefirst" />
        <comClass clsid="{CCDB0DF2-FD1A-4856-80BC-32929D8359B7}" tlbid="{831FDD16-0C5C-11D2-A9FC-0000F8754DA1}" threadingModel="Apartment" miscStatus="" miscStatusContent="recomposeonresize,cantlinkinside,insideout,activatewhenvisible,setclientsitefirst" />
        <comClass clsid="{2C247F23-8591-11D1-B16A-00C0F0283628}" tlbid="{831FDD16-0C5C-11D2-A9FC-0000F8754DA1}" progid="MSComctlLib.ImageListCtrl.2" threadingModel="Apartment" miscStatus="" miscStatusContent="recomposeonresize,cantlinkinside,insideout,activatewhenvisible,invisibleatruntime,alignable,setclientsitefirst">
            <progid>MSComctlLib.ImageListCtrl</progid>
        </comClass>
        <comClass clsid="{F91CAF91-225B-43A7-BB9E-472F991FC402}" tlbid="{831FDD16-0C5C-11D2-A9FC-0000F8754DA1}" threadingModel="Apartment" miscStatus="" miscStatusContent="recomposeonresize,cantlinkinside,insideout,activatewhenvisible,invisibleatruntime,alignable,setclientsitefirst" />
        <comClass clsid="{556C2772-F1AD-4DE1-8456-BD6E8F66113B}" tlbid="{831FDD16-0C5C-11D2-A9FC-0000F8754DA1}" threadingModel="Apartment" miscStatus="" miscStatusContent="recomposeonresize,cantlinkinside,insideout,activatewhenvisible,invisibleatruntime,alignable,setclientsitefirst" />
        <comClass clsid="{F08DF954-8592-11D1-B16A-00C0F0283628}" tlbid="{831FDD16-0C5C-11D2-A9FC-0000F8754DA1}" progid="MSComctlLib.Slider.2" threadingModel="Apartment" miscStatus="" miscStatusContent="recomposeonresize,cantlinkinside,insideout,activatewhenvisible,setclientsitefirst">
            <progid>MSComctlLib.Slider</progid>
        </comClass>
        <comClass clsid="{0B314611-2C19-4AB4-8513-A6EEA569D3C4}" tlbid="{831FDD16-0C5C-11D2-A9FC-0000F8754DA1}" threadingModel="Apartment" miscStatus="" miscStatusContent="recomposeonresize,cantlinkinside,insideout,activatewhenvisible,setclientsitefirst" />
        <comClass clsid="{DD9DA666-8594-11D1-B16A-00C0F0283628}" tlbid="{831FDD16-0C5C-11D2-A9FC-0000F8754DA1}" progid="MSComctlLib.ImageComboCtl.2" threadingModel="Apartment" miscStatus="" miscStatusContent="recomposeonresize,cantlinkinside,insideout,activatewhenvisible,setclientsitefirst">
            <progid>MSComctlLib.ImageComboCtl</progid>
        </comClass>
        <comClass clsid="{87DACC48-F1C5-4AF3-84BA-A2A72C2AB959}" tlbid="{831FDD16-0C5C-11D2-A9FC-0000F8754DA1}" threadingModel="Apartment" miscStatus="" miscStatusContent="recomposeonresize,cantlinkinside,insideout,activatewhenvisible,setclientsitefirst" />
    </file>
</assembly>

Next use ManifestCreatorv2.0.3 to create zMSCOMCTL.res file

*

*The Manifest > Create from Project File (vbp) zMSCOMCTL.vbp

*The Manifest > Append/Merge Manifest - From file [e.g.:
.\manifest\MSCOMCTL.exe.manifest]

*The Manifest > Export Manifest >

*[_] Indent Manifest

*

*[_] Do Not Use Prefixed Name Spaces

*[x] Do Not Export Empty/Blank Attributes

*Destination Resource File - save to zMSCOMCTL.res   (Replace)

*Open VB6 zMSCOMCTL Project or Add zMSCOMCTL.res back into Project

Compile, Build and Test the program.

*

*Within VB6 zMSCOMCTL Project, start witn full compile: Runs OK

*Within VB6 zMSCOMCTL Project, File -> Make new executable:

*Save Project

Running zMSCOMCTL.exe from with in its Project folder:
`[Run-Error 7 out of memory?]`

Build and use the NSIS file to create the SxS installation file for testing on any target PCs.
The NSIS file builds an executable program to:
- Determine if the target operating system is [AtLeastWinVista] and if it is [RunningX64].
- Request a selection from the available Harddrives / Partitions for installation.
- Based on this criteria, it creates an InstallDirectory and an InstallDirectory\Dependencies subdirectory.
- Copies the Program.exe into the InstallDirectory.
- Copies the Dependency files into the InstallDirectory\Dependencies subdirectory.
- Also based on this criteria it creates a Public read/write data directory.
- Creates desktop shortcut
- Creates start-menu items
- Creates an Uninstall mechanism

I adjusted the NSIS file to install only the dependency files listed in the .vbp file, the UMMM.ini file and in the resulting .exe.manifest file.
Installed on WinXP(32) works OK
Installed on Win7(64) works OK
Installed on Win10(64) works OK

A: Here is the entry from the manifest file from one of the VB6 apps I maintain:
<assemblyIdentity name="name of application" processorArchitecture="X86" type="win32" version="a.b.c.d" />

...
<file name="tabctl32.ocx">
    <typelib tlbid="{BDC217C8-ED16-11CD-956C-0000C04E4C0A}" version="1.1" flags="control,hasdiskimage" helpdir="" />
    <comClass clsid="{BDC217C5-ED16-11CD-956C-0000C04E4C0A}" tlbid="{BDC217C8-ED16-11CD-956C-0000C04E4C0A}" progid="TabDlg.SSTab.1" threadingModel="Apartment" miscStatus="" miscStatusContent="recomposeonresize,cantlinkinside,insideout,activatewhenvisible,simpleframe,setclientsitefirst">
        <progid>TabDlg.SSTab</progid>
    </comClass>
    <comClass clsid="{942085FD-8AEE-465F-ADD7-5E7AA28F8C14}" tlbid="{BDC217C8-ED16-11CD-956C-0000C04E4C0A}" threadingModel="Apartment" miscStatus="" miscStatusContent="recomposeonresize,cantlinkinside,insideout,activatewhenvisible,simpleframe,setclientsitefirst" />
</file>

generated from OCS version 6.1.98.39 using https://github.com/wqweto/UMMM using a INI configuration file line like so:
File tabctl32.ocx

This is somewhat different from the one in the question:

*

*Has a relative path to the file

*Different list of classes

*Various different attributes
Hard to say without experimentation how important those differences might be.
I highly recommend logging your program in Process Monitor and seeing what if any errors you get in the log. This is usually how I identify tricky manifest problems.


Q: iPhone SDK: Text between UITableView sections? In the settings on the iphone, there is text between some of the UITableView sections.  Sometimes larger text, sometimes smaller text.  How do I do this?
Safari http://www.zedsaid.com/__data/assets/image/0019/1765/safari.png
I would like to know how to do the "Security" text, as well as the "Warn when visiting fraudulent websites." text.
Ideas?

A: They are section headers and footers. You can set them in table view datasource tableView:titleForHeaderInSection: and tableView:titleForFooterInSection: methods


Q: How to create a coordinate pair Have a list of coordinate pairs based on the provided longitudes and latitudes and I want to store the list in a variable coordpairs.
I try using the code below. When I checked the coordinate pair I only get the value for the longitude.
for x in range(len(longitudes)):
    longitudes[x]

for y in range(len(latitudes)):
    latitudes[y]

    coordpairs = (longitudes[x], latitudes[y])
    print(coordpairs)

I have about 20 latlon point that I want to pass to a coordinate pair and then use the coordinate pair to create a polygon using this code: poly = Polygon(coordpairs)

A: Due to your current indentation, coordpairs is only seeing the last value of longitudes each time it loops through y.
If you would like to use loops, you could do something like this (assuming your longitudes and latitudes lists are the same length)
coordpairs = []
for coord_num in range(len(longitudes)):
    coord_pair = [longitudes[coord_num], latitudes[coord_num]]
    coordpairs.append(coord_pair)

If you want to combine each item in longitudes with each item in latitudes without using loops, you can use
list(zip(longitudes, latitudes))


Q: How convert telegram session to json file I searched the internet for a solution, but couldn't find anything
I tried to parse the session data, but the problem is that you can't get all the data, I couldn't find "register time"
What I want to see in Json:
{"session_file": "6285351202414", "phone": "6285351202414", "register_time": 1665007347, "app_id": id, "app_hash": "hash", "sdk": "iOS", "app_version": "1.52.10 Z", "device": "Mozilla/5.0 (iPhone; CPU iPhone OS 15_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) CriOS/100.0.5120.93 Mobile/15E148 Safari/604.1", "last_check_time": 1666735347, "avatar": "img/default.png", "first_name": "TGBOSS", "last_name": "Accounts", "username": "shykhiworyvi2", "sex": 1, "lang_pack": "en", "system_lang_pack": "en-US", "twoFA": "shykhiworyvi2_5631309146", "ipv6": false, "status": "ok", "status_time": 1666735347, "is_old": false, "proxy": []}


Q: Physical shapes you can't simulate using mathematical functions This question borders philosophy, so I would be happy to move it somewhere else if this forum is inappropriate.
While doing some 3D function plotting, it occurred to me that I can plot any shape that I can think of (theoretically that is), including all observable plain objects. My question is: Is there any physical object the look of which one cannot plot as a mathematical function? Note that the difficulty of such a task is beside the point; I am merely concerned with the decidability of this issue.


Q: 'Dynamic' fields in DRF serializers My aim is to build endpoint which will surve to create objects of model with GenericForeignKey. Since model also includes ContentType, the actual type of model which we will reference is not known before object creation.
I will provide an example:
I have a 'Like' model which can reference a set of other models like 'Book', 'Author'.
class Like(models.Model):
    created = models.DateTimeField()
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id')

Serializer may look like this:
class LikeSerializer(serializers.ModelSerializer):

    class Meta:
        model = models.Like
        fields = ('id', 'created', )

What I want to achieve is to determine type of Like based on keys passed in request. The problem is that DRF do not pass those keys from request if they were not expilictly specified in Serializer fields. For example, POST request body contains:
{
    "book":2
}

I want to do next
def restore_object(self, attrs, instance=None)
    if attrs.get('book', None) is not None:
        # create Like instance with Book contenttype
    elif attrs.get('author', None) is not None:
        # create Like instance with Author contenttype

In this case first if clause will be executed.
As you can see, The type determined based on key passed in request, without specifying special Field.
Is there any way to achieve this?
Thanks

A: You might try instantiating your serializer whenever your view is called by wrapping it in a function (you make a serializer factory):
def like_serializer_factory(type_of_like):
    if type_of_like == 'book':
        class LikeSerializer(serializers.ModelSerializer):
            class Meta:
                model = models.Like
                fields = ('id', 'created', )
            def restore_object(self, attrs, instance=None):
                # create Like instance with Book contenttype
    elif type_of_like == 'author':
        class LikeSerializer(serializers.ModelSerializer):
            class Meta:
                model = models.Like
                fields = ('id', 'created', )
            def restore_object(self, attrs, instance=None):
                # create Like instance with Author contenttype
    return LikeSerializer

Then override this method in your view:
def get_serializer_class(self):
    return like_serializer_factory(type_of_like)

A: Solution 1
Basically there is a method you can add on GenericAPIView class called  get_context_serializer
By default your view, request and format class are passed to your serializer
DRF code for get_context_serializer
def get_serializer_context(self):
    """
    Extra context provided to the serializer class.
    """
    return {
        'request': self.request,
        'format': self.format_kwarg,
        'view': self
    }

you can override that on your view like this
def get_serializer_context(self):
    data = super().get_serializer_context()
    # Get the book from post and add to context
    data['book'] = self.request.POST.get('book')
    return data

And use this on your serializer class
def restore_object(self, attrs, instance=None):
    # Get book from context to use
    book = self.context.get('book', None)
    author = attrs.get('author', None)
    if book is not None:
        # create Like instance with Book contenttype
        pass
    elif author is not None:
        # create Like instance with Author contenttype
        pass

Solution 2
Add a field on your serializer
class LikeSerializer(serializers.ModelSerializer):
    # New field and should be write only, else it will be
    # return as a serializer data
    book = serializers.IntegerField(write_only=True)
    class Meta:
        model = models.Like
        fields = ('id', 'created', )

    def save(self, **kwargs):
        # Remove book from validated data, so the serializer does
        # not try to save it
        self.validated_data.pop('book', None)

        # Call model serializer save method
        return super().save(**kwargs)


Q: Zurb class show-for-large-only aligns all text left I'm building a small site which makes use of the show-for-XXXX-only classes.
My text is center aligned however applying the show-for-large-only class (or small/medium) aligns the text left. I cannot seem to override this.
Here's my HTML:

                            Here is my text. It keeps aligning left!

Here is my CSS:
.hero-table {
        display: table;
        width: 100%;
        height: 320px;
        }

.hero-copy  {
            display: table-cell;
            vertical-align: middle;
            font-family: "adobe-garamond-pro",serif;
            font-size: 22px;
            -webkit-font-smoothing: antialiased;
            font-style: italic;
            font-weight: 400;
            color: #f2f2f2;
            height: 320px;
            background-color: red;
            }

I wonder if the table code I am using to vertically align the content is clashing with the Zurb class.

A: The show-for-large-up and related classes apply display: inherit !important;, which is overriding your display: table. As a result, the whole div shrinks down to the minimum width that it can be (just large enough to fit the text), making it left aligned within its container.
The text itself appears to be left-aligned in all scenarios, regardless of the value of display. You will need text-align: center to change that (or you could apply a Foundation class like large-text-left).


Q: Flutter native admob is not working on iPhone I added flutter native admob in my app. It's working very well on Android devices but when I try run the app on IOS devices it turns loading screen. I added my code and also screenshot about this issue. How can I fix that? Thanks in advance.
new Container(
                          margin: EdgeInsets.fromLTRB(10.0, 5.0, 10.0, 5.0),
                          height: 180,
                          width: double.infinity,
                          decoration: BoxDecoration(
                            color: Color(0xFFE7EFFF),
                            borderRadius: BorderRadius.circular(20),
                          ),
                          child: NativeAdmob(
                            adUnitID:
                                'ca-app-pub-3940256099942544/2247696110',
                            loading: Center(
                              child: CircularProgressIndicator(
                                color: Color(0xFFEEA86C),
                                backgroundColor: Color(0xFFE7EFFF),
                              ),
                            ),
                            error: Text('Failed to load the ads'),
                            controller: _controller,
                            type: NativeAdmobType.full,
                            numberAds: 1,
                            options: NativeAdmobOptions(
                                ratingColor: Colors.orange,
                                showMediaContent: true,
                                headlineTextStyle:
                                    NativeTextStyle(color: Colors.blue)),
                          ),
                        )

This is how it works on Android devices.

This is how it works on IOS devices.


Q: PHP - Filenames in HTTP-headers: Problem with whitespaces Working with CakePHP and Java Web Start I'm generating the necessary .jnlp-file within a controller in which among other things I set the filename as a header-field. That works fine as long I'm not trying to use special chars in the filenames. However, I'd like to enable every character that is possible on the main operating systems as a filename. So what I try to do is removing all the invalid characters by replacing them through empty strings. But there seems to be a problem with whitespaces which should be allowed in filenames.
That's the code:
$panel_id = 1
$panelname = 'w h i t e s p a c e s';
$filename = sprintf('"Project_%d_%s.jnlp"', $panel_id, $panelname);
$invalid_chars = array('<', '>', '?', '"', ':', '|', '\\', '/', '*', '&');
$filename = str_replace($invalid_filenamechars, '', $filename);
$this->header('Content-Disposition: attachment; filename=' . $filename);

When I do that, the resulting filename in the header is 'Project_1_w h i t e s p a c e', while Windows 7 wants to save the file as 'Project_1_w'. So it seems that my OS doesn't accept unescaped whitespaces in filenames? I would be happy with that explanation if it wasn't for the following: I left the lines 4 and 5, so that the code looks
$panel_id = 1
$panelname = 'w h i t e s p a c e s';
$filename = sprintf('"Project_%d_%s.jnlp"', $panel_id, $panelname);
$this->header('Content-Disposition: attachment; filename=' . $filename);

And now Windows is willing to save the file with all its whitespaces, still I cannot understand why. If I look at the filenames in the headers by using wireshark, both are the same. And if the sprintf-line is replaced by $filename = 'w h i t e s p a c e' or even $filename = $panelname it cuts the filename as in the first codesnippet. But I can replace the sprintf with the dottet-string-concat syntax and it works.
Can anyone tell me, what I'm overlooking?

A: The difference is the double quotes. With the first code you'll end up with:
Content-Disposition: attachment; filename=Project_1_w h i t e s p a c e s.jnlp

with the second code you'll end up with:
Content-Disposition: attachment; filename="Project_1_w h i t e s p a c e s.jnlp"

What you probably want is something like:
$panel_id = 1;
$panelname = 'w h i t e s p a c e s';
$filename = sprintf('"Project_%d_%s.jnlp"', $panel_id, $panelname);
$invalid_chars = array('<', '>', '?', '"', ':', '|', '\\', '/', '*', '&');
$filename = str_replace($invalid_filenamechars, '', $filename);
$this->header('Content-Disposition: attachment; filename="'.$filename.'"');

This strips any double quotes within $filename, but then makes sure that $filename is always surrounded by double quotes.

A: RFC2616, which is the HTTP/1.1 spec, says this:

The Content-Disposition response-header field has been proposed as a
  means for the origin server to suggest a default filename if the user
  requests that the content is saved to a file. This usage is derived
  from the definition of Content-Disposition in RFC 1806.
    content-disposition = "Content-Disposition" ":"
                          disposition-type *( ";" disposition-parm )
    disposition-type = "attachment" | disp-extension-token
    disposition-parm = filename-parm | disp-extension-parm
    filename-parm = "filename" "=" quoted-string
    disp-extension-token = token
    disp-extension-parm = token "=" ( token | quoted-string )

An example is
          Content-Disposition: attachment; filename="fname.ext"

Thus, sending this:
header('Content-Disposition: attachment; filename="' . $filename . '"');

conforms to the second form (quoted-string) and should do what you expect it to - take care to only send SPACE (ASCII dec 32 / hex 20) as whitespace, not some of the other fancy whitespace characters.


Q: React: check if props undefined I want to do some things in componentDidUpdate if a prop is undefined, however, I can't because I just get the error Cannot read property 'serial' of undefined. Is there a way to solve this?
This is what I tired, but it doesn't work - I get the error:
componentDidUpdate(prevProps) {
    if (typeof this.props.location.state.serial == "undefined"){
const database = db.ref().child("Devices/" + prevProps.location.state.serial);
...

Thanks in advance!

A: First you should make a test on the location and the location.state objects because they may be undefined because this method is called immediately after any update in the state or in the props from the parent component. you can see the Official doc. Rather you should do this:
componentDidUpdate(prevProps) {
    if (this.props.location && this.props.location.state &&  typeof this.props.location.state.serial === "undefined"){
const database = db.ref().child("Devices/" + prevProps.location.state.serial);
...

Or if you'd like to take advantage of new EcmaScript syntax Optional chaining:
componentDidUpdate(prevProps) {
    if (typeof this.props.location?.state?.serial === "undefined"){
const database = db.ref().child("Devices/" + prevProps.location.state.serial);
...


Q: how to compare a substring from char array with some valid range? I have a char * which contains year and month lets say YYYYMM. How can I compare MM within the range of 01 to 12 ? Do I have to do atoi for the substring and do it or anything else exists?

A: If the first character of the month portion of the string is '0' the second must be between '1' and '9' inclusive to be valid. If the first character is '1' the second must be between '0' and '2' inclusive to be valid. Any other initial character is invalid.
In code
bool valid_month (const char * yyyymm) {
  return ((yyymm[4] == '0') && (yyymm[5] >= '1') && (yyymm[5] <= '9')) ||
         ((yyymm[4] == '1') && (yyymm[5] >= '0') && (yyymm[5] <= '2'));
}

A: You can do atoi() of the substring or you can simply compare the ASCII values. For example:
if (buf[4] == '0')
{
  // check buf[5] for values between '1' and '9'
}
else if (buf[4] == '1')
{
  // check buf[5] for values between '0' and '2'
}
else
{
  // error
}

Either way is acceptable. I guess it really depends on how you will eventually store the information (as int or string).

A: Assuming your char* variable is called "pstr" and is null terminated after the MM you can do:
int iMon = atoi(pstr + 4);
if ( (iMon >= 1) && (iMon <= 12) )
{
  // Month is valid
}


Q: How to get the file's path from file input? please tell me how to get a full file path from an <input type="file">
i have tried fileinput.value but it shows fakepath.
i have also tried mozFullPath.

A: For security reasons browsers do not allow this, i.e. JavaScript in browser has no access to the File System, however using HTML5 File API, only Firefox provides a mozFullPath property, but if you try to get the value it returns an empty string:
$('input[type=file]').change(function () {
    console.log(this.files[0].mozFullPath);
});

https://jsfiddle.net/SCK5A/

A: Due to major security reasons, most browsers don't allow getting it so JavaScript when ran in the browser doesn't have access to the user file system. having said that,  the Firefox is exceptional and provides the mozFullPath property but it will only return an empty string.


Q: Logstash can't create index in elasticsearch for metricbeat file output I am trying to ingest metricbeat file output through logstash but logstash is not creating any index in elasticsearch. Below is my logstash .conf file
  input {
          file {
            type => "my-metricbeat"
            path => ["C:/tmp/metricbeat/metric*"]
            codec => "json"
            start_position => beginning
            sincedb_path => "/dev/null"
          }
         }
        output {
          if([type] == "my-metricbeat") {
              elasticsearch {
                hosts => "http://localhost:9200"
                index => "metricbeat-test-%{+YYYY.MM.dd}"
              }
}
      stdout { codec => rubydebug }
         }

ELK version is 5.2.1

A: I see a missing bracket in your output.


Q: How to create a vectorized version of this code in Matlab I tried to vectorized my code but hit this roadblock and can't find an answer to it.
I have this array of 0 and 1, that works like a stopwatch. The way I create it is already vectorized. Here is a sample of it:
array of 0 and 1
Now, whenever the array is 1, a counter must be started multiplied by a sample rate, to give me the current measured time. And every time the first array is 0, the stopwatch must be reset for the next set of 1s. Here is a result of it.
array of calculated time
The code is this:
timearray = zeros(size(array01));
for ii = 1:size(array01)
    if (array01(ii) == 0)
        timearray(ii) = 0;
    else
        timearray(ii) = 0.005 + timearray (ii-1);
    end
end

The issue with this for loop it's painfully slow. For a large array01 it takes many seconds and I'm pretty sure there's a clever way to do it, but I'm too dumb to see it.
Thanks for the help!

A: Here's a vectorized approach based on sparse matrices:
array01 = [0,0,0,0,0,1,1,1,1,0,0,0,0,0,0,1,1,1,1,0,0,0,0].'; % example data
sample_period = 0.005;                                       % example data
t = sparse(1:numel(array01), cumsum([true; diff(array01(:))>0]).', array01);
timearray = sample_period*full(max(cumsum(t, 1).*t, [], 2));


Q: How to get circle shaped image in swift 3 From the below code I got only oval shaped image I don't know why and what I did wrong..?
   self.viewCirlce.layer.cornerRadius = self.viewCirlce.frame.size.width / 2
   self.viewCirlce.clipsToBounds = true

A: This code used to display the circle image
image.layer.borderWidth = 1
image.layer.masksToBounds = false
image.layer.borderColor = UIColor.blackColor().CGColor
image.layer.cornerRadius = image.frame.height/2
image.clipsToBounds = true

A: My guess would be that the component you have called viewCirlce is a rectangle to start with, you are just setting the corner radius. If the component has the same width and height then this could give you a circle. If it's a rectangle, then you'll get an ellipse.

A: import UIKit

class ViewController: UIViewController {
  @IBOutlet weak var image: UIImageView!

  override func viewDidLoad() {
    super.viewDidLoad()

    image.layer.borderWidth = 1
    image.layer.masksToBounds = false
    image.layer.borderColor = UIColor.blackColor().CGColor
    image.layer.cornerRadius = image.frame.height/2
    image.clipsToBounds = true
}

A: add this code and make sure your viewCirlce is a square view
 self.viewCirlce.layer.masksToBounds = true

A: Make sure height and width of viewCirlce are equal and put your this code in a method which is called after viewCirlce is loaded for e.g :
override func viewDidLayoutSubviews() {
      self.viewCirlce =  self.viewCirlce.frame.size.height / 2.0
      self.viewCirlce.layer.masksToBounds = true
}


Q: Error when trying to select event data with BigQuery I'm trying to select the event_dim.date within BigQuery but am unable to actually access it due to an error
Error: Cannot access field date on a value with type ARRAY<STRUCT<date STRING, name STRING, params ARRAY<STRUCT<key STRING, value STRUCT<string_value STRING, int_value INT64, float_value FLOAT, ...>>>, ...>> at [1:18]

My Query:
SELECT event_dim.date FROM `table`

I know I'm doing something wrong and any help would be greatly appreciated. Thanks!

A: Are you trying to get an array of the dates for each row? Then you want an ARRAY subquery:
SELECT ARRAY(SELECT date FROM UNNEST(event_dim)) AS dates
FROM `table`;

If you are trying to get all dates in separate rows, then you want to cross join with the array:
SELECT event.date
FROM `table`
CROSS JOIN UNNEST(event_dim) AS event;

To filter for a particular date:
SELECT event.date
FROM `table`
CROSS JOIN UNNEST(event_dim) AS event
WHERE event.date = '20170104';

Or you can parse the date string as a date type, which would let you filter on the year or week, for example:
SELECT date
FROM (
  SELECT PARSE_DATE('%Y%m%d', event.date) AS date
  FROM `table`
  CROSS JOIN UNNEST(event_dim) AS event
)
WHERE EXTRACT(YEAR FROM date) = 2017;


Q: CMFCToolBarComboBoxEdit handle delete button CMFCToolBarComboBoxEdit handles the BackSpace button but it doesn't handle the delete button.
Is there any way to handle the delete button except PreTranslateMessage?
if yes, what is this way?
if no, then how can I get the current cursor position in the control and how to remove specific char using its index so I can remove the char which on the right of the cursor if nothing is selected?
Thanks in advance.

A: Yes use, PreTranslateMessage. If you detected the sequence that should be handled, call:
if (..) // Check if you have a message that should
        // be passed to the window directly
{
  TranslateMessage(pMsg);
  DispatchMessage(pMsg);
  return TRUE;
}

You can do this always in PreTranslateMessage, when you detect that the message should be handled by the default control, and should not be handled by any other control in the chain of windows that execute PreTranslateMessage. This is also helpful if you have a combo box open and want the Page Down/Up handled internally and not by the view or any accelerator.

A: I've handled the delete key in the PreTranslateMessage as follows:
BOOL PreTranslateMessage(MSG* pMsg)
{
  if(WM_KEYDOWN == pMsg->message && VK_DELETE == pMsg->wParam)
  {
    int iStartChar = -1, iEndChar = -1;
    GetSel(iStartChar, iEndChar);
    if(iStartChar != iEndChar)
      Clear(); //clear the selected text
    else
    {
      SetSel(iStartChar, iStartChar + 1);
      Clear();
    }
  }

  return CMFCToolBarComboBoxEdit::PreTranslateMessage(pMsg);
}


Q: Variance for mixed distribution (continuous + discrete)
A random variable X has the cumulative distribution function:
$F(x)=
\left\{
\begin{array}{l}
0 \text{ for x < 1}\\
\cfrac{x^2-2x+2}{2} \text{ for } 1 \le x <2\\
1 \text{ for } x \ge 2
\end{array}
\right.
$
Calculate the variance of x.

I know the definition of variance is:  $Var[X]=E[X^2]-E[X]^2$ so we proceed by calculating each term.
$E[X]=\int\limits_{-\infty}^{\infty}xf(x)dx\tag{1}$
$E[X^2]=\int\limits_{-\infty}^{\infty}x^2f(x)dx\tag{2}$
So to evaluate equations (1) and (2), we need to calculate the PDF.  This is where I am confused.  I know the PDF is the derivative of the CDF.  Also, we note that $F(2)-F(1) = 1/2$ and by definition $F(\infty)=1$.
This forces the probability for $x<1$ to be 1/2.  Is this correct?  How would we write the system of equations for the PDF below?  I don't really see how this is a combination of discrete and continuous if the limits are $(x<1), 1 \le x < 2, x \ge 2$.  Can someone please explain this and breakdown $E[X],E[X^2]$?

$f(x)=
\left\{
\begin{array}{l}
0 \text{ for x < 1}\\
(x-1) \text{ for } 1 \le x <2\\
0 \text{ for } x \ge 2
\end{array}
\right.
$

Any help is appreciated.  Thank you!

A: The CDF as given explicitly states that Pr{ X < 1 } = 0, so the answer to your first question is NO, it is not ½.
However, the CDF jumps from 0 to ½ at X = 1. Therefore we know that Pr{ X = 1 } = ½.
I think this will be enough to get you started on the answer. I could work it all out for you, but it looks like a homework problem so I think I will stop here.


Q: Why does a type assertion of "as any" fix this "No overload matches this call" error I am using React Navigation in a React Native project with TypeScript. The code below is somewhat simplified - hopefully it makes my question clearer.
I have a file <navigator.tsx> which sets up the navigator and type checks it ...
// navigator.tsx
// ...
import {NavigationContainer} from "@react-navigation/native"
import {createStackNavigator} from "@react-navigation/stack"
import {screen1, screen2} from "@screens"

export type StackNavigatorParams = {
    screen1: undefined
    screen2: undefined
}

const Stack = createStackNavigator<StackNavigatorParams>()

const Navigator = (): ReactElement => {
    return (
        <NavigationContainer>
            <Stack.Navigator initialRouteName="screen1" screenOptions={{headerShown: false}}>
                <Stack.Screen name="screen1" component={screen1}></Stack.Screen>
                <Stack.Screen name="screen2" component={screen2}></Stack.Screen>
            </Stack.Navigator>
        </NavigationContainer>
    )
}

export default Navigator

I then have a button component which expects a screen name as a prop (nextPage)
// ButtonComponent.tsx
// ...
import { StackNavigatorParams } from "@config/navigator";
import { StackNavigationProp } from "@react-navigation/stack";
import { useNavigation } from "@react-navigation/native";

type dummyButtonProps = {
    nextPage: "screen1" | "screen2";
};

export type StackNavigation = StackNavigationProp<StackNavigatorParams>;

const DummyButton = ({ nextPage }: dummyButtonProps) => {
    const navigation = useNavigation<StackNavigation>();
    return (
        // ...
        <Pressable
            onPress={() => {
                navigation.navigate(nextPage); // <-- TypeScript error here, however, if I pass "nextPage as any" the error goes away.
            }}
        ></Pressable>
        // ...
    );
};
export default dummyButtonProps;

If I pass nextPage to navigation.navigate(nextPage) I get the lengthy error
No overload matches this call. specifically that Argument of type '["screen1" | "screen2"]' is not assignable ....
However, if I pass nextPage as any, the error goes away and the type checking works as expected, that is, I can only pass the strings 'screen1' or 'screen2' as props - anything else gets a TypeScript error. Why does making this type assertion work? Is this the best way to handle the problem?
Many thanks.


Q: Haskell incorrect indentation I have an error saying "Possibly incorrect indentation"
boyerMooreSearch :: [Char] -> [Char] -> [Int] -> Int
boyerMooreSearch string pattern skipTable
                                    | skip == 0                                     = 0
                                    | skip > 0 && (string length > pattern length)  = boyerMooreSearch (substring string skip (string length)) pattern skipTable
                                    | otherwise                                     = -1
                                    where
                                    subStr = (substring 0 (pattern length))
                                    skip = (calculateSkip subStr pattern skipTable)

Whats wrong with it? Can anyone explain indentation rules in Haskell?

A: On the line with substr, you have a string of whitespace followed by a literal tab character, and on the line with skip you have the same string followed by four spaces. These are incompatible; one robust, flexible way to get this right is to line things in a block up with exact the same string of whitespace at the beginning of each line.
The real rule, though, since you asked, is that tabs increase the indentation level to the next multiple of eight, and all other characters increase the indentation level by one. Different lines in a block must be at the same indentation level. do, where, let, and of introduce blocks (I may be forgetting a few).