text:
Q: Adobe Flash. How to play animation till end without interrupting using AS3? I'm creating flash game. Here are 3 different attacks (label names: attack1, attack2, attack3) with different animations (keyboard bind z, x, c).
Problem
For example If I use attack1 (by clicking "z") It shows animation with ~100 frames (animation lasts 3 seconds), but while during animation I click attack2 (x) It cancels attack1 animation and start playing attack2 animation. I need to make that when during animation It can't be interrupted by using other animation.
I have created an array:
var codes:Array = new Array(0, 90, 88, 67);
var attack:Number = 0;

This is my key_down function:
    private function key_down(event:KeyboardEvent)
    {
        if (event.keyCode == 90)
        {

            if (attack > 0)
            {
                return;
            }// don't interrupt other attack
            for (var c in codes)
            {
                if (codes[c] == event.keyCode)
                {
                    attack = c;
                    Hero.gotoAndStop("attack" + attack);
                }
            }
        }
        if (event.keyCode == 88)
        {
            if (attack > 0)
            {
                return;
            }// don't interrupt other attack
            for (c in codes)
            {
                if (codes[c] == event.keyCode)
                {
                    attack = c;
                    Hero.gotoAndStop("attack" + attack);
                }
            }
        }
        if (event.keyCode == 67)
        {
            if (attack > 0)
            {
                return;
            }// don't interrupt other attack
            for (c in codes)
            {
                if (codes[c] == event.keyCode)
                {
                    attack = c;
                    Hero.gotoAndStop("attack" + attack);
                }
                else
                {
                    Hero.gotoAndStop("attack" + attack);
                }
            }
        }
}

When I use this, it not interrupting the same attacks animation, I mean If I use Attack1 by clicking "x" I can click "x" again and animation not interrupting, but still interrupting by clicking other button "z" or "c".
As I understand in timeline last animation's frame I need to add something like
attack=0;
MovieClip(parent).gotoAndStop("stay");

That after animation played attack will be set to 0 and continued playing "stay" animation, but I got error: Access of undefined property attack.

A: I cannot illustrate your problem. But as far as I understand you want to make animation without a hitch. In that case you need to do basic open - close animation for your character.
e.g. like that ;
1 - 30 frames for character attack animation. That means "open" animation.
30 - 60 frames when you faced with attack against then you need to do run "close" animation.
function attack():void
{
            if(currentState == "Attack")
            {
                currentState = "Attack";
                timelineAnimation.gotoAndPlay("Attack_InAnimation");
            }
            else if(currentState == "CounterAttack")
            {
                currentState = "CounterAttack";
                timelineAnimation.gotoAndPlay("Attack_OutAnimation");
            }
  }

I hope this is useful for you. This is just my approach.


text:
Q: XSLT key not available inside template (using note-set array) I created an XLT document with an array of values for each of the hour of the day. I loop through this array by creating a variable using node-set.
I have a key created that holds the total counts for each hour called key-hours. However, when I pass it a value from the $hour-array variable, it does not display the corresponding total count.
XML data
    <Records reportTime24h="18:14" reportTime="06:14:55PM" reportDate="2020-11-12" reportTitle="Samples per time of day v2">
      <vars>
      <date>2020-11-12</date>
      </vars>
      <Record>
      <TubeName>Wholeblood Haematology</TubeName>
      <RegisterHour>07 AM</RegisterHour>
      <Total>2</Total>
      </Record>
      <Record>
      <TubeName>Wholeblood Haematology</TubeName>
      <RegisterHour>08 AM</RegisterHour>
      <Total>15</Total>
      </Record>
      <Record>
      <TubeName>Chemistry Serum</TubeName>
      <RegisterHour>08 AM</RegisterHour>
      <Total>4</Total>
      </Record>
      <Record>
      <TubeName>Chemistry Wholeblood</TubeName>
      <RegisterHour>08 AM</RegisterHour>
      <Total>1</Total>
      </Record>
      <Record>
      <TubeName>Chemistry Plasma</TubeName>
      <RegisterHour>08 AM</RegisterHour>
      <Total>1</Total>
      </Record>
      <Record>
      <TubeName>Wholeblood Haematology</TubeName>
      <RegisterHour>09 AM</RegisterHour>
      <Total>23</Total>
      </Record>
      <Record>
      <TubeName>Chemistry Serum</TubeName>
      <RegisterHour>09 AM</RegisterHour>
      <Total>15</Total>
      </Record>
      <Record>
      <TubeName>Chemistry Wholeblood</TubeName>
      <RegisterHour>09 AM</RegisterHour>
      <Total>4</Total>
      </Record>
      <Record>
      <TubeName>FAST_PLA</TubeName>
      <RegisterHour>09 AM</RegisterHour>
      <Total>2</Total>
      </Record>
      <Record>
      <TubeName>1HR_PLASMA</TubeName>
      <RegisterHour>09 AM</RegisterHour>
      <Total>2</Total>
      </Record>
      <Record>
      <TubeName>2HR_PLASMA</TubeName>
      <RegisterHour>09 AM</RegisterHour>
      <Total>2</Total>
      </Record>
      <Record>
      <TubeName>Wholeblood Haematology</TubeName>
      <RegisterHour>10 AM</RegisterHour>
      <Total>25</Total>
      </Record>
      <Record>
      <TubeName>Chemistry Serum</TubeName>
      <RegisterHour>10 AM</RegisterHour>
      <Total>8</Total>
      </Record>
      <Record>
      <TubeName>Chemistry Wholeblood</TubeName>
      <RegisterHour>10 AM</RegisterHour>
      <Total>1</Total>
      </Record>
      <Record>
      <TubeName>Chemistry Serum</TubeName>
      <RegisterHour>11 AM</RegisterHour>
      <Total>30</Total>
      </Record>
      <Record>
      <TubeName>FAST_PLA</TubeName>
      <RegisterHour>11 AM</RegisterHour>
      <Total>4</Total>
      </Record>
      <Record>
      <TubeName>Wholeblood Haematology</TubeName>
      <RegisterHour>11 AM</RegisterHour>
      <Total>18</Total>
      </Record>
      <Record>
      <TubeName>Chemistry Wholeblood</TubeName>
      <RegisterHour>11 AM</RegisterHour>
      <Total>2</Total>
      </Record>
      <Record>
      <TubeName>1HR_PLASMA</TubeName>
      <RegisterHour>11 AM</RegisterHour>
      <Total>1</Total>
      </Record>
      <Record>
      <TubeName>2HR_PLASMA</TubeName>
      <RegisterHour>11 AM</RegisterHour>
      <Total>2</Total>
      </Record>
      <Record>
      <TubeName>FAST_PLA</TubeName>
      <RegisterHour>12 PM</RegisterHour>
      <Total>3</Total>
      </Record>
      <Record>
      <TubeName>Chemistry Serum</TubeName>
      <RegisterHour>12 PM</RegisterHour>
      <Total>29</Total>
      </Record>
      <Record>
      <TubeName>Wholeblood Haematology</TubeName>
      <RegisterHour>12 PM</RegisterHour>
      <Total>24</Total>
      </Record>
      <Record>
      <TubeName>2HR_PLASMA</TubeName>
      <RegisterHour>12 PM</RegisterHour>
      <Total>1</Total>
      </Record>
      <Record>
      <TubeName>1HR_PLASMA</TubeName>
      <RegisterHour>12 PM</RegisterHour>
      <Total>1</Total>
      </Record>
      <Record>
      <TubeName>Chemistry Wholeblood</TubeName>
      <RegisterHour>12 PM</RegisterHour>
      <Total>3</Total>
      </Record>
      <Record>
      <TubeName>Chemistry Plasma</TubeName>
      <RegisterHour>12 PM</RegisterHour>
      <Total>1</Total>
      </Record>
      <Record>
      <TubeName>Chemistry Serum</TubeName>
      <RegisterHour>01 PM</RegisterHour>
      <Total>32</Total>
      </Record>
      <Record>
      <TubeName>Wholeblood Haematology</TubeName>
      <RegisterHour>01 PM</RegisterHour>
      <Total>33</Total>
      </Record>
      <Record>
      <TubeName>2HR_PLASMA</TubeName>
      <RegisterHour>01 PM</RegisterHour>
      <Total>1</Total>
      </Record>
      <Record>
      <TubeName>1HR_PLASMA</TubeName>
      <RegisterHour>01 PM</RegisterHour>
      <Total>1</Total>
      </Record>
      <Record>
      <TubeName>FAST_PLA</TubeName>
      <RegisterHour>01 PM</RegisterHour>
      <Total>5</Total>
      </Record>
      <Record>
      <TubeName>Chemistry Wholeblood</TubeName>
      <RegisterHour>01 PM</RegisterHour>
      <Total>3</Total>
      </Record>
      <Record>
      <TubeName>Chemistry Serum</TubeName>
      <RegisterHour>02 PM</RegisterHour>
      <Total>36</Total>
      </Record>
      <Record>
      <TubeName>FAST_PLA</TubeName>
      <RegisterHour>02 PM</RegisterHour>
      <Total>13</Total>
      </Record>
      <Record>
      <TubeName>Wholeblood Haematology</TubeName>
      <RegisterHour>02 PM</RegisterHour>
      <Total>38</Total>
      </Record>
      <Record>
      <TubeName>Chemistry Wholeblood</TubeName>
      <RegisterHour>02 PM</RegisterHour>
      <Total>8</Total>
      </Record>
      <Record>
      <TubeName>2HR_PLASMA</TubeName>
      <RegisterHour>02 PM</RegisterHour>
      <Total>4</Total>
      </Record>
      <Record>
      <TubeName>1HR_PLASMA</TubeName>
      <RegisterHour>02 PM</RegisterHour>
      <Total>4</Total>
      </Record>
      <Record>
      <TubeName>Chemistry Plasma</TubeName>
      <RegisterHour>02 PM</RegisterHour>
      <Total>1</Total>
      </Record>
      <Record>
      <TubeName>Chemistry Serum</TubeName>
      <RegisterHour>03 PM</RegisterHour>
      <Total>23</Total>
      </Record>
      <Record>
      <TubeName>Wholeblood Haematology</TubeName>
      <RegisterHour>03 PM</RegisterHour>
      <Total>29</Total>
      </Record>
      <Record>
      <TubeName>Chemistry Wholeblood</TubeName>
      <RegisterHour>03 PM</RegisterHour>
      <Total>1</Total>
      </Record>
      <Record>
      <TubeName>FAST_PLA</TubeName>
      <RegisterHour>03 PM</RegisterHour>
      <Total>12</Total>
      </Record>
      <Record>
      <TubeName>2HR_PLASMA</TubeName>
      <RegisterHour>03 PM</RegisterHour>
      <Total>5</Total>
      </Record>
      <Record>
      <TubeName>1HR_PLASMA</TubeName>
      <RegisterHour>03 PM</RegisterHour>
      <Total>5</Total>
      </Record>
      <Record>
      <TubeName>Chemistry Plasma</TubeName>
      <RegisterHour>03 PM</RegisterHour>
      <Total>3</Total>
      </Record>
      <Record>
      <TubeName>Chemistry Urine</TubeName>
      <RegisterHour>03 PM</RegisterHour>
      <Total>1</Total>
      </Record>
      <Record>
      <TubeName>FAST_PLA</TubeName>
      <RegisterHour>04 PM</RegisterHour>
      <Total>6</Total>
      </Record>
      <Record>
      <TubeName>Chemistry Serum</TubeName>
      <RegisterHour>04 PM</RegisterHour>
      <Total>16</Total>
      </Record>
      <Record>
      <TubeName>Wholeblood Haematology</TubeName>
      <RegisterHour>04 PM</RegisterHour>
      <Total>17</Total>
      </Record>
      <Record>
      <TubeName>Chemistry Wholeblood</TubeName>
      <RegisterHour>04 PM</RegisterHour>
      <Total>2</Total>
      </Record>
      <Record>
      <TubeName>Chemistry Plasma</TubeName>
      <RegisterHour>04 PM</RegisterHour>
      <Total>2</Total>
      </Record>
      <Record>
      <TubeName>2HR_PLASMA</TubeName>
      <RegisterHour>04 PM</RegisterHour>
      <Total>2</Total>
      </Record>
      <Record>
      <TubeName>1HR_PLASMA</TubeName>
      <RegisterHour>04 PM</RegisterHour>
      <Total>2</Total>
      </Record>
      <Record>
      <TubeName>Chemistry Urine</TubeName>
      <RegisterHour>04 PM</RegisterHour>
      <Total>2</Total>
      </Record>
      <Record>
      <TubeName>Chemistry Plasma</TubeName>
      <RegisterHour>05 PM</RegisterHour>
      <Total>1</Total>
      </Record>
      <Record>
      <TubeName>Chemistry Serum</TubeName>
      <RegisterHour>05 PM</RegisterHour>
      <Total>3</Total>
      </Record>
      <Record>
      <TubeName>Wholeblood Haematology</TubeName>
      <RegisterHour>05 PM</RegisterHour>
      <Total>4</Total>
      </Record>
      <Record>
      <TubeName>Chemistry Serum</TubeName>
      <RegisterHour>06 PM</RegisterHour>
      <Total>2</Total>
      </Record>
      <Record>
      <TubeName>Wholeblood Haematology</TubeName>
      <RegisterHour>06 PM</RegisterHour>
      <Total>2</Total>
      </Record>
      <Record>
      <TubeName>Chemistry Serum</TubeName>
      <RegisterHour>09 PM</RegisterHour>
      <Total>5</Total>
      </Record>
      <Record>
      <TubeName>Wholeblood Haematology</TubeName>
      <RegisterHour>09 PM</RegisterHour>
      <Total>4</Total>
      </Record>
      <Record>
      <TubeName>Chemistry Serum</TubeName>
      <RegisterHour>10 PM</RegisterHour>
      <Total>11</Total>
      </Record>
      <Record>
      <TubeName>Wholeblood Haematology</TubeName>
      <RegisterHour>10 PM</RegisterHour>
      <Total>11</Total>
      </Record>
      <Record>
      <TubeName>Chemistry Wholeblood</TubeName>
      <RegisterHour>10 PM</RegisterHour>
      <Total>1</Total>
      </Record>
      <Record>
      <TubeName>Wholeblood Haematology</TubeName>
      <RegisterHour>11 PM</RegisterHour>
      <Total>2</Total>
      </Record>
      <Record>
      <TubeName>Chemistry Serum</TubeName>
      <RegisterHour>11 PM</RegisterHour>
      <Total>3</Total>
      </Record>
      <Record>
      <TubeName>Chemistry Wholeblood</TubeName>
      <RegisterHour>11 PM</RegisterHour>
      <Total>1</Total>
      </Record>
  </Records>

XSLT
   <?xml version="1.0" encoding="UTF-8"?>
   <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:key name="key-tube" match="Record" use="TubeName"/>
    <xsl:key name="key-hour" match="Record" use="RegisterHour"/>
    <xsl:key name="key-tube-hour" match="Record" use="concat(TubeName,'::',RegisterHour)"/>

    <xsl:key name="key-hour-list" match="RegisterHour" use="."/>
    <xsl:key name="key-tube-list" match="TubeName" use="."/>

    <xsl:variable name="unique-tube-list" select="//TubeName[generate-id() = generate-id(key('key-tube-list', .)[1])]"/>

    <xsl:variable name="hours">
       <hour>01 AM</hour>
       <hour>02 AM</hour>
       <hour>03 AM</hour>
       <hour>04 AM</hour>
       <hour>05 AM</hour>
       <hour>06 AM</hour>
       <hour>07 AM</hour>
       <hour>08 AM</hour>
       <hour>09 AM</hour>
       <hour>10 AM</hour>
       <hour>11 AM</hour>
       <hour>12 AM</hour>
       <hour>01 PM</hour>
       <hour>02 PM</hour>
       <hour>03 PM</hour>
       <hour>04 PM</hour>
       <hour>05 PM</hour>
       <hour>06 PM</hour>
       <hour>07 PM</hour>
       <hour>08 PM</hour>
       <hour>09 PM</hour>
       <hour>10 PM</hour>
       <hour>11 PM</hour>
       <hour>12 PM</hour>
    </xsl:variable>
    <xsl:variable name="hour-array" select="exsl:node-set($hours)" xmlns:exsl="http://exslt.org/common"/>

    <xsl:template match="/Records">

             <title>
                <xsl:value-of select="/Records/@reportTitle"/>_<xsl:value-of select="/Records/vars/date"/>
             </title>

<xsl:value-of select="/Records/@reportTitle"/>

<xsl:value-of select="/Records/vars/date"/>

                      Time of Day
                         <xsl:apply-templates select="$unique-tube-list" mode="day-list"/>
                      Total

                     <xsl:apply-templates select="$hour-array" mode="test-list"/>

                      Totals
                      <xsl:apply-templates select="$unique-tube-list" mode="day-totals"/>

                          <xsl:value-of select="format-number(sum(Record/Total),'###,###')" />

    </xsl:template>

    <xsl:template match="TubeName" mode="day-list">
        <xsl:value-of select="."/>
    </xsl:template>

    <xsl:template match="TubeName" mode="day-totals">
        <xsl:value-of select="format-number(sum(key('key-tube',.)/Total),'###,###')"/>
    </xsl:template>

    <xsl:template match="hour" mode="test-list">
        <xsl:variable name="h" select="."/>
        <xsl:variable name="grand-total" select="sum(/Records/Record/Total)" />
        <xsl:variable name="row-total" select="sum(key('key-hour',.)/Total)" />
        <xsl:variable name="pct" select="($row-total div $grand-total)*100" />

           <xsl:choose>
              <xsl:when test="$pct > 50">
                  <xsl:attribute name="class">red-90</xsl:attribute>
               </xsl:when>
               <xsl:when test="$pct > 40">
                  <xsl:attribute name="class">red-70</xsl:attribute>
               </xsl:when>
               <xsl:when test="$pct > 30">
                  <xsl:attribute name="class">red-50</xsl:attribute>
               </xsl:when>
               <xsl:when test="$pct > 20">
                  <xsl:attribute name="class">red-30</xsl:attribute>
               </xsl:when>
               <xsl:when test="$pct > 10">
                  <xsl:attribute name="class">red-10</xsl:attribute>
               </xsl:when>
           </xsl:choose>

               <xsl:value-of select="$h"/> (<xsl:value-of select="key('key-hour',$h)"/>)

            <xsl:for-each select="$unique-tube-list">
                <xsl:variable name="total" select="key('key-tube-hour',concat(current(),'::',$h))/Total"/>
                <xsl:choose>
                    <xsl:when test="$total">
                        <xsl:value-of select="format-number($total,'###,###')" />
                    </xsl:when>
                    <xsl:otherwise>
                        0
                    </xsl:otherwise>
                </xsl:choose>
            </xsl:for-each>

                <xsl:value-of select="format-number(sum(key('key-hour',$h)/Total),'###,###')" />

     </xsl:template>
   </xsl:stylesheet>

This results in the total column not been populated with the actual sum of totals. Here is what that looks like.

Here is a fiddle of the result for you to play with.
https://xsltfiddle.liberty-development.net/pNvtBGk

A: I would suggest to change the context by doing
   <xsl:template match="hour" mode="test-list">
       <xsl:apply-templates select="$main-doc" mode="test-list">
           <xsl:with-param name="h" select="."/>
       </xsl:apply-templates>
   </xsl:template>

   <xsl:template match="/" mode="test-list">
       <xsl:param name="h"/>
       <xsl:variable name="grand-total" select="sum(/Records/Record/Total)" />
       <xsl:variable name="row-total" select="sum(key('key-hour', $h)/Total)" />
       <xsl:variable name="pct" select="($row-total div $grand-total)*100" />

          <xsl:choose>
             <xsl:when test="$pct > 50">
                 <xsl:attribute name="class">red-90</xsl:attribute>
              </xsl:when>
              <xsl:when test="$pct > 40">
                 <xsl:attribute name="class">red-70</xsl:attribute>
              </xsl:when>
              <xsl:when test="$pct > 30">
                 <xsl:attribute name="class">red-50</xsl:attribute>
              </xsl:when>
              <xsl:when test="$pct > 20">
                 <xsl:attribute name="class">red-30</xsl:attribute>
              </xsl:when>
              <xsl:when test="$pct > 10">
                 <xsl:attribute name="class">red-10</xsl:attribute>
              </xsl:when>
          </xsl:choose>

              <xsl:value-of select="$h"/> (<xsl:value-of select="key('key-hour',$h)"/>)

           <xsl:for-each select="$unique-tube-list">
               <xsl:variable name="total" select="key('key-tube-hour',concat(current(),'::',$h))/Total"/>
               <xsl:choose>
                   <xsl:when test="$total">
                       <xsl:value-of select="format-number($total,'###,###')" />
                   </xsl:when>
                   <xsl:otherwise>
                       0
                   </xsl:otherwise>
               </xsl:choose>
           </xsl:for-each>

               <xsl:value-of select="format-number(sum(key('key-hour',$h)/Total),'###,###')" />

   </xsl:template>

Needs <xsl:variable name="main-doc" select="/"/> and where you process the hours change the apply-templates to <xsl:apply-templates select="$hour-array/hour" mode="test-list"/>
https://xsltfiddle.liberty-development.net/pNvtBGk/2

redpajama_set_name: RedPajamaStackExchange


text:
Q: Material does not display properly when loading json model in Three.js r69 Exporting model from Blender in json format using Three.js plugin. Loading it using JSONLoader, standard things with:
  var loader = new THREE.JSONLoader();
  loader.load(path, function (geometry, materials) {
  materials.forEach(function (material) {
       material.skinning = true;
  });
  var material = new THREE.MeshFaceMaterial(materials);
  var mesh = new THREE.SkinnedMesh(geometry, material);

now the problem manifests itself in model not being displayed at all. If i change the material:
  var loader = new THREE.JSONLoader();
  loader.load(path, function (geometry, materials) {
  materials.forEach(function (material) {
       material.skinning = true;
  });
  var material = new THREE.MeshLambertMaterial();
  var mesh = new THREE.SkinnedMesh(geometry, material);

things work, and mesh is displayed as intended.
here's the contents of JSON file with uvs,vertices, faces and normals omitted:
{

    "metadata": {
        "formatVersion" : 3.1,
        "generatedBy"   : "Blender 2.7 Exporter",
        "vertices"      : 774,
        "faces"         : 691,
        "normals"       : 751,
        "colors"        : 0,
        "uvs"           : [404],
        "materials"     : 2,
        "morphTargets"  : 0,
        "bones"         : 0
    },

        "scale" : 1.000000,

        "vertices" : ...,
        "faces"    : ...,
        "uvs"      : ...,
        "normals"  : ...,
        "skinIndices"  : [],
        "skinWeights"  : [],
        "morphTargets" : [],

        "bones"      : [],
        "animations" : [],

        "colors"    : [],
        "materials" : [
            {
                "DbgColor": 15658734,
                "DbgIndex": 0,
                "DbgName": "Crystal",
                "blending": "NormalBlending",
                "colorAmbient": [0.800000011920929, 0.800000011920929, 0.800000011920929],
                "colorDiffuse": [0.800000011920929, 0.800000011920929, 0.800000011920929],
                "colorEmissive": [0.0, 0.0, 0.0],
                "colorSpecular": [0.25, 0.25, 0.25],
                "depthTest": true,
                "depthWrite": true,
                "mapDiffuse": "Cristal_C_CM.png",
                "mapDiffuseWrap": ["repeat", "repeat"],
                "shading": "Lambert",
                "specularCoef": 33,
                "transparency": 1.0,
                "transparent": false,
                "vertexColors": false
            },
            {
                "DbgColor": 15597568,
                "DbgIndex": 1,
                "DbgName": "tower",
                "blending": "NormalBlending",
                "colorAmbient": [0.800000011920929, 0.800000011920929, 0.800000011920929],
                "colorDiffuse": [0.800000011920929, 0.800000011920929, 0.800000011920929],
                "colorEmissive": [0.0, 0.0, 0.0],
                "colorSpecular": [0.4180000126361847, 0.31944116950035095, 0.1504800170660019],
                "depthTest": true,
                "depthWrite": true,
                "mapDiffuse": "rock_CM_01.png",
                "mapDiffuseWrap": ["repeat", "repeat"],
                "mapNormal": "rock_NM_02.png",
                "mapNormalFactor": 0.3500420153141022,
                "mapNormalWrap": ["repeat", "repeat"],
                "shading": "Phong",
                "specularCoef": 511,
                "transparency": 1.0,
                "transparent": false,
                "vertexColors": false
            }
        ]

}

any ideas would be much appreciated.

A: Turns out the problem is in setting
material.skinning = true;

removing this line model is properly displayed. This looks like a bug.
for anyone who runs into the same problem, there are 2 simple ways to solve it:
 - use different code for loading skinned/static assets
 - use a piece of code which generates different materials and mesh types based on what's loaded.
for second, here's a snippet i use:
        assetManager.registerLoader("three.js", function (path, callback) {
            var loader = new THREE.JSONLoader();
            loader.load(path, function (geometry, materials) {
                //is it skinned?
                var isSkinned = geometry.skinIndices !== void 0 && geometry.skinIndices.length > 0;
                if (isSkinned) {
                    materials.forEach(function (material) {
                        material.skinning = true;
                    });
                }
                var faceMaterial = new THREE.MeshFaceMaterial(materials);
                var asset = {
                    material: faceMaterial,
                    geometry: geometry,
                    create: function () {
                        var mesh;
                        if (isSkinned) {
                            mesh = new THREE.SkinnedMesh(geometry, faceMaterial);
                        } else {
                            mesh = new THREE.Mesh(geometry, faceMaterial);
                        }
                        mesh.castShadow = true;
                        mesh.receiveShadow = false;
                        //
                        return mesh;
                    }
                };
                callback(asset);
            });
        });


text:
Q: Distribution of data in buckets - Oracle 11g I have a table with two columns BRANCH and ACTIVITIES, where BRANCH is a unique id of location and ACTIVITIES are number of records belong to respective BRANCH. These records to be distributed in 5 buckets in a way that all buckets should contain almost equal number of records. (no matter if difference is +/-1000)
The challenge is if one branch is selected in a bucket then all activities of same branch will also be selected in same bucket, in other words, number of activities belong to one BRANCH cannot be split. Lets take a very simple example so that I can explain what I am trying to achieve
Total Branches=10
Total Number of activities (records) = 55,000
Average (total activities/total buckets) = 11,000

Sample Data

After Distribution

All buckets contain 11,000 records but things are not such straight forward when we look into real data real data
All Oracle query masters are requested to please look into this. Your expert opinion will highly be appreciated.

A: Unfortunately, this is a bin-packing problem and a "perfect" solution requires -- essentially -- searching through all possible assignments of buckets and then choosing the "best" one.  And such an approach is not really suitable for SQL.
For a "good-enough" solution, though, something like a round-robin approach often works well.  Simply enumerate the branches from biggest to smallest and assign them to buckets:
select a.branch,
       1 + mod(seqnum, 5) as bucket
from (select a.branch, count(*) as cnt,
             row_number() over (order by count(*)) desc as seqnum
      from activities a
      group by a.branch
     ) a;

Because of the ordering, this is going to generally create buckets of different sizes.  So, a slight variation assigns the buckets as 1-2-3-4-5-5-4-3-2-1:
select a.branch,
       (case when mod(seqnum, 10) in (0, 9) then 1
             when mod(seqnum, 10) in (1, 8) then 2
             when mod(seqnum, 10) in (2, 7) then 3
             when mod(seqnum, 10) in (3, 6) then 4
             when mod(seqnum, 10) in (4, 5) then 5
        end) as bucket
from (select a.branch, count(*) as cnt,
             row_number() over (order by count(*)) desc as seqnum
      from activities a
      group by a.branch
     ) a;

A: You could also try below query. I added some stats columns in this inline view stats_cols_added_tab before I applied dense_rank analytic function to that inline view. Finally I used NTILE analytic function to get five groups.
with sample_data (branch, activities) as (
select 1, 1000 from dual union all
select 2, 2000 from dual union all
select 3, 3000 from dual union all
select 4, 4000 from dual union all
select 5, 5000 from dual union all
select 6, 6000 from dual union all
select 7, 7000 from dual union all
select 8, 8000 from dual union all
select 9, 9000 from dual union all
select 10, 10000 from dual
)
,
stats_cols_added_tab as (
    select s.*
    , count(*)over() total_branches
    , sum(activities)over() total_number_of_activities
    , avg(activities)over() * 2 Average
    , case when row_number()over(order by s.branch) <= count(*)over() / 2 then 1 else 2 end grp
from sample_data s
)
SELECT BRANCH, ACTIVITIES, NTILE(5) OVER (ORDER BY ranked_grp,  BRANCH) AS bucket
FROM (
        select BRANCH, ACTIVITIES
            , dense_rank()over(
                PARTITION BY grp
                    order by decode(grp, 1, activities, -1 * activities)
                    ) ranked_grp
        from stats_cols_added_tab t
    ) t
order by ranked_grp, BRANCH
;


text:
Q: Sql execption: Maximum stored procedure..level exceeded This is the first time im using caches. I set my local cache to true in my webconfig.When i try to run my login page is gives the following error

System.Data.SqlClient.SqlException occurred
    HResult=0x80131904
    Message=Maximum stored procedure, function, trigger, or view nesting level exceeded (limit 32).
    Source=.Net SqlClient Data Provider
    StackTrace:

it throws the error on the following code
lock (lastlevelLock)
        {
            DataSet retval = new DataSet();
            if (UseLocalCache)
            {
                retval =Data.DataRepository.Provider.GetDetailsAll(); // this is where the error comes in

                if (retval == null)
                    retval = new DataSet();
            }
            else

what am i doing wrong? because the exact same code and db works fine on other machines.I did look at the other similar errors mention on stackflow but nothing helped.
    --WITH ENCRYPTION
AS
BEGIN

;WITH cte AS (
        SELECT  //do selection
        FROM Table g WITH(NOLOCK)
    )
    SELECT //do selection
    INTO #cte
    FROM cte c
        INNER JOIN list.Type gt WITH(NOLOCK) ON c.TypeId = gt.TypeID
        INNER JOIN table.crumb br WITH(NOLOCK) ON c.ID = br.ID
    ORDER BY Lev
    SELECT
    // select columns
        NULL AS ResultExpected
    INTO #TempGame
    FROM #cte tg
        JOIN list.Type gt WITH(NOLOCK) ON tg.TypeID = gt.TypeID
    WHERE tg.ID IN (
        SELECT ID FROM table2 WITH(NOLOCK)
        WHERE ID = tg.ID

        )

    SELECT
        //select columns
    INTO #Temp2
    FROM tanbe2 m WITH(NOLOCK)
        INNER JOIN table g WITH(NOLOCK) ON m.ID = g.ID
        //perform all joins
    WHERE m.ID IN (SELECT ID FROM #Temp)

         GETDATE() < ISNULL(m.ResultDateTime, m.ResultExpected)

    SELECT * FROM #Temp
    SELECT * FROM #Temp2
    ORDER BY ResultExpected

    DROP TABLE #cte
    DROP TABLE #Temp
    DROP TABLE #Temp2

END
GO

A: After searching and trying different solutions for multiple hours,i finally just restored the db AGAIN and it seemed to work.


text:
Q: How to check which parts of a dead MacBook Pro 17" Mid 2010 work Mac was water damaged. No start up chime. Charger shows green light dimmer than when plugged in to working Macs when plugged. Battery status button on side has no effect. Won't start in safe, target disk, verbose etc modes. Removed the HDD and verified that it works fine and am cloning it before wiping, reinserting and selling.
I believe only the logic board is broken/shorted, but what can I do to check whether anything else works? Specifically if I can make sure the display is functional I assume it is of greater value.
edit: I have on hand a voltmeter and the 2011 model of the same Mac, but do not wish to potentially break that one in establishing what works on this.

A: That will depend on what kind of analytical/measurement tools do you have? Oscilloscope, Volt meter ect...
Since it does not start at all and Battery is shut it could be simply the power input module. Open it and check if power is coming in and the fuse is not blown.
Is the display working: try the Target Display Mode.
Here is some how to:
http://forums.macrumors.com/showthread.php?t=1122338
Check your DCIN board.


text:
Q: Change column values depending a another column value in pandas I have a dataframe in python such as :
seqnames    start   end name    number  strand
     A       50     453   A      1        -
     B       30     322   A      2        -
     C       10     432   A      3        -
     D       36     344   A      4        +
     E       40     321   A      5        +
     F       78     234   A      6        -

and I would like to change de values in the start and end columns depending on the symbole in the strand column.
So for each line, if the strand is - than do start+1 and end-2
if the strand is + than do nothing
here I should get :
seqnames    start   end name    number  strand
A   51  451 A   1   -
B   31  320 A   2   -
C   11  430 A   3   -
D   36  344 A   4   +
E   40  321 A   5   +
F   79  232 A   6   -

Thank you for your help

A: Use:
df[['start','end']]=np.where(df['strand'].eq('-')[:,None],
                np.column_stack((df['start']+1,df['end']-2)),
                df[['start','end']].values)
print(df)

  seqnames  start  end name  number strand
0        A     51  451    A       1      -
1        B     31  320    A       2      -
2        C     11  430    A       3      -
3        D     36  344    A       4      +
4        E     40  321    A       5      +
5        F     79  232    A       6      -

A: Use Series.mask:
df['start'].mask(df['strand']=='-',df['start']+1,inplace=True)
df['end'].mask(df['strand']=='-',df['end']-2,inplace=True)

print(df)

  seqnames  start  end name  number strand
0        A     51  451    A       1      -
1        B     31  320    A       2      -
2        C     11  430    A       3      -
3        D     36  344    A       4      +
4        E     40  321    A       5      +
5        F     79  232    A       6      -

Also you can use DataFrame.apply + DataFrame.where:
df[['start','end']]=( df[['start','end']]
                   .apply(lambda x: pd.Series((x['start']+1,x['end']-2)).rename({0:'start',1:'end'}),axis=1)
                   .where(df['strand']=='-',df[['start','end']])
                    )

print(df)
  seqnames  start  end name  number strand
0        A     51  451    A       1      -
1        B     31  320    A       2      -
2        C     11  430    A       3      -
3        D     36  344    A       4      +
4        E     40  321    A       5      +
5        F     79  232    A       6      -

A: Use DataFrame.loc:
df.loc[ df['strand'] == '-', ['start', 'end']] += [1, -2]
print (df)
  seqnames  start  end name  number strand
0        A     51  451    A       1      -
1        B     31  320    A       2      -
2        C     11  430    A       3      -
3        D     36  344    A       4      +
4        E     40  321    A       5      +
5        F     79  232    A       6      -

Or use numpy.where for add or subtract values:
m = df['strand'] == '-'
df['start'] = df['start'] + np.where(m, 1 ,0)
df['end'] =  df['end'] - np.where(m, 2, 0)

Or convert mask to integer and for second value only multiple by 2:
m = df['strand'] == '-'
df['start'] = df['start'] + m.astype(int)
df['end'] =  df['end'] - m.astype(int) * 2

print (df)
  seqnames  start  end name  number strand
0        A     51  451    A       1      -
1        B     31  320    A       2      -
2        C     11  430    A       3      -
3        D     36  344    A       4      +
4        E     40  321    A       5      +
5        F     79  232    A       6      -

A: Another one liner could be:
df.loc[ df['strand'] == '-', 'start'] = df.loc[ df['strand'] == '-', 'start'] + 1

which uses loc for indexing.


text:
Q: Sharepoint Training I need to learn Sharepoint, not so much admin functions, but usage/development.
Anyone know if Microsoft makes a free version, and if I need to learn .NET/C# or any other tools?

A: Free SharePoint Training from Microsoft:
http://www.microsoft.com/click/SharePointDeveloper/
Yes, you need to learn .NET/C#/ASP.NET. Others have done it, so can you! :-)

A: First, make sure you learn .NET (you're best off learning C# in my opinion)
After you have that down, sign up for a SharePoint boot camp. I just attended one from Unitek and it was excellent.
It's not free, but they're usually about a week long and will get you up to speed much faster than self-teaching...and you'll be learning 'best practices' at the same time. Sharepoint is a technology that is easy to get lost in if you're not familiar with it.

A: Microsoft offers a trimmed down version for free called Sharepoint Services 3.0, here link. There is also a link to the 2010 Beta program on there. This should be enough to get you started as there is plenty of information about Sharepoint development on the Web

A: I would suggest to go for online video tutorials for sharepoint rather than document study. It will surely save your time. You won't need any other reference after watching some good SharePoint video.


text:
Q: What do I do after extracting *.tar.gz file? I downloaded and extracted *.tar.gz file. Here's the link - Robomongo.
Then I located a folder named Bin and double clicked on a executable file. The program started to run. I didn't have to install it or anything.
I have two questions:
What's this type of package called - Source code | Compiled | something else?
What's the typical place to put these extracted files on your computer?

A: You have downloaded a compiled version of RoboMongo. Ordinarily such packages can be placed in either of 2 locations:

*

*$HOME/bin

*/usr/local/bin
I show the second option in this answer:
tar xvf robomongo-0.9.0-rc7-linux-x86_64-2b7a8ca.tar.gz
cd robomongo-0.9.0-rc7-linux-x86_64-2b7a8ca
sudo mv -v bin/* /usr/local/bin && sudo mv -v lib/* /usr/local/lib

If you then open the application with the command robomongo from the command line you will then have an option (for Xenial at least) on the sidebar to right click and 'Add to Dash' or 'Lock to Launcher':

It is not very tidy but this archive is not a fully developed package as such and lacks neat installation and removal options. However removal can be done manually with the following two commands:
sudo rm -v /usr/local/bin/{qt.conf,robomongo}
sudo rm -rfv /usr/local/lib/{imageformats,libQt5DBus.so,\
libQt5PrintSupport.so.5.5.1,\
libicudata.so.54,libQt5DBus.so.5,libQt5Widgets.la,\
libicudata.so.54.1,libQt5DBus.so.5.5,libQt5Widgets.prl,\
libicui18n.so.54,libQt5DBus.so.5.5.1,libQt5Widgets.so,\
libicui18n.so.54.1,libQt5Gui.la,libQt5Widgets.so.5,\
libicuuc.so.54,libQt5Gui.prl,libQt5Widgets.so.5.5,\
libicuuc.so.54.1,libQt5Gui.so,libQt5Widgets.so.5.5.1,\
libQt5Core.la,libQt5Gui.so.5,libQt5XcbQpa.la,\
libQt5Core.prl,libQt5Gui.so.5.5,libQt5XcbQpa.prl,\
libQt5Core.so,libQt5Gui.so.5.5.1,libQt5XcbQpa.so,\
libQt5Core.so.5,libQt5PrintSupport.la,libQt5XcbQpa.so.5,\
libQt5Core.so.5.5,libQt5PrintSupport.prl,libQt5XcbQpa.so.5.5,\
libQt5Core.so.5.5.1,libQt5PrintSupport.so,libQt5XcbQpa.so.5.5.1,\
libQt5DBus.la,libQt5PrintSupport.so.5,platforms,\
libQt5DBus.prl,libQt5PrintSupport.so.5.5,platformthemes}

It takes a little bit of manual fiddling but this works nicely on my system and should on yours as well...


text:
Q: how to use CreateObject in excel vba? Public Sub InformationManagement(myTable As String)
    Dim myaccess As Object
    Dim mydata As String
    mydata = ThisWorkbook.Path & "\Management.mdb"
    Set myaccess = CreateObject(mydata)
    With myaccess
        .Visible = True
        .DoCmd.OpenTable myTable
        .DoCmd.Maximize
    End With
    Set myaccess = Nothing
End Sub

There is a message error "Run-time error '429' ActiveX component can't create object" happened in Row -> Set myaccess = CreateObject(mydata)
Does anyone know how to resolve this? thank you very much

A: Ive not done this for a while but off the top of my head it should be more like..
Dim mydata As String
Dim myaccess As Object

mydata = ThisWorkbook.Path & "\Management.mdb"
Set myaccess = CreateObject("Access.Application")
With AccDatabase

    .OpenCurrentDatabase mydata
    .DoCmd.OpenTable myTable
    .DoCmd.Maximize
End With
Set myaccess = Nothing


text:
Q: Will pressure of water kept at constant volume increase indefintely with temperature? I am working through the questions in Zemansky's Heat and Thermodynamics.
Question 2.8 says:
The thermal expansivity and the compressibility of water are given in the accompanying table.  Draw a graph showing how $\left(\partial{P} / \partial{\theta}\right) _V$ depends on the temperature.  If water were kept at constant volume and the temperature were continually raised, would the pressure increase indefinitely?

t, Celcius                 0    50   100   150   200   250   300
Expansivity (10^-3)        0   .45   .74  1.02  1.35  1.80  2.90
Compressibility (10^-4)  .45   .45   .50   .62   .85  1.50  3.05

I can work out the required partial (it is expansivity divided by compressibility) and it's clearly positive everywhere in the range 0-300C. So pressure will increase with temperature over that range, at constant volume.  But indefinitely?
A common sense answer is that at a certain point it will become very hard to raise the temperature, or that any containing vessel will burst / melt at a sufficiently high temperature, but the question seems to ask what would happen if the temperature could keep being raised without the volume changing.
There is nothing I can find earlier in the text which gives a direct answer -- there is a phase diagram for water but it doesn't go much beyond 300C.


text:
Q: What does increased AI-Progress actually do in Ai-wars Fleet Command I've started playing AI-Wars Fleet Command and I understand that the game gets harder as AI-Progress increases.
But in what way does it manifest itself.
Does it just get more aggressive and send more ships to my controlled system, or does it also increase in tech level, does it spread to new system more quickly and build ships faster?
At the moment I am playing the base game without any Expansion with the latest patch - at moment of writing. 5.087

A: It depends actually. AI wars is still under active development. (Really active, at least one patch each week. Superb work from them).
What happens if the AIP goes up?
This list is based on the most recent patches (6.003 with the DLC, but that should not matter). I really cannot comment on older patches. It changes a lot. So update, if you can read this, you can update the game.

*

*Increase the amount of ships you get each attack wave.

*Increase the mark of the ships you get each attack wave. (In recent patches there is not a set point any more where the ships change from mark 1 to mark 2, it is now a percentage). But you can see the point where it changes by hovering over the AIP (AI-Progress)

*Increase the types of ships the AI has access to. After a certain (hidden, there is a list on the wiki) threshold the AI gets new ships. They are called bonus tech ships (on the wiki).

*The amount of ships the AI gets when reinforcing a planet. (Note, the amount of planets not owned by the AI also influences the amount of planets the AI is allowed to reinforce).

*DLC Timing of Exogalactic Strikeforces. The higher the AIP, the quicker, "Broken Golems - Hard", and/or "Spirecraft - Hard" strike forces arrive.

Note Under the hood the AI gets ship points for each point of AIP you got. It uses these points to buy ships. So that is why at high AIP you might only get two ships (badass ones), and at low AIP you get 4 fighters.
What happens when AIP goes down?

*

*The wave sizes and wave types will be reduced. (so, a 200 ship wave with 100% mark 2 ships will be downgraded to 190 90% mark 2 and 10% mark 1 wave).

*Existing ships will not be removed.

*Bonus tech ships will not be removed, and stay available to the AI.

note AIP reduction cannot be wasted. When you are at AIP 10 and reduce it by -20, the game keeps track of the reduction. So reduce that AIP when you can. You can waste a SuperTerminal however. Just not the AIP reduction it creates. (I use waste in the broadest sense, as in it can lose you the game).
What is not influenced by AIP?

*

*AI tactics are not changed by higher AIP.

*Timing between waves

*Timing between placement of reinforcements

*Planets being on alert.

*Structures. As far as I know the AI cannot rebuild a structure when it has been destroyed. (Note Tachyon guardians are guardian ships not structures). This was planned for one of the DLC but has not been implemented yet.

*DLC size of EXO strike forces.

*DLC Timing of "Fallen Spire" Exogalactic Strikeforces. Not influenced by AIP, as the AI now considers you a major threat, and sends massive amounts of ships.

*The internal Hacking the AI value. That one is influenced by hacking.

Strategic reserve
This was written before the new patches added the new feature called the strategic reserve. The patch notes only indicate it increases periodically (whatever that means). It is unlocked at difficulties 6+. And if it is filled over 50% some new ships added to this reserve will be added to cross planet attacks.
Using the debug mode it would be possible to check if higher AIP increase the amount of strategic reserve ships the AI gets. But I have not done that. Other patch notes to seem to indicate that the higher the AIP the more strategic reserve the AI gets.
Enemy Champions
The Ancient Shadows expansion adds human champion ships. The AI gets a nemesis champion ship to counter your ships. The higher the AIP gets, the less nemesis champions get spawned. As the AI has little time to invest into these nemesis ships.
Note to the reader: what did I miss? Mention it in the comments, and I'll update the answer.


text:
Q: Is every non-solvable group a product of a set and a subgroup? Every solvable group is a Zappa-Szep-product. Non-solvable groups need not be a Zappa-Szep-product, $A_6$ being the smallest counter-example.
However, if we define $$S:={(),(236),(456),(246),(263),(162)}$$ and $$H:=<(12345),(345)>$$
we have $H=A_5$ and $SH=A_6$ (but $HS\ne A_6$ because $(465)$ is not in $HS$). $S$ is not a subgroup, therefore $H$ and $S$ do not commute.
Note that the product of two permutations is done from left to right, as it is in GAP, so the first permutation acts first.

Is every finite group with a composite order (in particular a non-solvable group) a product of this kind ? If yes, how can I prove it ?

A: When $G$ is a group of composite order $n$, choose a proper subgroup $H$ and let $S$ be a complete set of left coset representatives. Then, $G=SH$.
(Note that such a subgroup can always be found. For example, $H=\langle g\rangle$ for some nontrivial element $g\in G$. If $G$ happens to be cyclically generated by $g$, then we can take $H=\langle g^d\rangle$ for some divisor $d$ of $n$.)


text:
Q: Replace string path in log file with current folder name I'm new here and already tried to find solution to the following requirement without success. I'm trying to achieve this:
I have these 5 folders:
ServiceEngine
PaymentEngine
InvoiceEngine
ProcessEngine
OrderProcessEngine

Inside each of these folders, I have a log file with default path location to store the log files e.g. ServiceEngine/logs
The log file contain the following path structure:
name="RollingRandomAccessFile" fileName="logs/engine.log"
filePattern="logs/engine-%i.log"

I expect to find a way that I retrieve the name of the current folder which I'm in and replace the string engine with folder name
Example: I'm in ServiceEngine folder and execute a command that retrieve the current folder name. The expected result is:
name="RollingRandomAccessFile" fileName="logs/ServiceEngine.log"
filePattern="logs/ServiceEngine-%i.log

Later I change the directory to PaymentEngine and the expected result is:
name="RollingRandomAccessFile" fileName="logs/PaymentEngine.log"
filePattern="logs/PaymentEngine-%i.log

and so on. Maybe there is a smarter way to create a script that update the string in a loop like do; if ... fi; done or to use the for in ... loop.

A: Do you mean something like this?
~/ServiceEngine$ cat logfile
name="RollingRandomAccessFile" fileName="logs/engine.log"
filePattern="logs/engine-%i.log"

~/ServiceEngine$ awk -v path=$(basename $(pwd)) 'gsub("engine", path)' logfile
name="RollingRandomAccessFile" fileName="logs/ServiceEngine.log"
filePattern="logs/ServiceEngine-%i.log"

See basename, declaring variables in awk and awk gsub.

A: I guess I don't understand your question, but:
dir=$( basename $( pwd ) )
echo name="RollingRandomAccessFile" \
     fileName="logs/$dir.log" \
     filePattern="logs/$dir-%i.log"

Is that what you're looking for?

A: It sounds like you are looking for something like this:
$ sed 's/\bengine\b/'$(basename $(pwd))'/' logs

When run from within one of your folders, it spits out the text you're asking for. It wasn't clear what you wanted to do with that text though.


text:
Q: How do you use a LIWC-formatted dictionary with the R package Quanteda? As LIWC software and dictionaries are proprietary, I was pleased to see they seemed to play well with the still-in-development but excellent R package Quanteda.
The documentation for the R package Quanteda demonstrates its use with a LIWC-format dictionary, as does this SO post.
I purchased LIWC 2015 but can't figure out how to export the dictionary outside the application other than as a PDF.

A: Edited by request of Receptivity ("the commercial side of LIWC")
I will not advise you on how to extract the English LIWC 2015 dictionary from the Java Archive (.jar) file that contains the software which requires a purchase.
Unlike in previous versions of the LIWC software, the dictionary files are not distributed directly with the software.  But using your legally purchased serial number to log in, you can download the non-English dictionaries from LIWC2007 and LIWC2001 (depending on the language) from  http://dictionaries.liwc.net, which includes German, Dutch, Italian, Russian, French, and Spanish versions.
If you have a dictionary formatted in the same manner as the LIWC dictionaries, for instance the Moral Foundations dictionary, then this will work:
require(quanteda)
mfdict <- dictionary(file = "http://www.moralfoundations.org/sites/default/files/files/downloads/moral%20foundations%20dictionary.dic",
                    format = "LIWC")

which loads and converts the Moral Foundations dictionary into the quanteda format.  You can use the dictionary in constructing a document-feature matrix using
dfm(x, dictionary = mfdict)


text:
Q: How can I maximize a WPF page when the application starts? I have a simple WPF application with two xaml Pages. I'd like the app opening with the maximum size of the screen.
I've found only answers about WPF Windows, but for Pages there is not a "WindowState" property.
Thanks a lot!

A: In your Xaml window definition simply define:
WindowStartupLocation="CenterScreen" WindowState="Maximized"

A: You could set the Width and Height property manually according to your current Screen Resolution from here
System.Windows.SystemParameters.PrimaryScreenWidth;
System.Windows.SystemParameters.PrimaryScreenHeight;


text:
Q: How to use atos to properly symbolicate addresses from OSReportWithBacktrace? I am trying to hunt down retain leaks in an open-source project to support I2C based trackpads (https://github.com/kprinssu/VoodooI2CHID).
The reason why I believe that there are retain leaks is because when I attempt to unload the kernel extension via the following commands:
sudo kextunload -verbose 6 VoodooI2CHID.kext

I get the following output:
Kext user-space log filter changed from 0xff2 to 0xfff.
Kext kernel-space log filter changed from 0xff2 to 0xfff.
Kext library architecture set to x86_64.
Requesting unload of com.alexandred.VoodooI2CHID (with termnation of IOServices).
(kernel) User-space log flags changed from 0x0 to 0xfff.
(kernel) Received 'Unload' request from user space.
(kernel) Rescheduling scan for unused kexts in 60 seconds.
(kernel) Can't unload kext com.alexandred.VoodooI2CHID; classes have instances:
(kernel)     Kext com.alexandred.VoodooI2CHID class VoodooI2CPrecisionTouchpadHIDEventDriver has 1 instance.
(kernel)     Kext com.alexandred.VoodooI2CHID class VoodooI2CMultitouchHIDEventDriver has 1 instance.
Kernel error handling kext request - (libkern/kext) kext is in use or retained (cannot unload).
Failed to unload com.alexandred.VoodooI2CHID - (libkern/kext) kext is in use or retained (cannot unload).

I came across pmdj's excellent answer on tracking down retain leaks (Can't Unload Kernel Extension; Classes Have Instances). I verfied that my situation is the second case via ioreg (classes are being terminated but are not properly freed). Additionally, I used pmdj's hint by overiding taggedRelease and taggedRetain (https://stackoverflow.com/a/13471512/48660) to print the stack trace of the function calls.
Here's where I run into problems, I cannot use atos to convert the hex addresses back into human readable symbols. I use the follow command to generate the symbols:
atos -arch x86_x64 -o VoodooI2C.kext/Contents/MacOS/VoodooI2C -l 0xffffff7f8432b000 0xffffff804588dfa0
The load address parameter is retrieved from kextstat and  I expect the -l argument should handle the slide arithmetic.
atos should return a valid symbol but all I get is the hex address back. In the above example, I get 0xffffff804588dfa0 as the output. Can anybody point out what I exactly I am missing?

A: Both kextstat and OSReportWithBacktrace report unslid addresses, so KASLR is not your problem.
Notice that your kext is apparently loaded at 0xffffff7f8432b000, whereas your backtrace frame address is 0xffffff804588dfa0. This is quite far apart, and indeed kexts are always loaded in the 0xffffff7f8??????? (unslid) range, so 0xffffff804588dfa0 can't be anywhere near kext code. (the offset is about 3GB) It's almost certainly a function in the kernel proper. If you use atos with the appropriate running kernel's binary, it should be able to locate which one. For example:
atos -o /Library/Developer/KDKs/KDK_10.14.5_18F132.kdk/System/Library/Kernels/kernel 0xffffff804588dfa0

(I don't know what kernel version you are using, and this address doesn't seem to be meaningful in the 18F132 kernel, but you get the idea.)


text:
Q: Plotting points on a graph? I have a function and I want to draw points on that function.
For example:
def f(x):
    return x ** 2 + 2 * x + 4

x_val= np.linspace(-6,6)
graph = f(x_val)

plt.plot(x_val, graph)

This will give the function evaluated at x_val.
I want to plot points on the graph at f(-2), f(2) like this.

A: You can use plot with the third parameter being a marker. The different markers can be found here. The third parameter of plot is a string where the first letter indicates the color ('r' for red, 'g' for green, ...) and the second letter the marker. More information can be found in the official docs.
import matplotlib.pyplot as plt
import numpy as np

def f(x):
    return x ** 2 + 2 * x + 4

x_val= np.linspace(-6,6)
graph = f(x_val)

plt.plot(x_val, graph)
plt.plot(-2, f(-2), 'ro')
plt.plot(2, f(2), 'ro')

plt.show()

A: In case you have several points, you have two options:

*

*Plot them individually using a for loop

*Plot them all at once using a scatter plot via vectorised operation on a NumPy array of points (shown below)

points = np.array([-2, 2])

plt.plot(x_val, graph)
plt.scatter(points, f(points), c='r')
plt.show()


text:
Q: Segmentation Fault is given, why? (C) I've been studying C for a about 2 weeks now and decided to try my hand at a simple port scanner. I can compile the code with no errors but whenever I try to execute it I get a segmentation fault.
#include<stdio.h>
#include<sys/socket.h>
#include<errno.h>
#include<netdb.h>
#include<string.h>
#include<stdlib.h>

int scanPort(char hostaddr[], int port) {
    struct hostent *host;
    int err, i, sock;
    struct sockaddr_in sa;

    strncpy((char*)&sa , "" , sizeof sa);
    sa.sin_family = AF_INET;

    if (isdigit(hostaddr[0])) {
        sa.sin_addr.s_addr = inet_addr(hostaddr);
    } else if ((host = gethostbyname(hostaddr)) != 0) {
        strncpy((char*)&sa.sin_addr , (char*)host->h_addr , sizeof sa.sin_addr);
    } else {
        printf("\n[!] Failed to resolve host!\n");
        exit(1);
    }

    sa.sin_port = htons(port);
    sock = socket(AF_INET, SOCK_STREAM, 0);

    if (sock < 0) {
        printf("\n[!] Failed to create socket!\n");
        exit(1);
    }

    err = connect(sock,  (struct sockaddr*)&sa , sizeof sa);

    close(sock);

    if (err < 0) {
        return 0;
    } else {
        return 1;
    }
}

int main(int argc, char *argv[]) {
    if (argc != 4) {
        printf("usage: ./portscan [TARGET] [START PORT] [STOP PORT]\n");
        exit(0);
    }

    char host[20];
    strcpy(host, argv[1]);
    int beginport;
    int endport;

    if (isdigit(argv[2]) && isdigit(argv[3])) {
        beginport = atoi(argv[2]);
        endport = atoi(argv[3]);
    } else {
        printf("[!] Invalid port range given\n");
    }

    printf("[*] Beginning Scan...\n\n");

    int i = beginport;

    for (i; i<=endport; i++) {
        if (scanPort(host, i)) {
            printf("Port %d: Open\n", i);
        }
    }

    printf("\n[*] Scan complete!");
    return 0;
}

I understand that there is some improper/insecure function usage within the code, but I'm just trying to get this program functioning. This is only a test, not an actual program for use.
Here is a screenshot of compiling and executing, I don't think it'll be of much help though:

UPDATE: I passed arguments to it, still get segmentation fault:

UPDATE 2: I've added a few lines to evaluate argc
Thank you for your time.
-Defalt

A: The crash is happening here:
if (isdigit(argv[2]) && isdigit(argv[3])) {

The isdigit function expects an int (actually a char converted to an int), but you pass in a char *.  This invokes undefined behavior, which in this case (luckily for you) manifests as a crash.
You probably want to check the first character of each string, so pass in argv[2][0] and argv[3][0] to this function.
Also, this is incorrect:
strncpy((char*)&sa.sin_addr , (char*)host->h_addr , sizeof sa.sin_addr);

The strncpy function is for copying strings, not arbitrary bytes.  If there is a null byte among the bytes being copied, no others bytes after that one will be copied.  Use memcpy instead, which copies an exact number of bytes:
memcpy((char*)&sa.sin_addr , (char*)host->h_addr , sizeof sa.sin_addr);


text:
Q: My DatePickerDialog not showing the current date. How to get Current date in DatePickerDialog? I used TimepickerDialog and DatePicker Dialog to get the Time and Date.
But when open the Date Picker Dialog it showing different date click to view
Here is my code.
         final Calendar calendar = Calendar.getInstance();

            dt_day = calendar.get(Calendar.DAY_OF_MONTH);
            dt_month =calendar.get(Calendar.MONTH);
            dt_year = calendar.get(Calendar.YEAR);
           final DatePickerDialog datePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {

            @Override
            public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                 //     datePickerDialog.updateDate(12,12,1993);
                date.setText(dayOfMonth + "/" + (month+1) + "/" + year);
                str_date = String.valueOf(dayOfMonth + "/" + (month+1) + "/" + year);
            }
        },dt_day, dt_month,dt_year);

        datePickerDialog.show();

A: You have given wrong values in parameter, the third parameter should be dt_year and the fifth parameter should be dt_day


text:
Q: Parse through the line in csv with python I'm trying to parse csv file with python. When I try to read through each character in the string at each line, it only evaluate and prints out the result for the end character. I'm not sure what happened. Below is the code. Thanks.
def assignment(s):
    switcher = {
        "N": "N",
        "N": "Q",
        "I" : "S",
        "I" : "T",
        "I" : "K",
        "I" : "R",
        "I" : "H",
        "I" : "D",
        "I" : "E"
    }
    return switcher.get(s, "H")

with open('sentence.csv', 'r') as csv_file:
    csv_read = csv.reader(csv_file)
    for line in csv_read:
        i = 0
        index = 0
        aa = ""
        a = ""
        for index in range (len(line)):
            a=assignment(line[index])
            aa = aa + a
            print(aa)
            index +=1
            print(index)
        h = aa.count("H");
        i = aa.count("I");
        n = aa.count("N");

        print(aa + " has" + "H= " + str(h) + "I=" + str(i) + "N=" + str(n))
        ++i

A: You have your translation table (the dict) backwards.  You're trying to classify input characters as type N, I, or H.
I've reversed the dict order so you can look up things correctly, although you can do better if you search for Python translation tables.  I also reduced your code just enough to hard-code a test case:
def assignment(s):
    switcher = {
        "N": "N",
        "Q": "N",
        "S": "I",
        "T": "I",
        "K": "I",
        "R": "I",
        "H": "I",
        "D": "I",
        "E": "I"
    }
    return switcher.get(s, "H")

csv_read = ["QWERTASDFGZXCVBYUIOPHJKLNM"]
for line in csv_read:
    i = 0
    index = 0
    aa = ""
    a = ""
    for index in range (len(line)):
        a=assignment(line[index])
        aa = aa + a
        print(aa)
        index +=1
        print(index)
    h = aa.count("H");
    i = aa.count("I");
    n = aa.count("N");

    print(aa + " has" + "H= " + str(h) + "I=" + str(i) + "N=" + str(n))

Output (last lines only):
25
NHIIIHIIHHHHHHHHHHHHIHIHNH
26
NHIIIHIIHHHHHHHHHHHHIHIHNH hasH= 17I=7N=2

I'll let you clean up the tracing and formatting from here.


text:
Q: How to disable USB Keyboard at run time from udev.c not from udev rules I want to disable my USB keyboard at boot time (in some scenarios) without modifying udev rules, as I know udev rules only works when a device is attached or detached from the target.
Is there any option in "udev.c" or in udev rules by which I can disable my USB keyboard at boottime?

A: Modifying udev rules is actually the way to go. Udev rules are applied when the device is attached, but that includes devices that are already attached when the system boots: once udev has started, it applies all the rules to already-connected devices.
So write a udev rule that declares your keyboard as not authorized.


text:
Q: Polymer 1.0 how to show the value of paper input in vaadin grid after pushing button? I am trying to create some paper input in Polymer. When I click the "calculate" icon next to the item, it doesn't show the value or the result of paper input. It looks like it's getting the wrong in calling the value (?), and I'm not sure how to fix it? Thanks!
<link rel="import" href="../bower_components/polymer/polymer.html">
<link rel="import" href="../bower_components/iron-pages/iron-pages.html">
<link rel="import" href="../bower_components/iron-selector/iron-selector.html">
<link rel="import" href="shared-styles.html">
<link rel="import" href="../bower_components/paper-input/paper-input.html">
<link rel="import" href="../bower_components/paper-icon-button/paper-icon-button.html">
<link rel="import" href="../bower_components/paper-button/paper-button.html">
<link rel="import" href="../bower_components/vaadin-grid/vaadin-grid.html">
<link rel="import" href="../bower_components/vaadin-date-picker/vaadin-date-picker.html">

<dom-module id="my-view2">
  <template>

      <paper-input type="number" name="satu" label="BLABLABLA1" value="{{todo.satu}}"></paper-input>
      <paper-input type="number" name="dua"label="BLABLABLA2" value="{{todo.dua}}"></paper-input>
      <paper-input type="number" name="tiga"label="BLABLABLA3" value="{{todo.tiga}}"></paper-input>

   <paper-icon-button src="calculator.ico" on-tap="_addTodo"></paper-icon-button>

<vaadin-grid item="{todos}">

          <colgroup>
            <col name="satu">
            <col name="dua">
            <col name="tiga">
          </colgroup>

      </vaadin-grid>

  </template>

</dom-module>

A: your binding to item property of vaadin grid is invalid. You are missing one more brackets {}, plus property should be called items not item (according to documentation).


text:
Q: How to send BIGPKT using SSH command I need to test common criteria requirement for my SSH clients. As part of that i need to send larger packets from SSH client. Is there ssh option to do so  ? This is the requirements
    FCS_SSHC_EXT.1.3The  TSF  shall  ensure  that,  as described  in  RFC  4253,
packets  greater than [assignment: number of bytes]bytes in  an SSH transport  connection  are dropped.

A: I don't believe OpenSSH provides an option to control packet size.  A normal SSH client would send different amounts of data depending on how much data there was to read or write at the time, so using a normal SSH client wouldn't be a good way to test this.  You'd probably want to craft a custom tool to test this case, so if you are testing clients, you'd want to craft a custom server.
Note that as far as I'm aware, RFC 4253 doesn't require that packets over the maximum size are dropped.  In fact, it says, "Implementations SHOULD support longer packets, where they might be needed."  It does specify that implementations should take care to avoid DoS attacks, but with modern cryptography and the resources of a typical system, an implementation might well be able to process a 1 MiB packet without risk of DoS.
If your goal is to find clients that meet some set of criteria, it may be practically easier to see if someone else has done that work for you.


text:
Q: MySQL: can not get rid of "Using filesort" in a simple query Simple query but can not get rid of "using filesort":
CREATE TABLE IF NOT EXISTS `online` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `uid` int(11) NOT NULL,
  `expiration` int(11) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `uid` (`uid`),
  KEY `expiration` (`expiration`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1925234 ;

mysql> explain SELECT i.id, i.uid, i.expiration, u.nick, u.mainpicture
    -> FROM online i join usertable u on i.uid = u.id
    -> order by i.expiration DESC limit 0,12;

+----+-------------+-------+--------+---------------+---------+---------+----------------+------+----------------+
| id | select_type | table | type   | possible_keys | key     | key_len | ref            | rows | Extra          |
+----+-------------+-------+--------+---------------+---------+---------+----------------+------+----------------+
|  1 | SIMPLE      | i     | ALL    | uid           | NULL    | NULL    | NULL           | 1020 | Using filesort |
|  1 | SIMPLE      | u     | eq_ref | PRIMARY       | PRIMARY | 4       | dbasen01.i.uid |    1 |                |
+----+-------------+-------+--------+---------------+---------+---------+----------------+------+----------------+
2 rows in set (0.00 sec)

"usertable" has index on "id" column. Tried to order by "i.id" (primary key) but the same - query still uses filesort.
Update after RolandoMySQLDBA answer:
+----+-------------+-----------------+--------+---------------+---------+---------+-------+------+----------------+
| id | select_type | table           | type   | possible_keys | key     | key_len | ref   | rows | Extra          |
+----+-------------+-----------------+--------+---------------+---------+---------+-------+------+----------------+
|  1 | PRIMARY     | <derived2>      | ALL    | NULL          | NULL    | NULL    | NULL  |   12 |                |
|  1 | PRIMARY     | u               | eq_ref | PRIMARY       | PRIMARY | 4       | i.uid |    1 |                |
|  2 | DERIVED     | online          | ALL    | NULL          | NULL    | NULL    | NULL  | 1009 | Using filesort |
+----+-------------+-----------------+--------+---------------+---------+---------+-------+------+----------------+

Solution:
I deleted column "id" because it's not used. Then modified index:
ALTER TABLE online ADD INDEX expiration (expiration,uid);

Result:
+----+-------------+-------+--------+---------------+------------+---------+----------------+------+-------------+
| id | select_type | table | type   | possible_keys | key        | key_len | ref            | rows | Extra       |
+----+-------------+-------+--------+---------------+------------+---------+----------------+------+-------------+
|  1 | SIMPLE      | i     | index  | uid           | expiration | 8       | NULL           |   12 | Using index |
|  1 | SIMPLE      | u     | eq_ref | PRIMARY       | PRIMARY    | 4       | dbasen01.i.uid |    1 |             |
+----+-------------+-------+--------+---------------+------------+---------+----------------+------+-------------+

Thanks to all.

A: Here is your original query
SELECT i.id, i.uid, i.expiration, u.nick, u.mainpicture
FROM online i join usertable u on i.uid = u.id
order by i.expiration DESC limit 0,12;

Try refactoring the query to coerce the retrieval of 12 rows before doing the JOIN
SELECT i.id, i.uid, i.expiration, u.nick, u.mainpicture FROM
(SELECT * FROM online ORDER BY expiration DESC limit 0,12) i
LEFT JOIN usertable u on i.uid = u.id;

The subquery may be forced to use the expiration index now.
You can also try this one:
SELECT i.id, i.uid, i.expiration, u.nick, u.mainpicture FROM
(SELECT id FROM online ORDER BY expiration DESC limit 0,12) ik
LEFT JOIN online i on ik.uid = u.id;
LEFT JOIN usertable u on ik.uid = u.id;

but you will need redo the expiration index
ALTER TABLE online DROP INDEX expiration;
ALTER TABLE online ADD INDEX expiration (expiration,id);

Give it a Try !!!

A: I don't have time to check; however, just looking at the query I expect the filesort is being triggered by the ORDER BY/LIMIT. There isn't much use in doing a sequential O(n) pass over the uid index when it will still have to do O(n) datafile lookups followed by an external sort to extract the first 12 before performing the 12 (or-so) eq_ref joins against usertable's id index followed by probes into usertable's datafile to extract the fields required by select.
I expect Mysql believes (correctly) that it is better to do a single sequential O(n) pass over the datafile followed by the external sort, the eq_ref joins and the probes.
What you need is to do the external sort for mysql up-front, so it doesn't have to do it itself. That means you need a covering index over the join/where conditions.
ie.
ALTER TABLE online ADD INDEX expiration (expiration,uid,id);

Then again, given there are only 1020 rows in online, why are you worrying about this now?

A: explain SELECT i.id, i.uid, i.expiration, u.nick, u.mainpicture, count(*) as bogusvar
-> FROM online i join usertable u on i.uid = u.id
-> GROUP BY i.id
-> order by i.expiration DESC limit 0,12;

Adding group by to force the index. Ugly but worked for me.


text:
Q: "The OAuth client was not found." from admin.directory API When trying to obtain an access token through the admin.directory API, I get a 401 error: "The OAuth client was not found."  As best I can tell the url is properly formed, but I honestly have no idea if either of my client_id's qualify me for this API, or for OAuth2, since this is my first foray into same.  Is there a way to verify that a specific client_id is valid for a specific API?

A: Your OAuth client ID is created in the Google Developers Console.  Create a new client for a project (in the sidebar under "APIs & auth", select Credentials), and copy the client ID into your request. If you already have a client ID, perhaps you copied it incorrectly.
For an interactive demo, try the OAuth Playground. You can configure it to use your own OAuth client ID and redirect URIs.


text:
Q: Will it work if i put a div inside another div Does div work inside another div? If so, how should I do the CSS? I just started doing this so I'm not really sure.

A: Yes, a div inside div works. Basically that is how many of webpages are designed. Take a look at source of Wikipedia. Stacked divs...
So why you want to nest
? For example, you don't want your page to be over whole width of the screen, but you want it centered and to have some blank space on left and right. You would do something like

    Some content...

But then you want to style the content inside the outside div. Again, you need div... Consider divs as LEGO blocks: you make a house out of LEGO block, but you furnish the interior of the house with LEGO blocks as well. The same is here, just substitute LEGO blocks with
. At the end you might get something like this:

Click on image and see what happens...

           ...

Might be a poor example but just to give you an idea...

A: According to MDN:

The HTML
 element:
Content categories: Flow content, palpable content.
Permitted content: Flow content.

It means you can put any of elements with current content category into an element that permits this content category's element inside.
For example:

div {
  padding: 20px;
  background-color: yellow;
}

div div {
  background-color: red;
}

  Main div

Child div

You can do the same with some other elements, simply check MDM HTML element reference before (or HTML 5 specification). Also you could try HTML 5 Validator.


text:
Q: c++ thread waiting for user IO ('getchar()') hangs 'Py_Initialize()' in main process I just stumbled upon a really strange problem.  In my code, I have one thread launch to wait for user input---in case the user wants to interrupt the main process.  After that thread is going, I try to do some computations using python.  The thread looks for user input using getchar() -- if the input is a return, a boolean flag is set to make the main process stop doing what its doing.  The main process checks this flag every once and a while, and if its set, it takes appropriate action.
Schematically:
bool volatile stopper = false;
thread stopThread(interrupt, &stopper);
while( !stopper ) {
    /* ... stuff ... */
    Py_Initialize();                            // this doesn't return unless 'interrupt()' completes.
    /* ... do things with python object ... */
}

the interrupt method looks like,
void interrupt(bool *st) {
    char ch;
    while( ch != '\n' ) {
        ch = getchar();
    }
    *st = true;
}

If I replace the getchar() while-loop with a sleep(10), the Py_Initialize() returns fine, and everything works great.  Why is the IO request blocking Py_Initialize()?
thanks!

A: When you call an I/O function like getchar, you hold a lock on some I/O object until the function terminates. It is very bad form to hold a lock indefinitely in a multi-threaded program, as that will cause any thread that tries to acquire that lock to block indefinitely. Don't call blocking I/O functions in multi-threaded programs.


text:
Q: Append form value to URL that already has variables in it I've got a page showing the results of a MYSQL query written in PHP. The URL has the variables that the user submitted on the previous page as:
www.mydomain.com/search/?var1=xx&var2=xx&var3=xx
When the user is on the results page they need to be able to sort the results. To do this I've got a SELECT form
<form action="/search<?php echo $urlQuery; ?>"  name="order "class="formsrch" method="post" >
            sort by:
            <select class="order" id="order" name="order" onChange="this.form.submit()">
                <option value="pricedesc">Price High to Low</option>
                <option value="priceasc">Price Low to High</option>
                <option value="dist">Distance</option>
            </select>
        </form>

The variable $urlQuery contains the string to be appended onto the url:
i.e. $urlQuery = "?var1=xx&var2=xx&var3=xx"
The problem is that when the form is submitted the page is reloaded and at the end of the url is ?order=dist.
Is there a way of replacing the question mark with an ampersand so the page will load and the value of order can be retreived?
Or, if anyone has a better way of doing the whole thing I'm definitely open to suggestions.
Thanks

A: You could make a hidden field for each of the variables you want to transfer so that they get appended too.
Better still, make the method of the form get and then access all the variables with the $_REQUEST global in the backend script.

A: Output the other variables as <input type="hidden" name="var1" value="xx" /> instead of as the form action, so they'll get taken into your query string.

A: why don't you put them in the form as hidden?
<?php
$extraVars = "";
  foreach($_GET AS $key=>$value) {
   $extraVars .= '<input type="hidden" name="'.$key.'" value="'.$value.'" />';
  }
?>
<form action="/search"  name="order "class="formsrch" method="post" >
    <?php echo $extraVars;?>
    sort by:
    <select class="order" id="order" name="order" onChange="this.form.submit()">
        <option value="pricedesc">Price High to Low</option>
        <option value="priceasc">Price Low to High</option>
        <option value="dist">Distance</option>
    </select>
</form>

A: With this action="/search" and $urlQuery = "?var1=xx&var2=xx&var3=xx"
then to have the value appended on the querysting you should change the form method to "GET".
If you want to keep the form method to "POST" then some javascript would be required to change the action of the form when the form is submitted.


text:
Q: Optimizations for Travelling Salesman Problem I have to design a branch-and bound algorithm that solves the optimal tour of a graph on the cartesian plane every time. I have been given the hint that identifying hopeless branches earlier in the runtime will compound into a program that runs "a hundred times faster". I had the idea of assuming that the shortest edge connected to the starting/ending node will be either the first or last edge in the tour but a thin diamond shaped graph proves otherwise. Does any one have ideas for how to eliminate these hopeless branches or a reference that talks about this?

A: Are you allowed to use any kind of heuristic? If you have a heuristic that easily finds a feasible, yet not optimal tour, then you have a good bound for the tour. For example, in a given graph the optimal tour has length 100 miles (which is obviously not known beforehand). If you have a heuristic that finds a feasible tour with length say 500 miles, many branches in the branch and bound tree can be cut off by this upper bound. If the LP relaxation returns an optimal tour of length > 500 miles in a given part of the branch-and-bound tree, then the whole branch can be cut off as the integer solution cannot be better than the relaxation and we know that the optimal tour is less than or equal to 500 miles.


text:
Q: Please help a noob understand service reference bindings I was recently asked to connect to a third party web service (*.asmx). I created a new ASP.NET website, and used the wizard to create the Service reference. When I went to call the service, the code complained that it did not know which endpoint to use.
I looked in the Web.config, and sure enough, the wizard created TWO bindings, and thus two end-points. By adding either endpoint to the service call, everything works perfectly.
My question then is simply meant to help me understand why I have two bindings, and if there is some reason that I should use one over the other? Or should I remove one, and if so, which?
The bindings look totally different to me, and I am assuming that two different protocols are being used (but they are both labeled SOAP, so..). I am very "front end focused" and don't get involved in the back end mechanics very often, which is why I am asking. I'll post the bindings below.
    <bindings>
  <basicHttpBinding>
    <binding name="ServiceSoap" closeTimeout="00:01:00"
      openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
      allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
      maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
      messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
      useDefaultWebProxy="true">
      <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
        maxBytesPerRead="4096" maxNameTableCharCount="16384" />
      <security mode="None">
        <transport clientCredentialType="None" proxyCredentialType="None"
          realm="" />
        <message clientCredentialType="UserName" algorithmSuite="Default" />
      </security>
    </binding>
  </basicHttpBinding>
  <customBinding>
    <binding name="ServiceSoap12">
      <textMessageEncoding maxReadPoolSize="64" maxWritePoolSize="16"
        messageVersion="Soap12" writeEncoding="utf-8">
        <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
          maxBytesPerRead="4096" maxNameTableCharCount="16384" />
      </textMessageEncoding>
      <httpTransport manualAddressing="false" maxBufferPoolSize="524288"
        maxReceivedMessageSize="65536" allowCookies="false" authenticationScheme="Anonymous"
        bypassProxyOnLocal="false" decompressionEnabled="true" hostNameComparisonMode="StrongWildcard"
        keepAliveEnabled="true" maxBufferSize="65536" proxyAuthenticationScheme="Anonymous"
        realm="" transferMode="Buffered" unsafeConnectionNtlmAuthentication="false"
        useDefaultWebProxy="true" />
    </binding>
  </customBinding>
</bindings>
<client>
  <endpoint address="http://someURL.asmx" binding="basicHttpBinding"
    bindingConfiguration="ServiceSoap" contract="ServiceReference.ServiceSoap"
    name="ServiceSoap" />
  <endpoint address="http://someURL.asmx" binding="customBinding"
    bindingConfiguration="ServiceSoap12" contract="ServiceReference.ServiceSoap"
    name="ServiceSoap12" />
</client>

A: I believe the service offers both SOAP 1.1 and SOAP 1.2. You will need to specify the client configuration to use in the constructor of the service reference class:
var client = new MyClient("ServiceSoap12");

A: It looks like this service simply exposed two endpoints with different encodings.
You would also see two bindings if it allowed both http and https.


text:
Q: keeping view name and corresponding controller method name different I have a controller method named CreatePANApplication but I have created view page for this named as PANApplication. Now when I am trying to call this method from another view page as:
// dataTable code block
<td>
    @Html.ActionLink("PAN Application", "CreatePANApplication", new { id = item.PANKey }, new { @class = "btn btn-warning" })
</td>

getting error as:
The view 'CreatePANApplication' or its master was not found or no view engine supports the searched locations.

It means that I should not keep my controller name and corresponding view page name different. But many times we have to change the view page name, what can we do at that time?
Controller class:
public ActionResult CreatePANApplication(int? id)
        {
            try
            {
                if (id == null)
                {
                    return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
                }
                var data = (from z in db.PANModels
                            where z.PANKey == id
                            select z).ToList();

                if (data == null)
                {
                    return HttpNotFound();
                }
                return View(data);
            }
            catch (Exception)
            {

                throw;
            }
        }

A: if your view is still in the  folder that is named as a controller, or you put your view in a Shared folder, you can use this
 return View("PANApplication", data);

but if your view is in different folder you will have to use the full path
return View(" ~/Views/folder/PANApplication.cshtml", data);


text:
Q: howto to load listView items in app I use Telerik Icenium for creating a mobile app, its just Cordova and Jquery mobile involved.
On the frontpage I have a listView like this

Project 1

Project 2

This I would like to load from local storage instead, and then when the user chooses so, I will synch that against my API.
Would it be a good way to use the localstorage and fetch them items from there? If so, could anyone give me a good way to load the items either from a local json file or from a local database on the mobile into the listView.
Thanks

A: I made you a working example: http://jsfiddle.net/Gajotres/W3YDd/
$(document).on('pagebeforeshow', '#index', function(){
        if(typeof(Storage)!=="undefined") {
            localStorage.jsonExample='[{"score":null,"popularity":3,"translated":true,"adult":false,"language":"en","original_name":"The Goonies","name":"The Goonies","alternative_name":"Балбесы","movie_type":"movie","id":9340,"imdb_id":"tt0089218","url":"http://www.themoviedb.org/movie/9340","votes":43,"rating":8.5,"certification":"PG","overview":"A young teenager named Mikey Walsh finds an old treasure map in his fathers attic. Hoping to save their homes from demolition, Mikey and his friends Data Wang, Chunk Cohen, and Mouth Devereaux run off on a big quest to find the secret stash of Pirate One-Eyed Willie.","released":"1985-06-06","posters":[{"image":{"type":"poster","size":"thumb","height":138,"width":92,"url":"http://d3gtl9l2a4fn1j.cloudfront.net/t/p/w92/bZUbpjwnarSHJK40W9sGpyedWhx.jpg","id":"4ea6009334f8633bdc002f61"}},{"image":{"type":"poster","size":"w154","height":231,"width":154,"url":"http://d3gtl9l2a4fn1j.cloudfront.net/t/p/w154/bZUbpjwnarSHJK40W9sGpyedWhx.jpg","id":"4ea6009334f8633bdc002f61"}},{"image":{"type":"poster","size":"cover","height":278,"width":185,"url":"http://d3gtl9l2a4fn1j.cloudfront.net/t/p/w185/bZUbpjwnarSHJK40W9sGpyedWhx.jpg","id":"4ea6009334f8633bdc002f61"}},{"image":{"type":"poster","size":"w342","height":513,"width":342,"url":"http://d3gtl9l2a4fn1j.cloudfront.net/t/p/w342/bZUbpjwnarSHJK40W9sGpyedWhx.jpg","id":"4ea6009334f8633bdc002f61"}},{"image":{"type":"poster","size":"mid","height":750,"width":500,"url":"http://d3gtl9l2a4fn1j.cloudfront.net/t/p/w500/bZUbpjwnarSHJK40W9sGpyedWhx.jpg","id":"4ea6009334f8633bdc002f61"}},{"image":{"type":"poster","size":"original","height":1500,"width":1000,"url":"http://d3gtl9l2a4fn1j.cloudfront.net/t/p/original/bZUbpjwnarSHJK40W9sGpyedWhx.jpg","id":"4ea6009334f8633bdc002f61"}}],"backdrops":[{"image":{"type":"backdrop","size":"thumb","height":169,"width":300,"url":"http://d3gtl9l2a4fn1j.cloudfront.net/t/p/w300/awhHFqiw6Dta0uHQVjgwQiyOgro.jpg","id":"4ffdbd7f760ee3570d0000e8"}},{"image":{"type":"backdrop","size":"poster","height":439,"width":780,"url":"http://d3gtl9l2a4fn1j.cloudfront.net/t/p/w780/awhHFqiw6Dta0uHQVjgwQiyOgro.jpg","id":"4ffdbd7f760ee3570d0000e8"}},{"image":{"type":"backdrop","size":"w1280","height":720,"width":1280,"url":"http://d3gtl9l2a4fn1j.cloudfront.net/t/p/w1280/awhHFqiw6Dta0uHQVjgwQiyOgro.jpg","id":"4ffdbd7f760ee3570d0000e8"}},{"image":{"type":"backdrop","size":"original","height":1080,"width":1920,"url":"http://d3gtl9l2a4fn1j.cloudfront.net/t/p/original/awhHFqiw6Dta0uHQVjgwQiyOgro.jpg","id":"4ffdbd7f760ee3570d0000e8"}}],"version":3350,"last_modified_at":"2013-03-19 13:57:18 UTC"}]';
        }

    var jsonObject = jQuery.parseJSON(localStorage.jsonExample);

    $('#movie-data').append('
Movie name: ' + jsonObject[0].original_name+ '
');
    $('#movie-data').append('
Popularity: ' + jsonObject[0].popularity + '
');
    $('#movie-data').append('
Rating: ' + jsonObject[0].rating+ '
');
    $('#movie-data').append('
Overview: ' + jsonObject[0].overview+ '
');
    $('#movie-data').append('
Released: ' + jsonObject[0].released+ '
');
    $('#movie-data').listview('refresh');
});

For a better clarification, this example was created from my other example:
http://jsfiddle.net/Gajotres/jLdFj/
In this example json is acquired from a remote source. But basic principle is the same.


text:
Q: Custom NgbModal service to set default config on open does not find an entry component I want all the modals in our application to have a set of default options, and not have to apply them individually each time a modal is opened.  So I created a service that extends NgbModal so I could overwrite the open method since in NgBootstrap v1.1.2 there is no global config, but the entry component though listed in the feature module is not found.
I'm wondering if the service being provided in/core doesn't see entry components loaded in a feature module?  Using NgbModal directly the modal opens as you would expect, but changing the provided class doesn't seem to replace the service or swapping the DI from NgbModal to the ModalService produces this error:
ERROR Error: No component factory found for
ConfirmReleaseDocumentsModalComponent. Did you add it to
@NgModule.entryComponents?

Can anyone see why this might not work, or is there a better way to have a global config on a modal in NgBootstrap v1.1.2?
Service
import { Injectable } from '@angular/core';

import { NgbModal, NgbModalOptions, NgbModalRef } from '@ng-bootstrap/ng-bootstrap';

@Injectable()
export class ModalService extends NgbModal {

  public open(content: any, options?: NgbModalOptions): NgbModalRef {
    const defaultOptions: NgbModalOptions = {
      backdrop: 'static',
      keyboard: false
    };
    options = { ...defaultOptions, ...options }
    return super.open(content, options);
  }
}

App Module
@NgModule({
  imports: [
    BrowserModule,
    CoreModule,
    SharedModule
  ],
  declarations: [
    AppComponent
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

Core Module
@NgModule({
  imports: [
    CommonModule
  ],
  providers: [
    ModalService
  ]
})
export class CoreModule {
  constructor(@Optional() @SkipSelf() parentModule: CoreModule) {
    throwIfAlreadyLoaded(parentModule, 'CoreModule');
  }
}

Feature Module
@NgModule({
  imports: [
    CommonModule,
    SharedModule,
    DocumentsRoutingModule
  ],
  declarations: [
    // ...
    ConfirmReleaseDocumentsModalComponent
    // ...
  ],
  entryComponents: [
    ConfirmReleaseDocumentsModalComponent
  ]
})
export class DocumentsModule { }

I initially tried to replace the provider, but this didn't work for some reason:
providers: [
  { provide: NgbModal, useClass: ModalService },
]

So then I tried using the service directly:
Component Opening Modal
constructor(
  // private modalService: NgbModal, // original that works
  private modalService: ModalService, // replaced with ModalService
) { }

public releaseBatchFromQueue(): void {
  fromPromise(this.modalService
    .open(ConfirmReleaseDocumentsModalComponent)
    .result)
    .pipe(
      switchMap((result: boolean) => {
        return (result)
          ? this.documentService
            .releaseFromQueue(this.selectedIds)
          : Observable.empty();
      })
    )
    .subscribe(...);
}

Update
Also tried just invoking NgbModal directly in the service and not extending, but it produces the same entry component error:
import { Injectable } from '@angular/core';

import { NgbModal, NgbModalOptions, NgbModalRef } from '@ng-bootstrap/ng-bootstrap';

@Injectable()
export class ModalService {

  constructor(
    private modalService: NgbModal
  ) { }

  public open(content: any, options?: NgbModalOptions): NgbModalRef {
    const defaultOptions: NgbModalOptions = {
      backdrop: 'static',
      keyboard: false
    };
    options = { ...defaultOptions, ...options }
    return this.modalService.open(content, options);
  }
}

A: It's related to lazy loading of modules.  Entry components are NOT loaded if they are in a lazy loaded module, and must be moved up to shared.  There is a posted GitHub issue related to entry components in modules not being available, but it's been open for over a year without much activity from contributors so it might be an issue and in the backlog for awhile - https://github.com/angular/angular/issues/14324.


text:
Q: Edit>copy/paste implementation with perl / tk I'm using Perl/Tk to build the GUI for an application. I plan on adding an edit menu to it with standard cut, copy, and paste options. Right here is where I realized that I've never actually interacted with the clipboard using perl.
Can anyone give me a link to information about messing with clipboard in perl? Is there a perl module for those kind of functions in specific?
And would I have to modify my code to be platform-specific if I interact with the clipboard since it's part of the host OS, and not part of my application itself?
Thanks in advance for the help!

A: Are you looking for Win32::Clipboard?

A: use strict;
use Win32::GuiTest qw(:ALL);
use Win32::Clipboard;
use POSIX qw(strftime);

my @windows = FindWindowLike( 0, "Total", "" );
die "Could not find Total\n" if not @windows;

SetForegroundWindow( $windows[0] );

&send_keys;

sub send_keys {
my $dir=strftime( '%Y%m%d', localtime(time) );
my $CLIP = Win32::Clipboard();
  $CLIP->Set($dir);
  $CLIP->WaitForChange();
    SendKeys("^V");
#    SendKeys("{ENTER}");
}


text:
Q: Laravel Remember Me, running with Auth::attempt? So I have this code:
public function postLogin() {
    // validate the info, create rules for the inputs
    $rules = array(
        'username'    => 'required', // make sure the email is an actual email
        'password' => 'required|alphaNum|min:3' // password can only be alphanumeric and has to be greater than 3 characters
    );

    // run the validation rules on the inputs from the form
    $validator = Validator::make(Input::all(), $rules);

    // if the validator fails, redirect back to the form
    if ($validator->fails()) {
        return Redirect::route('login')
            ->withErrors($validator) // send back all errors to the login form
            ->withInput(Input::except('password')); // send back the input (not the password) so that we can repopulate the form
    } else {

        $remember = (Input::has('remember')) ? true : false;
        // create our user data for the authentication
        $userdata = (array(
            'username'  => Input::get('username'),
            'password'  => Input::get('password')
        ), $remember);

        // attempt to do the login
        if (Auth::attempt($userdata)) {

            // validation successful!
            // redirect them to the secure section or whatever
            // return Redirect::to('secure');
            // for now we'll just echo success (even though echoing in a controller is bad)
            echo 'SUCCESS!';

        } else {

            // validation not successful, send back to form
            return Redirect::route('login')
             ->with('global', 'Incorrect username or password. Please try again.');
        }
    }
}

When it runs I get: syntax error, unexpected ','. Basically it isn't expecting the $remember to be passed there. Where is it meant to be? I've tried putting it here: Auth::attempt($userdate), $remember) { } but that didn't work either. It had the same error. Not sure what's going on. Any help would be appreciated.

A: You can use Auth::viaRemember() in your Authcontroller, to check if a user was already logged:
if (Auth::check() || Auth::viaRemember()) {...

And change your login-check as follows:
//Assuming, the remember-input is a checkbox and its value is 'on'
if (Auth::attempt($userData, (Input::get('remember') == 'on') ? true : false)) {...


text:
Q: Not able to launch VMware Player Installing VMware Player 6.0.6
configuring...
[#########################################################] 100%
Installation was successful.
root@shirishnag:/home/shirishnag/Desktop#vmware-installer -l
No protocol specified
No protocol specified
Product Name    Product Version
==============  ================
vmware-player   6.0.6.2700073
root@shirishnag:/home/shirishnag/Desktop#

I'm not able to launch VMware Player due to No protocol specified error asking for GNU C compiler gcc version 7.2.0 was not found.

A: Alternatively, try the graphical installation method.

*

*Therefore go to the vmware website and download the bundle of your
choice: wm ware: all downloads

*Then execute the script you just downloaded in a terminal: eg: sudo sh VMware-Player-12.5.1-yyy.x86_64.bundle (VMware-Player-12.5.1-yyy.x86_64.bundle has to be the path to your downloaded file and can also be: User/Downloads/VMware-Player-12.5.1-yyy.x86_64.bundle)

*Follow the instructions in the installation manager

*To start it, type vmplayer in a terminal.

It is possible that even with this installation procedure you cannot launch it. Before giving more detailed information about this case, please try to update your version (even you just downloaded it). You can update your kernel with sudo vmware-modconfig --console --install-all within a terminal.
Good luck and welcome to Ask Ubuntu!