text:
Q: pass an empty argument into an scheduled task xml file I am trying to run a batch file when some specific events occurs and I want to pass some null arguments to one of my tasks. The problem is that I don't know how.
I have tried a lot of combinations but without success.
My xml files looks something like:
    ........

      <ValueQueries>
            <Valuename="TargetUserName">Event/EventData/Data[@Name='TargetUserName']</Value>
            <Value name="EventID">Event/System/EventID</Value>
      </ValueQueries>

    ......

   <Exec>
      <Command>C:\passwd.bat</Command>
      <Arguments>$(TargetUserName) $(SubjectUserName) $(EventID) </Arguments>
    </Exec>

Now, I would like to pass an empty argument [between $(TargetUserName) and $(EventID)] for one of my events but I didn't manage to do this yet.
Any suggestions ?


text:
Q: Placing 4 servlets in one project i dont know how to place many servlets in one project. Am I supposed to create seperate web.xml file for each one? I have 4 html files named index.html,index1.html,index2.html and index3.html
Thanks beforehand
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

 xmlns="http://java.sun.com/xml/ns/javaee"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
   http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID"
  version="3.0">
 <display-name>WM2_as03</display-name>

 <servlet>
<servlet-name>form</servlet-name>
<servlet-class>com.ccc.Task3</servlet-class>

 </servlet>
<servlet-mapping>
<servlet-name>form</servlet-name>
<url-pattern>/register</url-pattern>
 </servlet-mapping>

 <servlet>
 <servlet-name>newtask</servlet-name>
 <servlet-class>com.ccc.Task3</servlet-class>

</servlet>
<servlet-mapping>
<servlet-name>newtask</servlet-name>
<url-pattern>/taskkk</url-pattern>
</servlet-mapping>

<welcome-file-list>
  <welcome-file>index.html</welcome-file>
 <welcome-file>index.htm</welcome-file>
     <welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
    </web-app>

A: Create 1 web.xml file and add multiple servlets :
<servlet>
  <servlet-name>Servlet1</servlet-name>
  <servlet-class>path_to.Servlet1</servlet-class>
</servlet>
<servlet-mapping>
  <servlet-name>Servlet1</servlet-name>
  <url-pattern>/s1</url-pattern>
</servlet-mapping>
 <servlet>
  <servlet-name>Servlet2</servlet-name>
  <servlet-class>path_to.Servlet2</servlet-class>
</servlet>
<servlet-mapping>
  <servlet-name>Servlet2</servlet-name>
  <url-pattern>/s2</url-pattern>
</servlet-mapping>

A: Instead using web.xml
<servlet>
  <servlet-name>servletName</servlet-name>
  <servlet-class>packageName.servletName</servlet-class>
</servlet>

<servlet-mapping>
  <servlet-name>servletName</servlet-name>
  <url-pattern>/yourServletUrl</url-pattern>
</servlet-mapping>

you can use annotations since servlets 3.0.
import javax.servlet.annotation.WebServlet;

@WebServlet(name = "servletName", urlPatterns = { "/yourServletUrl" })
public class servletName extends HttpServlet {

It is easier and more readable.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Swift: Which one of the following code is better performance wise As I know let is better over var but I am not sure which one of the following is good practice on the performance basis.
var edgeValue: Int
var edgeChars: String
var edgeColor: String

if directionUp {
  edgeValue = -5
  edgeChars = "x"
  edgeColor = "red"
} else {
  edgeValue = 5
  edgeChars = "y"
  edgeColor = "green"
}

or
let edgeValue = directionUp ? -5 : 5
let edgeChars = directionUp ? "x" : "y"
let edgeColor = directionUp ? "red" : "green"

Last one is more readable and they are constants but if I have to change directionUp to anotherCondition in the future then I will need to change it in all lines and it has to calculate or check directioinUp on each line run.
I am looking for best code among these two performance wise.
Thanks in advance for all of your answers and suggestions.

A: Both solutions end up being compiled to assembly code, that has multiple steps:

*

*Memory allocation

*Copy those value L1, L2, ... in CPU

*Comparation
...

Assembly code looks like below:
MOV AX,5h
MOV BX,5h
SUB AX,BX
JZ EQUALS
JNZ NOTEQUALS

EQUALS:
MOV CL,'Y'
JMP PRINT

NOTEQUALS:
MOV CL,'N'

PRINT:
MOV AH,2
MOV DL,CL
INT 21H

RET

This solution looks elegant but it cost more steps to execute than the others,
comparing directionUp three time as example.
let edgeValue = directionUp ? -5 : 5
let edgeChars = directionUp ? "x" : "y"
let edgeColor = directionUp ? "red" : "green"

A: There are three criteria of performance:
a) speed of computation
b) less amount of used memory
c) quicker reading and understanding code for any developer (as result it is in demand of commercial code, were big team must write down big project and recheck each other)
For quickest performance it is:
 let edgeValue: Int
 let edgeChars: String
 let edgeColor: String

 (edgeValue, edgeChars, edgeColor) = directionUp ?
       (-5, "x", "red") :
       (5, "5", "green")

For quicker usage code (reading and understand it) looks better to connect all this data into one structure:
struct Edge{
   let value: Int
   let chars: String
   let color: String
}

let edge = directionUp ?
       Edge(value: -5, chars: "x", color: "red") :
       Edge(value: 5, chars: "5", color: "green")

This structure take additional 4 bytes of memory and few ticks of processor performance for each call to any property, but it is more comfortable to work with few similar structures than to try remember of all variables in each class.
Anyway - if this values will not be changed - use let, for clearing your code and forbidding to change this value

A: Make let, not var:
let edgeValue: Int
let edgeChars: String
let edgeColor: String

if directionUp {
    edgeValue = -5
    edgeChars = "x"
    edgeColor = "red"
} else {
    edgeValue = 5
    edgeChars = "y"
    edgeColor = "green"
}

Just replace var with let in your first code snippet. You initialise edgeValue, edgeChars and edgeColor only once.


text:
Q: ng-repeat with ng-transclude inside a directive I want to create a list with custom behavior when it's content changes. I try to create a directive for this but I get a bit lost with how to combine the ng-transclude with the ng-repeat directive. Can somebody put me on track?
Html:

    <mylist items="myItem in items">
       {{myItem}}
    </mylist>

Javascript:
angular.module('myApp', [])

.controller('ctrl', function ($scope) {
  $scope.items = ['one', 'two', 'three'];
})

.directive('mylist', function () {
  return {
    restrict:'E',
    transclude: 'element',
    replace: true,
    scope: true,
    template: [
      '
',
        '

',
      '
'
    ].join(''),
    link: function (scope, element, attr) {
      var parts = attr.items.split(' in ');
      var itemPart = parts[0];
      var itemsPart = parts[1];
      scope.$watch(itemsPart, function (value) {
        scope.items = value;
      });
    }
  }
});

I've got part of this somewhat working here
EDIT:
Criteria:

*

*The template of the item must be defined in the view, not in the directive and it must have access to an item property in a child scope. Ideally I want to define this like it is done in the ng-repeat directive

*The directive must have access to the list so I can set proper watches and change things. If possible I would like to have easy access to the generated DOM items (I can also do it with element[0].querySelectorAll('ul>li') or something, It only has to work on Chrome).

*If possible I would like to reuse the logic in the ng-repeat directive because it does already do a lot of what I want. Preferably I don't want to copy the code. I just want to augment its behavior, not change it

A: Other answers unfortunately does not work with newest version of angular(I checked 1.4) so I think there is a benefit to share this jsbin I found:

var app = angular.module('app', [])
  .controller('TestCtrl', function($scope) {
    $scope.myRecords = ['foo', 'bar', 'baz'];
  });

app.directive('myDirective', function($compile) {
  var template = '

';

  return {
    scope: {
      records: '='
    },
    restrict: 'A',
    compile: function(ele) {
      var transclude = ele.html();
      ele.html('');

      return function(scope, elem) {
        var tpl = angular.element(template);
        tpl.append(transclude);

        $compile(tpl)(scope);

        elem.append(tpl);
      };
    }
  };
});

    ?: {{record}}

A: Transcluding isn't necessary because items contains what we need to render the template.  Put another way, there isn't anything inside the element -- i.e.,  <mylist>nothing new here we need to transclude</mylist>.  It seems Angular will do the $watching for us too.
.directive('mylist', function () {
  return {
    restrict:'E',
    replace: true,
    scope: true,
    template: [
      '
',
      '
{{myItem}}
',
      '
'
    ].join('')
  }
});

HTML:
<mylist></mylist>

Fiddle.
Note that creating a new scope is optional, so you could comment out this line:
//scope: true,

Update:  You could optionally create an isolate scope:
scope: { items: '='},

HTML:
<mylist items=items></mylist>

Fiddle.
Update2: based on additional info provided by Jan:

The template of the item must be defined in the view... I would like to reuse the logic in the ng-repeat directive

Okay, so lets put it all in the view, and use ng-repeat:

    {{myItem}}

it [the directive] must have access to an item property in a child scope... The directive must have access to the list so I can set proper watches and change things

Following your original fiddle, we'll use a normal child scope (i.e., the child scope will prototypically inherit from the parent scope): scope: true,.  This will ensure the directive has access to the properties defined on the controller's scope, e.g., items.

access to the generated DOM items

The directive's link function has an element argument.  So in the HTML above, element will be set to the
 element.  So we have access to all the DOM elements.  E.g., element.find('li') or element.children().  In the fiddle referenced below, I have it $watch the items array.  The $watch callback has access to element, so you have access to the generated DOM items.  The callback logs element.children() to the console.
Fiddle.
In summary, to add custom behavior to a list, just plop a directive onto a ul or ol and away you go.

A: Solved the problem myself:
I am able to do it in the compile step (jsfiddle) by adding the ng-repeat attribute when the template is compiled and feeding it the content of my attribute.
Html:

    <mylist element="myItem in items">{{myItem}}</mylist>

Javascript:
var myApp = angular.module('myApp', [])

.controller('ctrl', function ($scope) {
  $scope.items = ['one', 'two', 'three'];
})

.directive('mylist', function ($parse) {
  return {
    restrict:'E',
    transclude: 'element',
    replace: true,
    scope: true,
    template: [
      '
',
      '

',
      '
'
    ].join(''),
    compile: function (tElement, tAttrs, transclude) {
      var rpt = document.createAttribute('ng-repeat');
      rpt.nodeValue = tAttrs.element;
      tElement[0].children[0].attributes.setNamedItem(rpt);
      return function (scope, element, attr) {
        var rhs = attr.element.split(' in ')[1];
        scope.items = $parse(rhs)(scope);
        console.log(scope.items);
      }
    }
  }
});

A: An alternative way to achieve this as follows.
Index.html:

    <title>AngularJS Transclude within Repeat Within Directive</title>

    <people>Hello {{person.name}}</people>
    <button name="button" ng-click="changeRob()">Change Rob</button>

index.js:
var myApp = angular.module( 'myApp', [] );

myApp.controller( 'myController', function( $scope ) {
    $scope.people = [
        { name: 'Rob'  },
        { name: 'Alex' },
        { name: 'John' }
    ];

    $scope.changeRob = function() {
        $scope.people[0].name = 'Lowe';
    }
});

myApp.directive( 'people', function() {
    return {
        restrict: 'E',

        transclude: true,
        template: '

',
    }
});

myApp.directive( 'transcope', function() {
    return {
        link: function( $scope, $element, $attrs, controller, $transclude ) {
            if ( !$transclude ) {
                throw minErr( 'ngTransclude' )( 'orphan',
                    'Illegal use of ngTransclude directive in the template! ' +
                    'No parent directive that requires a transclusion found. ' +
                    'Element: {0}',
                    startingTag( $element ));
            }
            var innerScope = $scope.$new();

            $transclude( innerScope, function( clone ) {
                $element.empty();
                $element.append( clone );
                $element.on( '$destroy', function() {
                    innerScope.$destroy();
                });
            });
        }
    };
});

See it in action in this similar plunker. Based on this long Github issue discussion.

A: I have faced the same problem and ended up adding a little code to ng-transclude so it would allow watch and accept custom data from the using parent.

*

*this way the transcluded data have access to the grandparent scope

*and also have access to the ng-repeat data given to it.

Usage
Grandparent.js

{{ $ctrl.listName }}</div.

<my-list items="$ctrl.movies">

From context: {{ name }}

From grandparent: {{ $ctrl.listName }}

</my-list>

Parent.js (MyList)

  <cr-transclude context="item"></cr-transclude>

Code changes to ng-transclude
return function ngTranscludePostLink(
   ...
  ) {
  let context = null;
  let childScope = null;
  ...
  $scope.$watch($attrs.context, (newVal, oldVal) => {
    context = newVal;
    updateScope(childScope, context);
  });
  ...
  $transclude(ngTranscludeCloneAttachFn, null, slotName);
  ...
  function ngTranscludeCloneAttachFn(clone, transcludedScope) {
     ...
     $element.append(clone);
     childScope = transcludedScope;
     updateScope(childScope, context);
     ...
  }
  ...
  function updateScope(scope, varsHash) {
    if (!scope || !varsHash) {
      return;
    }
    angular.extend(scope, varsHash);
  }
}

Full code is at Github.
A working example can be seen in Codesandbox.


text:
Q: I need help extending the Multinomial Theorem to Polynomials I have been pondering the question, what does $f(x)$ look like if $f(x)=\left(\frac{d^{w}}{dx^{w}}f(x)\right)^n$ and $f(x)$ is a polynomial. If you're given w, then I believe that there are a limited number of n values and families of polynomials that satisfy this property.
I went through and solved for $w=1$:
$$
n=2;
f(x)=\frac{1}{4}x^2+bx+b^2=\frac{1}{4}(x+2b)^2
$$
and $w=2$:
$$
n=3;
f(x)=\frac{1}{\sqrt{216}}x^3+bx^2+2\sqrt{6}b^2x+8b^3=\frac{1}{\sqrt{216}}(x+2\sqrt{6}b)^3
$$
$$
n=2;
f(x)=\frac{1}{144}x^4+bx^3+54b^2x^2+1296b^3x+11664b^4=\frac{1}{144}(x+36b)^4
$$
(b can be any real number). I see a pattern there (with the equivalent polynomial being shifted to the left or right), but I want to generalize. I'll be using $f(x)=a_{m}x^m+a_{m-1}x^{m-1}+\cdots+a_1x+a_0$ from here on out.
$$f(x)\text{ can be represented as }\sum_{k=0}^{m}a_kx^k;\text{ and }\frac{d^w}{dx^w}f(x)=\sum_{k=w}^{m}a_k\frac{k!}{(k-w)!}x^{k-w}$$
Using the Multinomial Theorem, we can write $\left(\frac{d^w}{dx^w}f(x)\right)^n$ as
$$\sum_{i_{w}+i_{w+1}+i_{w+2}+\cdots+i_{m}=n}\frac{n!}{i_{w}!i_{w+1}!i_{w+2}!\cdots i_{m}!}\left(\prod_{k=w}^{m}\left(a_k\frac{k!}{(k-w)!}x^{k-w}\right)^{i_{k}}\right)$$
I've evaluated for $a_0$, $a_1$, $a_2$, and $a_m$, but finding other terms looks like an impossible mess. $a_2$ was already difficult enough.
I want an equivalent Multinomial Theorem that allows for me to find the coefficient for any term with a certain degree without considering every way to make that degree. Hopefully, I can more easily evaluate for w or $m-1$ and find a pattern or relations between each term.


text:
Q: C# web API POST JSON data using POSTMAN client results in always NULL in FromBody I am having a Web Api containing Model -
 public class Assessments
{
    public List<AssessmentResult> Results { get; set; }
}

public class AssessmentResult
{
    public int? AssessorId { get; set; }
    public int? AssessmentId { get; set; }
    public int? CentreId { get; set; }
    public int? BatchId { get; set; }
    public DateTime AssessmentDate { get; set; }

And Controller -
[HttpPost]
    [ActionName("SetAssessmentResults")]
    public HttpResponseMessage SetAssessmentResults([FromBody] Assessments assessments)
    {
        try
        {

            string sproc = ConfigurationManager.AppSettings["ASSESSORAPP_InsertAssessmentsStaging"];
            //_dt = Helper.ToDataTable(assessments); use this if sending list doesnt work

            Mapper.Initialize(cfg =>
            {
                //cfg.CreateMissingTypeMaps = false;
                cfg.CreateMap<AssessmentResult, AssessmentTable>().IgnoreAllNonExisting();

                //cfg.IgnoreUnmapped();
            });
            List<AssessmentTable> assessmentTable = Mapper.Map<List<AssessmentResult>, List<AssessmentTable>>(assessments.Results);
            Mapper.Configuration.AssertConfigurationIsValid();

            string isSuccess = _db.InsertAssessmentResults(sproc, assessmentTable);
            if (isSuccess.Split('$')[0].ToLower() == "success")
            {
                return Request.CreateResponse(HttpStatusCode.OK, isSuccess);
            }
            else if (isSuccess.Split('$')[0].ToLower() == "duplicate")
            {
                return Request.CreateResponse(HttpStatusCode.OK, isSuccess);
            }
            else
            {
                return Request.CreateResponse(HttpStatusCode.OK, isSuccess);
            }
        }
        catch (Exception ex)
        {
            return Request.CreateResponse(HttpStatusCode.InternalServerError, ex);
        }
    }

Client side, I am using Postman Chrome extension.
I am sending POST request with JSON data in body. However, I am not getting the JSON data in controller (assessments object always shows NULL value)
assessments object showing NULL value
In client side, I am request using PostMan Chrome extension
PostMan Client sending request
This is my JSON data :
    {
"assessment":
[{
      "AssessorId": 3,
      "AssessmentId": 123,
      "CentreId": 1,
      "BatchId": null,
      "AssessmentDate": "2016-09-30T00:00:00",

    },{
     "AssessorId": 2,
      "AssessmentId": 123,
      "CentreId": 1,
      "BatchId": null,
      "AssessmentDate": "2016-09-30T00:00:00",
    }]
    }

I have also added Content-Type : application/json
Please help me to solve this problem. Thank you !

A: In your class Assessments you name the property that contains the list of AssessmentResult "Results" but when you send the post you are naming the property "assessment" it should be "Results" (considering you have the default serializer configuration eg: no propertie name to lower camel case when serializing)
Try:
  {
     "Results":[{
                 "AssessorId": 3,
                 "AssessmentId": 123,
                 "CentreId": 1,
                 "BatchId": null,
                 "AssessmentDate": "2016-09-30T00:00:00",

               },
               {
                 "AssessorId": 2,
                 "AssessmentId": 123,
                 "CentreId": 1,
                 "BatchId": null,
                 "AssessmentDate": "2016-09-30T00:00:00",
               }]
 }

Also as a good practice you should instance the list in the constructor of your class
Eg:
public class Assessments
{
    public Assessments()
    {
         Results = new List<AssessmentResult>();
    }
    public List<AssessmentResult> Results { get; set; }
}


text:
Q: How to float an icon right for high resolution but add it after the text on a low resolution? For different resolutions my site needs to look differently, with the same html.
On the high resolution I would like a text first and an icon floating to the right of the parent container. For the low resolution the icon should be directly after the text.
Large resolution text here                                              floating icon
Might be several lines

----

small resolution Text - Icon directly following

I can only get the floating icon to be on the correct line if I place this first in the html otherwise it moves to the second line.
I've tried variations of clear, floats, absolute and relative positioning, vertical align, and css columns but it either works correctly for large resolutions or small ones, but not both.
This example works for the large resolutions:

@media (min-width: 800px) {
  .right-icon {
    float: right;
  }
}

Icon

Text

A: One way to do this is flex layout combined with mediaquery.

.container {
  display: flex;
}

@media (min-width: 800px) {
  .container {
    justify-content: space-between;
  }
}

Icon

Text


text:
Q: Why do node_modules keep disappearing from docker after build? I'm mimicking the setup found here https://github.com/mjhea0/node-docker-workflow. Using docker-compose to link 2 docker containers (node, redis).
Here's the circle ci file:
machine:
  services:
    - docker

dependencies:
  override:
    - sudo pip install -U docker-compose

test:
  override:
    - docker-compose run -d --no-deps node
    - cd node; npm test

And here is my node Dockerfile:
FROM dockerfile/nodejs

RUN mkdir /src

RUN npm install nodemon -g

WORKDIR /src
ADD . /src
RUN npm install

EXPOSE 3000

CMD npm start

The tests are constantly failing because chai can't be found. This is due to node_modules disappearing once the build is complete.
Literally between these 2 steps in the circle.yml file node_modules are installed by npm install, and then they're gone by the time the npm test command is run.
test:
  override:
    - docker-compose run -d --no-deps node
    - cd node; npm test

I can't figure out why this is happening. As i'm just starting out with Docker, can someone please (in laymens terms) explain fairly thoroughly what is wrong with the repo i'm using above, and how to solve it.
Thanks!

A: Well, it turns out it was something very, very simple, and probably rather silly/obvious.
The tests aren't being run inside the container.
docker-compose run -d --no-deps node
This line runs the container in detached mode. Which means when the next command runs, it's running outside the container.
To solve this, simply remove the -d, so the next command runs inside the container.
docker-compose run --no-deps node
Simple.


text:
Q: How to execute a code only for the blog post page on my functions.php file I'm trying to execute a simple code via my functions.php file (child theme) on my wordpress website.
The code should return "yes blog" when I open the blog post page, and return "no blog" for any other page. But it only returns "no blog" whatever the page.
I tried different conditionnal tags :

*

*is_home()

*is_front_page() && is_home()

*!is_front_page() && is_home()

*is_page_template()

*is_page('')

It always returns "no blog"
I have a default front page and a default blog page on my website.
Here is my code:

   if(is_home()){
    echo '<script language="javascript">';
    echo 'alert("yes blog")';
    echo '</script>';
        } else {
        echo '<script language="javascript">';
        echo 'alert("no blog")';
        echo '</script>';
            }

A: You could replace the if condition with something like:
if($_SERVER["REQUEST_URI"] == "/blog")

A: The "blog" page is a page and has an ID, so you can write something like:
if (is_page(345)) {
   // content/code for page whose ID is 345
} else {
  // content/code for pages whose ID is not 345
}

A: Checking if you're on the blog page by looking at the request URI or the page ID is a bad thing since it's hard coded.
You should use these conditions :
if ( is_front_page() && is_home() ) {
  // Default homepage
} elseif ( is_front_page() ) {
  // static homepage
} elseif ( is_home() ) {
  // blog page
} else {
  //everyting else
}

Make sure you have registered a front page (for is_front_page() cond.) or a blog page (is_home() cond.) in your Wordpress permalinks options
This thread will maybe help : https://wordpress.stackexchange.com/questions/107141/check-if-current-page-is-the-blog-page


text:
Q: Using public and private methods inside their class in Perl 6 If I have a public method, I can call it inside its class using both $.name and self.name:
class TEST {
  has Int $.a;

  method b($x) {
    return $!a * $x;
  }

  method c($y) {
    return self.b($y) * 3; # or $.b($y)
  }
}

my $m = TEST.new(a => 10);
say $m.c(2); # 60

But if I make b a private method, I only can call it with self!b, not $!b, otherwise I get the following error message:
Attribute $!b not declared in class TEST

What's behind this rule? What are the rules of calling a method inside its own class?

A: An attribute can always be referred to as $!foo in a class.  If you do that, than the code will be generated to directly access the attribute itself, and any classes subclassing your class will not be able to change this behaviour.
If you use has $.foo in the declaration of a class, it means that a public accessor (and if you add is rw it can also function as a mutator).
When you use $.foo in your code otherwise, it is exactly the same as $( self.foo ).  This means that it will call the method foo on self, and itemize the return value (make it a single "thing" if it wasn't yet).  This will go wrong if you defined your attribute with $!foo and you did not supply a method foo yourself.
This goes even further: $.bar really means self.bar: you only need to have a method existing by the name bar, which may not be related to any attribute at all.
If you define a private method !baz, the ! just indicates the privacy of the method, which means you need to call it indeed as self!baz.  There is no short syntax for it.
Personally I dislike the fact that you can say $.zippo even if zippo is not an attribute.  But I'm afraid that ship has sailed.  But this behaviour is now causing you confusion :-(
So what's behind the rule for not having a short syntax for calling a private method?  Not sure, I guess really that $!foo was already taken to mean direct access to the attribute, and provide you with a compile time error if the attribute doesn't exist.
Hope this answers your question!


text:
Q: convert object to map when object contains another class's object in flutter I want to convert object to map as key, value pair when an object contains another class's object...so here I don't know how to make a method named toMap
here is my class structure
class Category
{
  String title;
  String iconurl;
  Category({required this.title, required this.iconurl});

  Map<String,dynamic> toMap()
  {
    return {
      'title':title,
      'iconurl':iconurl,
    };
  }
}

class Transaction
{
  String id;
  Category category;
  String paymentmode;
  bool isexpense;
  DateTime date;
  String note;
  double amount;
  Transaction({this.amount=0.00,required this.id, required this.category,required this.paymentmode, this.isexpense=true,required this.date,this.note='No Note'});

  Map<String,dynamic> tomap()
  {
    //what is the code for converting object to map
    //confused as object containing another class's object...
    return {

    };
  }
}

A: You can use https://app.quicktype.io to create classes from json
// To parse this JSON data, do
//
//     final welcome = welcomeFromJson(jsonString);

import 'package:meta/meta.dart';
import 'dart:convert';

Welcome welcomeFromJson(String str) => Welcome.fromJson(json.decode(str));

String welcomeToJson(Welcome data) => json.encode(data.toJson());

class Welcome {
    Welcome({
        @required this.id,
        @required this.category,
        @required this.paymentmode,
        @required this.isexpense,
        @required this.date,
        @required this.note,
        @required this.amount,
    });

    final String id;
    final Category category;
    final String paymentmode;
    final bool isexpense;
    final String date;
    final String note;
    final int amount;

    factory Welcome.fromJson(Map<String, dynamic> json) => Welcome(
        id: json["id"],
        category: Category.fromJson(json["category"]),
        paymentmode: json["paymentmode"],
        isexpense: json["isexpense"],
        date: json["date"],
        note: json["note"],
        amount: json["amount"],
    );

    Map<String, dynamic> toJson() => {
        "id": id,
        "category": category.toJson(),
        "paymentmode": paymentmode,
        "isexpense": isexpense,
        "date": date,
        "note": note,
        "amount": amount,
    };
}

class Category {
    Category({
        @required this.title,
        @required this.iconurl,
    });

    final String title;
    final String iconurl;

    factory Category.fromJson(Map<String, dynamic> json) => Category(
        title: json["title"],
        iconurl: json["iconurl"],
    );

    Map<String, dynamic> toJson() => {
        "title": title,
        "iconurl": iconurl,
    };
}


text:
Q: why &(arr+1) does not compile I wrote the next code:
int main()
{
    int arr[] = {1,2,3,4,5};

    std::cout <<"&arr: " <<&arr<<"\narr&:"<<&(arr+1);

    return 0;
}

why is &arr compile and gives the address of arr at the position 0,
and &(arr+1) doesn't compile?
(I have expected it will return the address of arr at the position 1)

A: &arr is not an address "at a position", but the address of the entire array. You can see this via the difference in types:
&arr is the address of the array and has type ARR*, where ARR is the type int[5]. When combined, this type looks like int(*)[5].
&arr[0] is the address of the first element. It has type int*.
Now the actual values are the same because the array object starts at its first element, but it helps to not focus on that when trying to understand arrays vs. pointers.
When you say arr + 1, what's actually happening is that arr is being silently converted from an array (int[5]) to a pointer (int*) to the first element of the array. You then advance this pointer by one int. This results in an int* pointing to the second element of the array. This is the result you wanted to print and is equivalent to &arr[1].
Remember that & takes the address of an object. It's meaningless to take the address of a temporary like the pointer arr + 1. &(arr + 1) is equivalent to &(&arr[1]). They both try to take the address of something that logically doesn't have an address of its own. Remember that a pointer can store an address as its value, but the only reason & comes into play is because you can use it to obtain the address of an object, which can then be stored into a pointer. &ptr is the address of ptr itself, not the value stored in ptr.

In short, be consistent with what you want. Both of the following will print the address of the first element and the address of the second element. Both print two int*s since your intent is about individual elements, not the whole array:
std::cout << "First: " << &arr[0] << "\nSecond: " << &arr[1];
std::cout << "First: " << arr << "\nSecond: " << (arr + 1);


text:
Q: rails - validate product ordered has the available quantity I have two related validations on separate models.  I can validate one way but not another.  The post validation works: if I try to change the quantity available as the seller, and people have already ordered some of it, it (correctly) won't let me change the quantity below the amount ordered already.
The order validation does not work: if I try changing the order amount to more than is available, it lets me.  It checks only the current sum (I guess before the save), and does not notice the buyer trying to sneak out more than what's available.  When I try and change the order back to less than what is available, it won't let me, checking the current sum ordered (before save).
I also tried validating the quantity of the order + the remaining available stock (available -sum ordered), but have the same problem.
How would I get the validation to check what the quantity would be after the save, and then not save it should the value be invalid?  It would have to work also for editing an order
class Post < ActiveRecord::Base
    belongs_to :product
    belongs_to :event
    has_many :orders, :dependent => :destroy

    attr_accessible :quantity, :deadline, :product_id, :event_id

    validate :quantity_gt_ordered

    def quantity_gt_ordered
       self.errors.add(:quantity, " - People have already ordered more than this") unless self.quantity >= self.sum_orders
    end

    def sum_orders
        self.orders.sum(:quantity)
    end

class Order < ActiveRecord::Base
      belongs_to :user
      belongs_to :post

    attr_accessible :order_price, :post_id, :user_id, :quantity

    validate :quantity_is_available

    def quantity_is_available
       self.errors.add(:quantity, " - Please order only what's available") unless self.sum_post_orders <= self.post.quantity
    end

    def sum_post_orders
      Order.where(:post => self.post).sum(:quantity)
    end

A: You should just be able to compare to the available quantity minus the ordered quantity:
available_quantity = self.post.quantity - self.sum_post_order
if quantity > available_quantity
  self.errors.add(:quantity, " - Please order only what's available")
end

And also make sure your sum_post_orders doesn't include the current order:
Order.where("id != ?", self.id).where(:post => self.post).sum(:quantity)


text:
Q: How to use a chef helper library from another chef cookbook in a ruby_block AWS Opsworks: Chef version 11.10, Berkshelf version 3.2.0.
I can't figure out how to use a helper library from cookbook A in a ruby_block in cookbook B.
I found a post discussing how to include a method in a ruby_block and another discussing how to share libraries across cookbooks but I can't get both working at the same time.
cookbookA/libraries/helpers.rb
module libraryA
    module Helpers
        def log(output)
            Chef::Log.info("#{cookbook_name}:#{recipe_name}: #output}")
        end
    end
end

cookbookB/metadata.rb
depends 'cookbookA'

The following setup.rb works.
cookbookB/recipes/setup.rb
 ::Chef::Recipe.send(:include, libraryA::Helpers)
 log("this is a log")

However, when I use the log function in a ruby block, it fails. The following setup.rb does not work:
cookbookB/recipes/setup.rb
 ::Chef::Recipe.send(:include, libraryA::Helpers)
 ruby_block "logging-function" do
      block do
           log("this is a log")
      end
 end

P.S.: I have also tried using ::Chef::Resource.send(:include,
libraryA::Helpers)
Updated code block:
::Chef::Recipe.send(:include, libraryA::Helpers)
ruby_block "logging-test" do
    block do
        ::Chef::Recipe.send(:include, libraryA::Helpers)
        ::libraryA::Helpers.ttlog("message")
    end
end

Received error: NoMethodError - undefined method ttlog for libraryA::Helpers:Module
Updated helpers
cookbookA/libraries/helpers.rb
def log(output)
    Chef::Log.info("#{cookbook_name}:#{recipe_name}: #output}")
end

P.S: Removed the modules structure

A: I think ruby_block runs in other context, under other object.
You can try to include that library into provider, but I can't guarantee it would work.
::Chef::Provider::RubyBlock.send(:include, libraryA::Helpers)
ps. Resource does have definition and list of parameters, but code is executed from Provider.


text:
Q: Member variable initialization with non-default constructor gives error
robot.h:11:20: error: expected identifier before numeric constant
     Queue SQ(10);

struct Robot
{
  string m_name; //robot name
  Queue<string> SQ(10); //queue of services
  int m_timer; //time til robot is done
  string m_lastService; //most recent service
};

I don't understand why I'm getting an error on this. When I take away the (10) it used the default constructor and works fine. Here is the Queue class.
template <typename T>
class Queue : public AbstractQueue<T>
{
  private:
    T* m_array;
    int m_front;
    int m_back;
    int m_capacity;
    int m_size;
  public:
    Queue();
    Queue(int max);
    void setMax(int max);
    bool isEmpty() const;
    const T& front() const throw (Oops);
    const T& back() const throw (Oops);
    void enqueue(const T& x);
    void dequeue();
    void clear();
    ~Queue();
};

I used another declaration of the Queue class and it worked in main, but for some reason it won't work in the struct, here is what I declared in main
Queue<Robot> R(10);

A: You can't specify the non-default constructor used on member variable initialization like this.
You could provide a constructor with member initializer list to specify the constructor of Queue to be used.
struct Robot
{
  string m_name; //robot name
  Queue<string> SQ(); //queue of services
  int m_timer; //time til robot is done
  string m_lastService; //most recent service
  Robot() : SQ(10) {}
};

Or use default member initializer (since c++11):
Queue<string> SQ{10};


text:
Q: rotating images inside of div separately new to css here, I have bunch of images that I want to rotate/spin them.
.images_div{
  position: absolute;
  top: 1%;
  left: -2%;
  width: 250px;
  height: 200px;
  margin:-60px 0 0 -60px;
  -webkit-animation:spin 150s linear infinite;
  -moz-animation:spin 150s linear infinite;
  animation:spin 150s linear infinite;
}
@-moz-keyframes spin { 100% { -moz-transform: rotate(360deg); } }
@-webkit-keyframes spin { 100% { -webkit-transform: rotate(360deg); } }
@keyframes spin { 100% { -webkit-transform: rotate(360deg); transform:rotate(360deg); } }

I use the code above for spin the div that includes the images.
the problem is well it spins the div not the images inside of it, but I want the images not to move and each of them just spin separately.
I'm guess using the code above for each one of the images is not the right way to do this? so How should I do this?
Thanks,

A: Add the following styles to img tags inside the div
.images_div img {
  width: 50px;
  height: 50px;
  margin: 20px;
  -webkit-animation: spin 150s linear infinite;
  -moz-animation: spin 150s linear infinite;
  animation: spin 150s linear infinite;
}

.images_div img {
  width: 50px;
  height: 50px;
  margin: 20px;
  -webkit-animation: spin 150s linear infinite;
  -moz-animation: spin 150s linear infinite;
  animation: spin 150s linear infinite;
}

@-moz-keyframes spin {
  100% {
    -moz-transform: rotate(360deg);
  }
}

@-webkit-keyframes spin {
  100% {
    -webkit-transform: rotate(360deg);
  }
}

@keyframes spin {
  100% {
    -webkit-transform: rotate(360deg);
    transform: rotate(360deg);
  }
}


text:
Q: Implicit use of symbol from a static library I come to submit a problem I have while trying to import symbols from static library implicitly.
Let me set up the problem with a peace of simplified code:
I have 3 projects:
    - a static plugin handler project that defines a registry class, it is linked in the other two projects
    - a static plugin project
    - a final project that has a plugin handler and "load statically" the plugin.
first, the static plugin handler project:
struct PluginType
{
    virtual void doMyStuff() = 0 ;
};

typedef PluginType* (*PluginCreator)();

struct Registry
{
      std::map<std::string, PluginCreator> _item_list;
      static Registry& instance()
      {
            static Registry singleton;
            return singleton;
      }
      static PluginType* create(std::string const& name)
      {
      // call the creator function that returns an PluginType*
        return instance()[name]();
      }
};

struct RecordInRegistry
{
     RecordInRegistry(std::string const& key, PluginCreator new_item_creator)
     {
          Registry::instance()._item_list[key] = new_item_creator;
     }
};

Now, a static plugin project
struct ADerivedItem : public PluginType
{
    virtual void doMyStuff() override
    {
        //some really interesting stuffs
    }
    static PluginType* create() { return new ADerivedItem() ; }
}

export "C" const RecordInRegistry i_record_derived_item_class("derived_item", &ADerivedItem::create);

Then, the final project where i use the plugin. This project links the two other porjects !
int main()
{
    PluginType*  my_instance = Registry::create("derived_item");

    return 0;
}

What I hope is that I will be able to register my static plugin just by linking the static library plugin
to the project.
It almost worked ! The only problem I got is that the symbol "i_record_derived_item_class" from the static
plugin is not explicitly used in the final project, thus this symbol is not imported from the static plugin lib !
I work on visual studio, i found a simple fix that consists in forcing the symbol import, something like
/INCLUDE:i_record_derived_item_class, and everything works fine.
I want to know if you see a work around to this, what I would like is to be able to add this kind of static
plung just by linking it, without having to add anything more than /LINK:myStaticPlugin.lib
Any idea ?
Moreover it would be really nice to avoid MSVC-specific solution.
Thanks in advance !

A: The problem is that symbols in library are used only when required. Draft n4659 says at 5.2 Phases of translation [lex.phases]:

*All external entity references are resolved. Library components are linked to satisfy external references
  to entities not defined in the current translation.

As your current source has no external references to i_record_derived_item_class, nor to the class ADerivedItem, nothing will be loaded by default from the plugin project. Worse, even the plugin handler module has no reference either, so you need to declare an undefined reference to the build system itself, be it MSVC or anything else.
Alternatively, you could link a minimal translation unit (means a .cpp or .o file) containing an external reference to i_record_derived_item_class, to force the resolution from a library.


text:
Q: Set all selected media gallery types to default store value using SOAP Api I want all images of a product to use the default small_image, thumbnail and image again for every storeview using the SOAP api.
So far I've tried to set the 'types' using catalog_product_attribute_media.update to null but with no success.
            foreach($storeviews as $storeviewId) {
                $result = $client->call(
                    $session,
                    'catalog_product_attribute_media.list',
                    $productId,
                    $storeviewId
                );

                foreach($result as $image) {
                    $client->call(
                        $session,
                        'catalog_product_attribute_media.update',
                        [
                            $productId,
                            $image['file'],
                            [
                                'types' => null,
                            ]
                        ],
                        $storeviewId
                    );
                }
            }

A: You have an error in your API call, the parameter type needs to be an array in order to be processed correctly. If you change your code and use an empty array instead of null you should achieve what you want.
Anyway it's not necessary to make update calls for images which do not have any image type set. So please change the code for the second foreach loop as follows and give it a try:
foreach($result as $image) {
    if (count($image['types']) > 0){
        $client->call(
            $session,
            'catalog_product_attribute_media.update',
            [
                $productId,
                $image['file'],
                [
                   'types' => []
                ]
            ],
            $storeviewId
        );
    }
}


text:
Q: Swift 3 Core Data - How to save context synchronously? I need to import data into one enity, and then another entity that has a relationship with the first. The problem is that it crashes on the second entity because the the save is not complete on the first. How should I best deal with this in Swift 3 / Xcode 8 / IOS 10?
self.viewContext.save()

I need to make sure the save is complete before importing the second entity.

A: I figured out that it was saving synchronously, but I had to save after each row, otherwise it was just not working.


text:
Q: Django date format swap I have a problem with date format. I'm using 'Y-m-d' format. When I enter the format the next time I want to edit, swaps month and day. Reading the doc I see input_format parameter, so I force it input_formats='%Y-%m-%d'. And I get an error that the date is not valid.
forms.py:
date_start = forms.DateField(input_formats='%Y-%m-%d',widget=forms.DateInput(format = '%Y-%m-%d',attrs={'class':'datepicker form-control'}))

template:

    {{ form.date_start.label }}

    {{ form.date_start }}

models.py:
date_start = models.DateField()

SOLVED:
No need to force date_format in django. The problem was the picker
forms.py
date_start = forms.DateField(widget=forms.DateInput(attrs={'class':'datepicker form-control'}))

template

A: In your form your date format is %Y-%m-%d => yyyy-mm-dd which is not equal to the format you set within your date picker script!


text:
Q: product list filtering by checkboxes without Javascript enabled I am using YII and I have a checkbox filter that filters Product by Brands.
This is my filter HTML:

        <input value="1" id="chb_1" class="brand-filter-chb" type="checkbox" name="brands[]">
        Brand Name 1

        <input value="2" id="chb_2" class="brand-filter-chb" type="checkbox" name="brands[]">
        BRAND Name 2

    etc.

When user does a click on checkbox then jquery do YII fn.yiiListView.update. This is something like ajax call that updates data I am filtering. Ajax call is made to controller/action (in my case controller is Product and action is List) and parameter $brands is passed to controller/action.
This is my filter javascript (Jquery):
$('.brand-filter-chb').live('click', function(){
    brands = $('#filter-form').serialize();     //brand names are serialized
    $.fn.yiiListView.update(  //this updates product list by brand names
        'product-list',   //id of product list table
        {data: brands}   //serialized data send to controller/action by ajax call
    );
});

This allows to filter Product list by brands. Use checks Brand Name checkbox and list is filtered. Also user can check more than one Brand Name and everything works fine.
However, it doesn't work without Javascript.
I wondering what is the best solution to allow the same or very similar user experience without javascript.
For example, it would be also acceptable if use could filter Product list only by one Brand if javascript is not enabled.

A: What i'd suggest is to enclose your filter HTML within a form and set the action of the form to the same action you used for your AJAX filter.
If you're considering SEO, then your form should submit using the get method and then you can use Yii's request object:
Yii::app()->request->isPostRequest
to determine if it's the AJAX request that's being processed or the Non-script version.
You can enclose the submit button for the form filter within a couple of  tags.
As for knowing what checkboxes were selected before reloading a page, I'm not entirely sure it's possible without javascript.

A: If you are not wanting to use javascript, what you could do is create a
Please enable javascript
or have the page refresh after a check box is selected and do the showing / hiding of the elements with your php.


text:
Q: Errors with Ruby and File.open Having problems with a Ruby script that uses File.Open
Here is the code that I am speaking of...
f = File.open(Socket.gethostname().gsub!(/[[:space:].]/,"")+".log","a")
The issue is the + inside of .open, it is returning a error message saying its a undefined method.
Anyone able to help?
Edit:
Here is some code from the class which is causing the problem.
Not sure if this will help though.
def logExecution()
  f = File.open(Socket.gethostname().gsub!(/[[:space:].]/,"")+".log","a")
  f.puts(" [" + Time.new().to_s() + "] " +\
         File.basename($0) + " " + $*.join(" "))
  f.close
end

A: What is the error message you're getting:     NoMethodError: undefined method+' for nil:NilClass` ?
If yes, then Socket.gethostname().gsub!(/[[:space:].]/,"") is returning nil
How do you create your Socket ? You could try with a fully qualified domain name, i.e. "myhost.mydomain.com" instead of "myhost".
What name should your log file have ?

A: First of all, there's no really compelling reason to strip dots from hostnames.  "www.example.com.log" is a better filename than "wwwexamplecom.log".  So my recommendation would be to use this:
def log_execution
  hostname = (Socket.gethostname() || "localhost")
  File.open(hostname + ".log", "a") do |f|
    f.puts(
      " [" + Time.new.to_s + "] " +
      File.basename($0) + " " + $*.join(" ")
    )
  end
end

But if you really must, then use this:
def log_execution
  hostname = (Socket.gethostname() || "localhost")
  File.open(hostname.gsub(".", "") + ".log", "a") do |f|
    f.puts(
      " [" + Time.new.to_s + "] " +
      File.basename($0) + " " + $*.join(" ")
    )
  end
end

Essentially, this block of code just logs the name of the command being run and the command line arguments used to invoke it.  Also note, I renamed and reformatted the method to use standard Ruby coding style.  The original was really awful.

A: There is more than the ruby code style that you can improve:

*

*use gethostbyname, and rescue to a default

*open the file using a block, ensures that if something throws, the file is closed

The result would be:
require 'socket'

def log_execution()
  logname = Socket.gethostbyname(Socket.gethostname).first rescue "localhost"
  File.open("#{logname}.log", 'a') do |f|
    f.puts(" [" + Time.new().to_s() + "] " + File.basename($0) + " " + $*.join(" "))
  end
end

And then you can improve further, by not reinventing the stdlib:
require 'socket'
require 'logger'

# do only once in your program
logname = Socket.gethostbyname(Socket.gethostname).first rescue "localhost"
log = Logger.new(logname)
log.level = Logger::WARN

Then just log using the standard api:
log.info("hello!")
log.warn("message!")

If you don't like the format which looks like:
W, [2009-12-05T03:05:48.764552 #22759]  WARN -- : message!

You can use log4r, which is api compatible but has more options...


text:
Q: how to install python-elementtree on CentOS 6.5? How to install python-elementtree on CentOS 6.5 using yum? I need it for s3cmd, but their documentation page doesn't explain it.

A: It's necessary to add EPEL repo first, as explained here:
wget http://dl.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm
sudo rpm -Uvh epel-release-6*.rpm

Then, just run
sudo yum install s3cmd

Works for me.


text:
Q: Windows hangs during (or after) execution of Java code generating many images I am developing a code which sometimes has to generate a lot of images. The program works perfectly fine when I have relatively small number of images to generate, however when I have to generate tens of thousands of images something strange could happen.
At some random point Windows appears to hung during execution of the code for up to few minutes. Task manager claims that Java application uses 0% of processor at that time. In fact every application that tries to use a resource from hard drive hangs, but applications that are already opened and don't require access to the hard drive seems to work.
What is more strange this behavior could happen even few seconds/minutes after my program is finished. But sometimes it doesn't happen at all.
Here is the simplified example:
public static void main(String[] args) {
    try {
        for (int i = 1; i <= 100; i++) {
            String dirName = "tmp/" + i + "/";
            File dir = new File(dirName);
            dir.mkdirs();
            //put only 200 file into one directory
            for (int j = 0; j < 200; j++) {
                drawImage(dirName, j);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

private static void drawImage(String dirName, int j)
                             throws FileNotFoundException, IOException {
    BufferedImage bi = new BufferedImage(512, 512, BufferedImage.TYPE_INT_ARGB);
    Graphics2D graphics = bi.createGraphics();

    //draw something on the image
    for (int k = 0; k < 10; k++)
        graphics.drawLine(k, 0, k*2, 512);
    BufferedImage tmpBI=new BufferedImage(512, 512, BufferedImage.TYPE_INT_ARGB);
    Graphics2D tmpGraphics = tmpBI.createGraphics();
    tmpGraphics.drawImage(bi, 0, 0, 512, 512, 0, 0, 512, 512, null);

    //write image to png
    FileOutputStream fos;
    fos = new FileOutputStream(new File(dirName + "img" + j + ".PNG"));
    ImageIO.write(tmpBI, "PNG", fos);
    fos.close();
}

My first guess is that there are some problems with file handlers in OS or that my Java code improperly handles files.
The second guess is that garbage collector does some magic things that I don't understand.
But to be honest I have no idea how to find out what the real problem is and how to fix it.
I run the code on Windows 7 64bit and jdk1.7 64-bit with NTFS file system.

UPDATE
Few responses proposed some workarounds. I tested all of them with the same effect:

*

*change the output directory to USB memory stick

*additional thread for computations

*single ZIP file as the output stream for all files

The last try suprised me. I expected that in this case it wouldn't hang. So, I performed another test and instead of writing to file I used NullOutputStream. The result was the same...
My conclusion: either there is something wrong in swing library (very unprobable) or maybe there is something wrong with my computer/OS. I will check it on other computers/OS. If the problem persists I will get back to it.

A: The code you write access some kernell functions.
The open and close functions for OutputStream are partially done in native, so is createGraphics().
When accessing native functions, keep in mind that they will have their own synchronization implemented.
I believe you are in the scenario where the quantity of information sent to the native thread comes at a much higher pace then the native thread writes to disk (when you think about it, RAM memory access is way quicker then HDD memory).
Even if your Java machine quits, the "tasks" were already given to the native thread to write.
That's probably why all HDD operations are getting hanged.
Try adding a Thread Sleep to your thread in order to put the Java thread in a lower priority and see if this helps.
As a general rule of thumb, file creation is a very expensive operation.20000 files is hard to even be listed in a folder :).

A: My feeling is that you should invoke the drawings on the UI thread, because you make use of awt.Graphics and BufferedImage. These are UI specific components and you always want to make UI operations on the UI thread.
Try somethig like:
 EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    // do your graphics related operations here
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

A: Try going multithreaded, so you don't use up your main thread. I guess this code is originally ran in a swing form other than console, if you do massive operations on the main thread the program won't redraw until the operation is over.
public static void main(String[] args) {
     Thread operation = new Thread(new Runnable(ThreadOperation));
     operation.start();
}

public static void ThreadOperation() {
    try {
        for (int i = 1; i <= 100; i++) {
            String dirName = "tmp/" + i + "/";
            File dir = new File(dirName);
            dir.mkdirs();
            //put only 200 file into one directory
            for (int j = 0; j < 200; j++) {
                drawImage(dirName, j);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Also you may track the progress with a taskbar with a little more coding.
Now, you should really expect other programs to hang while your program saves a massive amount of data into the disk, since hard disks aren't as fast as your processor can be. Unless (or even if) you have an SSD HD you will have this issue.
Other programs hanging while your process writes your data, only means they're trying to write data into the disk using their main thread and won't redraw until they finish writing their data, then windows thinks: Wait this guy isn't redrawing... must be dead.
PS: This code might be wrong somewhere, i've been coding way too much in c# lately.


text:
Q: IOS 5 - UIWebView duplicating requests to Rails server I have a IOS 5 application that uses a Webview which shows some HTML received from the server.
The HTML has a form and a submit button.
The backend is a RoR 3 server.
When I click the submit button it is sending two duplicate requests to the server.
If I test the same HTML in a browser it does not send duplicate requests.
Any ideas?  It is inserting two records in the DB. I want a good solution , not an unique index in the DB.
The HTML code of the page is very simple:

    <form accept-charset="UTF-8"     action="http://localhost:3000/questions/actions/sendQuestion" method="get">

            <input name="utf8" type="hidden" value="✓" />

                    0

                    Question 1

                    <input id="userQuestion" name="userQuestion" type="text" />

                    <input name="commit" type="submit" value="Send" />

   </form>

It is generated on the server and sent to the App via REST/Json, then setted to the webview using [webView loadHTMLString:htmlQuestions baseURL: nil];
Thanks


text:
Q: How to continuously populate a Redshift cluster from AWS Aurora (not a sync) I have a number of MySql databases (OLTP) running on an AWS Aurora cluster.  I also have a Redshift cluster that will be used for OLAP.  The goal is to replicate inserts and changes from Aurora to Redshift, but not deletes.  Redshift in this case will be an ever-growing data repository, while the Aurora databases will have records created, modified and destroyed — Redshift records should never be destroyed (at least, not as part of this replication mechanism).
I was looking at DMS, but it appears that DMS doesn't have the granularity to exclude deletes from the replication.  What is the simplest and most effective way of setting up the environment I need?  I'm open to third-party solutions, as well, as long as they work within AWS.
Currently have DMS continuous sync set up.

A: You could consider using DMS to replicate to S3 instead of Redshift, then use Redshift Spectrum (or Athena) against that S3 data.
S3 as a DMS target is append only, so you never lose anything.
see
https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Target.S3.html
and
https://aws.amazon.com/blogs/database/replicate-data-from-amazon-aurora-to-amazon-s3-with-aws-database-migration-service/
That way, things get a bit more complex and you may need some ETL to process that data (depending on your needs)
You will still get the deletes coming through with a record type of "D", but you can ignore or process these depending on your needs.

A: A simple and effective way to capture Insert and Updates from Aurora to Redshift may be to use below approach:
Aurora Trigger -> Lambda -> Firehose -> S3 -> RedShift
Below AWS blog-post eases this implementation and look almost similar to your use-case.
It provides sample code also to get the changes from Aurora table to S3 through AWS Lambda and Firehose. In Firehose, you may setup the destination as Redshift, which will copy over data from S3 seemlessly into Redshift.
Capturing Data Changes in Amazon Aurora Using AWS Lambda
AWS Firehose Destinations


text:
Q: Function with parameters does not run inside Javascript AddEventListener In NuxtJS I am trying to run a function with two parameters when an element is clicked with an AddEventListener.
async handleSubmit(recipe, userRating) {some code...}

setup(recipe) {
  document.querySelectorAll('.recipe-rating > .star').forEach(function(el) {
    el.addEventListener('click', function(el) {
        const userRating = el.currentTarget.getAttribute('data-rating');
        this.handleSubmit(recipe, userRating);
    }, false);
  });
...more code...
}

All of the code is within methods: {}, and I get the following error when clicking.
Uncaught TypeError: this.handleSubmit is not a function at SVGSVGElement.eval

How can I fix the problem, and what is the problem with my code?

A: On way around this problem is to use Vue.js with the HTML element instead of trough a .js file. With v-on:click (se Vue docs) we can run a function when the user clicks the HTML element.
<svg v-for="(el, i) in 5" :key="i" :data-rating="el" @click="handleSubmit(recipe, el)">
  <polygon />
</svg>

Note: v-on:click changes to @click with ESLint.


text:
Q: Approach for IT Support assistance Let's say that you are a company that gives IT Support. Your client contact you to have a price quotation to give IT Support for the following areas: Network (Wifi included) Servers Storage Cloud services
In order to have an idea, which steps would you follow to understand what's the impact of the work?
As first, I believe you need to know what's the number and the status of the assets you need to give assistance to. This implies an inventory of the hardware, software, license and warranty status, from 10000ft view.
Do you have any experience on how to conduct this analysis? Thanks.
.: Francesco

A: Yeah, bringing on a new support customer should involve an assessment of what they have and some stuff about what the customer is, and does. Asset counts matter at certain scales, as does user count, and site count.
You should also detail what's in-scope and out-of-scope (or extra cost) for the support contract.
It sounds like you're trying to start a Managed Service Provider company? I feel like you should already have some ideas about these sorts of things. If your business plan is "I will ask strangers on the internet to help make my pricing and engagement strategy, for free", I'm worried you're not going to be successful.
And this question is probably out of scope for this site, and certainly way too large to answer generically.


text:
Q: How did Sauron not notice Gandalf sneaking about in Dol Guldur? Maia are said to sense each other's presence. I know Gandalf was in disguise but it just seems that he got into Dol Guldur then the dungeons then escaped a bit too easy. It might be possible that Sauron knew Gandalf had entered Dol Guldur but wasn't powerful enough to confront him yet.
So how did Gandalf accomplish such a feat without getting noticed?

A: Whether or not Maiar can sense each other's presence is immaterial; even if they could, Sauron would not be able to sense Gandalf.
From the Istari material in Unfinished Tales we read:

...their emissaries were forbidden to reveal themselves in forms of majesty...

And:

...his joy, and his swift wrath, were veiled in garments grey as ash, so that only those that knew him well glimpsed the flame that was within.

And:

...being sent back from death for a brief while was clothed then in white, and became a radiant flame (yet veiled still save in great need).

It should therefore be obvious that Gandalf's "angelic presence" (for want of a better term) was concealed, and it should likewise be obvious that this is as a result of the nature of the Istari.
The Istari, of course, are not Maiar as they would be in Valinor, but are instead incarnated in real Mannish bodies (hence the fact that they could be killed), and it's crucial to understand this difference.
And so hence the fact that Gandalf would not be detected (even if such detection were possible).


text:
Q: change element based on time I'm trying to change this element based on time: text
I found this snippet, but what do I change/add so that it effects the h1?
var myDate = new Date();

/* hour is before noon */
if ( myDate.getHours() < 12 ) {
    document.write("Good Morning!");
}

/* Hour is from noon to 5pm (actually to 5:59 pm) */
else if ( myDate.getHours() >= 12 && myDate.getHours() <= 17 ) {
    document.write("Good Afternoon!");
}

/* the hour is after 5pm, so it is between 6pm and midnight */
else if ( myDate.getHours() > 17 && myDate.getHours() <= 24 ) {
    document.write("Good Evening!");
}

/* the hour is not between 0 and 24, so something is wrong */
else {
    document.write("I'm not sure what time it is!");
}

thanks in advance!

A: You need to have one h1 tag on your page, and you can give 'id' attribute and change the contents according to the current time: Below code may help you

var myDate = new Date();   /* hour is before noon */ if (
myDate.getHours() < 12 )  {
  document.getElementById('greeting').innerHTML ="Good Morning!"; }
else if ( myDate.getHours() >= 12 && myDate.getHours() <= 17 )
 {     document.getElementById('greeting').innerHTML ="Good Afternoon!"; }
else if ( myDate.getHours() > 17 && myDate.getHours() <= 24 )
  {     document.getElementById('greeting').innerHTML= "Good Evening!"; }
 else
  {     document.getElementById('greeting').innerHTML="I'm not sure what time it is!"; }

A: You can change the document.write(...) to document.getElementsByTagName('h1')[0].write(...)
This would write to the first h1 tag in your webpage

A: Using JQuery:
var myDate = new Date();
var text = "";

/* hour is before noon */
if ( myDate.getHours() < 12 )  {
   text = "Good Morning!";
}

/* Hour is from noon to 5pm (actually to 5:59 pm) */
else if ( myDate.getHours() >= 12 && myDate.getHours() <= 17 ) {
   text = "Good Afternoon!";
}

/* the hour is after 5pm, so it is between 6pm and midnight */
else if ( myDate.getHours() > 17 && myDate.getHours() <= 24 ) {
   text = "Good Evening!";
}

/* the hour is not between 0 and 24, so something is wrong */
else {
   text = "I'm not sure what time it is!";
}

$("h1").text(text);

Without JQuery, the last line would instead be:
var h1s = document.getElementsByTagName('h1');
for(var i = 0; i < h1s.length; i ++) {
    h1s[i].innerHTML = text;
}


text:
Q: fullscreen background video not working on 18:9 mobile devices I implemented a fullscreen background video for this website https://www.yu-performance.at with the code below. It works fine on desktop and also on most mobile devices. Only on mobile devices with the 18:9 format there is white space above and below the video like shown below, but I want the video to also be fullscreen on 18:9 devices. Does anyone have an idea why this happens?
The video on 18:9 device with whitespace:
screenshot mobile 18:9
The website has a background video in the first section which is emulated as background size cover, using the following styles:
//container div
.banner {
    position: relative;
    overflow: hidden;
    width: 100%;
    height: 100%;

    //fullsize background video
    video {
        position: absolute;
        top: 50%;
        left: 50%;
        min-width: 1000%;
        min-height: 1000%;
        width: auto;
        height: auto;
        z-index: -100;
        transform: translate(-50%, -50%) scale(0.1005);
    }

A: The issue was that the video is 16:9 and on 18:9 mobile devices the video doesn't fill out the entire viewport. So I wrote another media query for only 18:9 devices that forces the video to resize to full-window-height and then the video will automatically cover the entire screen, because the width of the upscaled 16:9 video will be bigger than the screen width.
    @media screen and (max-aspect-ratio: 9/18) and (orientation: portrait) {
        video {
            min-width: 100% !important;
            min-height: 100% !important;
            width: auto !important;
            height: 100% !important;
            transform: translate(-50%, -50%) scale(1.0) !important;
        }
    }

A: just use this code in your style.css (line no. 577) code and it will be display on full screen for all screens
.banner video {
    position: absolute;
    width: 100vw;
    height: 100vh;
    z-index: -100;
}

right now you are giving left right position with transform which is useless


text:
Q: check if a string contains determinate sequence from last element to first how can i check if a string contains determinate sequence from last element to first?
Example:
I have this sequence:
A, C, C, A, B, C

If sequence contains C [index:5], B[index:4], A[index:3] return true.
In this example the expected out is true
I have this sequence:
P, R, P, R, R

If sequence contains P [index:5], R[index:4], P[index:3] return true.
In this example the expected out is false

A: If you have your target sequence as list, you could slice your input in reversed order and check if equal:
# 1st
#input list
lst = ['A', 'C', 'C', 'A', 'B', 'C']

#target list
target = ['C', 'B', 'A']
len_target = len(target)

# get the ending index dependent on length of input and target list
idx = len(lst) - len_target - 1 # 5 - 3 - 1 = 2
print(lst[:idx:-1] == target) # lst[:2:-1] slice starting from the back till idx 2 (2 not included)
# ['C', 'B', 'A'] == ['C', 'B', 'A'] --> True

# 2nd
lst = ['P', 'R', 'P', 'R', 'R']
target = ['P', 'R', 'P']
len_target = len(target)
idx = len(lst) - len_target - 1

print(lst[:idx:-1] == target)
False

If you want to read more about how to slice lists, this question has very detailed explanation.

A: Rabinzel's solution is good.  If you want a solution using a loop you can do something like this:
Given seqeunce = 'ACCABC' and target = 'CBA'
def checkSeq(sequence, target):
    # This assumes target is the characters to be checked in reverse order from end of seqeuence
    if len(target) > len(sequence):
        return False

    pos = -1
    for ch in target:
        if sequence[pos] != ch:
            return False
        pos -= 1

    return True

Or this solution which ignores checking lengths and indexes entirely:
def checkSeq(sequence, target):
    # target is list of elements to check for at the end of sequence in the reverse order
    target = list(reversed(target))
    sequence = list(sequence)
    while sequence and target:
        if target.pop() != sequence.pop():
            return False
    return not (target and not sequence)


text:
Q: HSQLDB ANY array function not working I have a table like this
CREATE TABLE inlist_test_table (
    id  NUMERIC(5) NOT NULL PRIMARY KEY,
    val VARCHAR(50) NOT NULL
);

I'm executing the following query
SELECT val
FROM inlist_test_table
WHERE id = ANY(?)
ORDER BY id

Using this code
try (var connection = this.dataSource.getConnection();
     var preparedStatement = connection.prepareStatement(this.getQuery())) {
  var array = connection.createArrayOf("smallint", new Object[] {3, 5});
  try {
    preparedStatement.setArray(1, array);

    List<String> values = new ArrayList<>(2);
    try (var resultSet = preparedStatement.executeQuery()) {
      while (resultSet.next()) {
        values.add(resultSet.getString(1));
      }
    }
    assertEquals(Arrays.asList("Value_00003", "Value_00005"), values);
  } finally {
    array.free();
  }
}

I expect rows with id 3 and 5 to be returned. Instead I'm getting the following exception:
java.sql.SQLSyntaxErrorException: invalid ORDER BY expression in statement [SELECT val FROM inlist_test_table WHERE id = ANY(?) ORDER BY id]
    at org.hsqldb.jdbc.JDBCUtil.sqlException(Unknown Source)
    at org.hsqldb.jdbc.JDBCUtil.sqlException(Unknown Source)
    at org.hsqldb.jdbc.JDBCPreparedStatement.<init>(Unknown Source)
    at org.hsqldb.jdbc.JDBCConnection.prepareStatement(Unknown Source)
    at com.github.marschall.jdbcinlists.AbstractInListTest.plainJdbc(AbstractInListTest.java:43)
    ...
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:206)
Caused by: org.hsqldb.HsqlException: invalid ORDER BY expression
    at org.hsqldb.error.Error.error(Unknown Source)
    at org.hsqldb.error.Error.error(Unknown Source)
    at org.hsqldb.QuerySpecification.resolveColumnReferencesInOrderBy(Unknown Source)
    at org.hsqldb.QuerySpecification.resolveColumnReferences(Unknown Source)
    at org.hsqldb.QuerySpecification.resolveReferences(Unknown Source)
    at org.hsqldb.QueryExpression.resolve(Unknown Source)
    at org.hsqldb.ParserDQL.compileCursorSpecification(Unknown Source)
    at org.hsqldb.ParserCommand.compilePart(Unknown Source)
    at org.hsqldb.ParserCommand.compileStatement(Unknown Source)
    at org.hsqldb.Session.compileStatement(Unknown Source)
    at org.hsqldb.StatementManager.compile(Unknown Source)
    at org.hsqldb.Session.execute(Unknown Source)
... 59 more

I am using HSQLDB 2.4.1. The same code is working for Postgres and H2.
Edit 1
SELECT val
FROM inlist_test_table
WHERE id IN ( UNNEST(?) )
ORDER BY id

Does not work as only the row with id 3 (the first element in the array) is matched and row with id 5 (the second element in the array) is not matched.
Edit 2
Changing the column type from NUMERIC(5) to int makes the UNNEST code work even if the array element type is smallint.

A: With HSQLDB you need to use
... WHERE id IN ( UNNEST(?) ) ...

As of version 2.4.1 there appears to be an issue when the column is NUMERIC(5) and the array is smallint. That will likely be fixed in a future release of HSQLDB.


text:
Q: Sampling variance when the largest observation is removed I have the sampling variance of the sample mean: $V_1=\frac{1}{N-1}\sum_i (x_i-\bar{x})^2$. Now if the largest observation is removed, I have a new variance, $$V_2=\frac{1}{N-2}\sum_{i=0}^{n-1} (x_i-\bar{\bar{x}})^2$$ where $\bar{\bar{x}}$ is the new (reduced) mean of the $N-2$ observations.
Depending on the data, I could see $V_1$ could be greater or lesser than $V_2$.
An intuitive example of $V_1>V_2$ is when you consider one anomalous large value and mostly small observations.
Is there an intuitively clear example where I can visually understand the case where $V_1<V_2$?

A: Consider ${\bf x}=(1,8,9,10)$: $\bar x = 7$, $s^2 = 16 \frac23$. When you remove the highest value $x_4=10$, it only increases the influence of the low outlier $x_1=1$: $\bar x =6$, $s^2 = 19$. Feel free to play with numbers more to get all the results in integers :).


text:
Q: Which template system should I use in Typo3? Up to now, I used to use template auto-parser. I like the fact I can modify any element of the template using typoscript, without altering the initial HTML file. I also like the fact that I can render the html template directly in a web browser, filling it with dummy elements to see examples of menus and content elements. Finally, with the new backend templates, i now can place content elements anywhere on a grid, in a way that mimics the real aspect of the website.
I know there is also TemplaVoila. I never took the time to learn it. My feeling is that it is less compatible with some extensions, but maybe I am wrong.
Now, there is fluid, that will be used in the next version of Typo3. While it is clear that it is better using it that using template markers, I don't really understand why I should be better using Fluid than using template auto-parser or TemplaVoila. What I dislike is the fact it requires to modify the html template with special tags, meaning that either the web designer has to know Fluid, or the Typo3 integrator has to modify templates from the designer each time a modification is performed.
My question is: should I migrate form template auto-parser to Fluid for my website template? What are the benefits of using Fluid? Why should it be better? What template system should I use with Typo3?

A: As long as TypoScript does not support objects, the benefits of FLUIDTEMPLATE over template auto-parser are only a few. So there is no need to migrate.
But IMHO there are some arguments to switch to fluid:

*

*more and more extensions will use fluid, so it will help you to learn fluid

*you can use an ide with code-completion for fluid (it is just XML!)

*fluid is really powerfull, you can have f.e. if statements which checks for empty content

*some day TypoScript will support objects as well

But for extension developement, it is totally different. In an Extension, i would allways prefere using FLUID. You do not have to deal with template things inside your extension anymore. Just pass the data to fluid and things which concern the view will be done in your template.

A: Whever you choose, it should be something based on Fluid - this will allow you to be extremely versatile and it makes the implementation less important than the template, which is quite good.
I myself am the creator of the "Fluid Powered TYPO3" framework (formerly known as FED) and would of course recommend that you take a look at what this framework can do for you - it's capable of great things, not the least of which is saving you a lot of time while at the same time allowing you to create even more consistent templating for pages and content - and even backend modules.
And we're always happy to help new users. We are currently in the process of improving our documentation, but you can already find many fully up-to-date guides on our Github page - https://github.com/FluidTYPO3 - the repository called "documentation" is the place we will store all the documentation.
You may want to have a look at http://fedext.net http://fluidtypo3.org - especially the "Tour of features" which tries to explain the point of Fluid Powered TYPO3 in as few words as possible. After that, the examples from the documentation will give you a much clearer picture of what Fluid Powered TYPO3 can do for you.
We focus on efficiency always - we've tried to do all the heavy lifting so that you really can just sit down and begin creating page templates. We took a lot of inspiration from TemplaVoila but there is no more re-mapping of content and things like this: when you change your templates, that change is immediately reflected, which makes it very nice to work with in iterations and do things like continuous delivery and -integration.
Hopefully this helps!
Cheers,
Claus aka. NamelessCoder

A: You could also argue, that adding special tags like
<f:section name="typo-content">

This is where the designer intended content to go</

</f:section>

Could assist your designer while doing a redesign to know where you "mapped" your content elements to. This is neither the case with autoparser nor with TemplaVoila. So if the designer moves stuff around you probably get your templates back and they still work without any modifications.


text:
Q: Center divs with text I am running the following code:
https://jsfiddle.net/5uoz3mqz/1/

.triangle {
  text-align: center;
  width: 100%;
  height: 0px;
  border-style: inset;
  border-width: 0 300px 300px 0;
  border-color: transparent #f08326 transparent transparent;
  position: absolute;
}

.page-title {
  position: relative;
  text-align: center;
  font-family: "bebas";
  font-size: 30px;
  color: #fff;
  text-transform: uppercase;
  padding: 5px;
  background-color: rgba(15, 138, 199, 0.87);
  border: 0.1em solid rgba(4, 79, 102, 0.22);
  width: 130px;
}

White Labs

Some text here to make dasssssssssssssssssssssssssssssssssssssssssssssssssssssss

How can I center the title box as well as the text on top of the div with the triangle? I just the triangle to stay on the side and on top have the centered title box and then have the centered text.
Thanks,

A: Just use margin: 0pc auto; in .page-title
for updated fiddle demo click here
.page-title {
  position: relative;
  text-align: center;
  font-family: "bebas";
  font-size: 30px;
  color: #fff;
  text-transform: uppercase;
  padding: 5px;
  background-color: rgba(15, 138, 199, 0.87);
  border: 0.1em solid rgba(4, 79, 102, 0.22);
  width: 130px;
  margin:0px auto;
}

Or better to give pseudo element instead of tringle border,
updated code below:
.triangle {
    text-align: center;
    width: 300px;
    height: 300px;
    position: absolute;
    overflow: hidden;
}
.triangle:before {
  content:'';
  position:absolute;
  right:-423px;
  top:-300px;
  background:rgba(240,131,38,0.50);
  width:600px;
  height:600px;
  transform: rotate(45deg);
  z-index:0;
}
.page-title {
  position: relative;
  text-align: center;
  font-family: "bebas";
  font-size: 30px;
  color: #fff;
  text-transform: uppercase;
  padding: 5px;
  background-color: rgba(15, 138, 199, 0.87);
  border: 0.1em solid rgba(4, 79, 102, 0.22);
  width: 130px;
  margin:0px auto;
}
.triangle p {
  position: relative;
}

for fiddle link click here

A: Simply Add "margin:0 auto;" property to .page-title in css.
it will reset all margins and set it to center automatically.

A: The main div container with width:0 will be an issue , because the child container will need some width in order to position/float to center. I have changed the div structure as well, please find the solution in : https://jsfiddle.net/u1Lsux7n/1/ . Also the long text 'dssssss.......' in your example, you will have to add 'overflow' css to make such textx center aligned.
You can also have your main triangle container with a width of 90% to start and then give child containers width accordingly.
.triangle {
    text-align: center;
    width: 0px;
    height: 0px;
    border-style: inset;
    border-width: 0 300px 300px 0;
    border-color: transparent #f08326 transparent transparent;
    position: absolute;
}

.page-title {
    position: relative;
    text-align: center;
    font-family: "bebas";
    font-size: 30px;
    color: #fff; text-transform: uppercase;
    padding: 5px; background-color: rgba(15, 138, 199, 0.87);
    border: 0.1em solid rgba(4, 79, 102, 0.22);
    width: 130px;
    margin:0 auto;

 }

 .triangle-container {
      width: 300px;
      height: 300px;
      float: left;
 }

 .page-contents {
      float: left;
 }

Tile

Some text here to make dasssssssssssssssssssss ssssssssssssssssssssssssssssssssss


text:
Q: checkbox inside update panels refreshed and the When i take 55 checkboxes inside updatepanel then ..after selecting first checkbox the whole whole checkboxes will be refreshed and instead of showing images, it displays the checkboxes only in TFT monitors ... in wave form !!
hw to fix tis ..
or otherwise tell me how to insert checkbox checked value to textbox without autopostback

A: Set the AutoPostBack to False and not True!


text:
Q: How to drag and drop directory and get only the path of it? How can i drag and drop directory in windows and get the path of the directory - that is in order to not to write the path by myself all the time (sometimes its really long).
I tried to look for a solution but couldn't find as most drag and drop that relate to directory or files just getting the directory file list.

A: Dropping directories is supported in input type "file" on Chome, however I don't think you will be able to get the full path easily, due to security reasons.
Take a loot at the example:
var dropzone = document.getElementById('dropzone');
dropzone.ondrop = function(e) {
  var length = e.dataTransfer.items.length;
    var entry = e.dataTransfer.items[0].webkitGetAsEntry();
    if (entry.isDirectory) {
        alert(entry.fullPath);
    }
};

https://jsfiddle.net/zp574g63/1/


text:
Q: How to convert Array of values in VBA to array of other value types, based on user input? So I have an class returns array of singles. Problem is that new requrement came up where I need to be able provide these values as a single string, which can be done with Join except Join requres that array is made up of strings not singles.
I guess I could write a new method in my class that provides same array but with values as strings. However I was wondering if I could just convert existing method to accept something like Optional ValType as vbVarType as a parameter and accordingly change the type of values in ouputed array.
Is this doable in a relatively DRY way?? I'd love to avoid code that looks like:
Select Case ValType
    Case #something1
        #omitted code
    Case #something2
        #omitted codev
    Case #something3
        #omitted code
    ........

UPDATE: I guess what I am looking for is a formula like Cstr() except that I'd like it to work on an Array and have it expect parameeter describing value to convert to.

A: Can you simply have an array of type Variant rather than Single? The following code seems to work ok:
Dim arrInt() As Variant

ReDim arrInt(0 To 3)

arrInt(0) = 0
arrInt(1) = 1
arrInt(2) = 2
arrInt(3) = 3

Debug.Print Join(arrInt, "#")


text:
Q: Cannot Read Property Map of Undefined--Twitter API in React Hi all I'm fairly new to React so please tread lightly :0)
I'm trying to create a simple React app, in which a user can enter a search term, and a list of Tweets is populate.  Just fleshing this out right now using the Node Twit app.  I'm getting a 'Cannot read property 'map' of undefined' on a map function in the part where I'm trying to list out the tweets.
Here's where I'm running the map function in my 'Twitter' Component.
render() {
        const tweets = this.state.tweets;
        return (

          {tweets.statuses.map(tweet =>

                    {tweet.text}

          )}
            )};

        );
    }
}

I know this has to be an issue with how I'm fetching the data--but have never worked with the Twitter API, so hoping someone might have some input---here's where I do that:
 performSearch = (searchTerm) => {
       T.get('search/tweets', {q: {searchTerm}})
       .then((err,data,response) => {
           let tweets = this.state.data;
           this.setState({
               tweets
           });
           console.log(tweets);
       })
       .catch(err=>{
           console.log('Error happened fetching data');
       });
    }

I'm also running this search function when the component mounts, like so
 componentDidMount() {
        this.performSearch();
    }

And not sure if matters but variable 'tweets' is set on initial state as []
class Twitter extends Component {

    constructor(props) {
        super(props);

        this.state = {
            tweets: [],
            searchTerm: this.props.searchTerm
    }
   }

If you need any more code for this to make more sense--just let me know. Thanks!

A: I guess if you call this function in WillMount this will work!
because in DidMount  your component already have been called the render() method and the current value of statuses is undefined.
or you can try some approuch like this:
render() {
        const tweets = this.state.tweets;
        return (

          {tweets.statuses &&
            tweets.statuses.map(tweet =>

                    {tweet.text}

          )}
            )};

        );
    }
}

hope this could help you!


text:
Q: Best practice to convert data.responseText to jQuery object Is there any difference between this code
$.get('http://www.google.com/', function(data) {
    var html = $('

').html(data.responseText).children();
});

and this code
$.get('http://www.google.com/', function(data) {
    var html = $(data.responseText);
});

What should I use and why?
Thanks in advance.


text:
Q: I'd like to grep the output of ifconfig in bash I'm making a small script to determine if I have an internet connection on OSX. More of just practice, I suppose.
In terminal "ifconfig | grep -cs 'status: active' " will return 1 if there's at least one active connection
The script I have is this
    #!/bin/bash

detect(){
ONLINE=ifconfig | grep -cs 'status: active'
}

if [[ detect = 1 ]]
then
        echo "Online"
else
        echo "Offline"
fi

However the Variable ONLINE always returns 0.
From what I can tell/understand, this has to do with using a pipe inside of the script. A sub-pipe is used when running the command, and ONLINE just gets stuck with 0 as the sub-pipe closes.
I think I see the issue, but I don't know how to get around this. I saw a bunch of work arounds for scripts having this issue with while loops, but nothing where I need the output from ifconfig fed into grep.

A: Several problems with your current script:

*

*You set a variable ONLINE, but you test for detect.

*You don't actually assign the result of the ifconfig | grep -cs 'status: active' command to the variable ONLINE

*You use = instead of == to test for equality

The following would seem to be closer to what you intended:
#!/bin/bash
ONLINE=$(ifconfig | grep -cs 'status: active')
if [[ $ONLINE == 1 ]]
then
  echo "online"
else
  echo "offline"
fi

A: use this:
ONLINE=$(ifconfig | grep -cs 'status: active')

cause without "$" what bash will return is the result of the command being successful or not and if it is successful it is always zero.

A: Or you can just keep it simple like this ...
ifconfig | grep 'status: active' > /dev/null 2>&1
if [ $? == 0 ]
then
   echo "online"
else
   echo "offline"
fi

A: As none of the answers explain the exact issue with your script, I'm adding an answer.
The issue lies with the line ONLINE=ifconfig | grep -cs 'status: active'.
What is wrong is that there is no command substitution ($(...) or `...`) used in the line. As correctly suggested by other answers as well, the assignment needs to be $(ONLINE=ifconfig | grep -cs 'status: active').
What this line actually does is that it assigns the string "ifconfig" to the variable ONLINE and pipes the output of that (no output in this case) through grep -cs ...
One point to note is that this assignment is only for the duration of that line, and does not survive till the next line. To illustrate:
samveen@precise:~$ I=0
samveen@precise:~$ echo $I
0
samveen@precise:~$ I=1 | echo "blank"
blank
samveen@precise:~$ echo $I
0

Edit: I totally missed another very important point: Subroutines do not return values in bash, just exit status
Thus capturing variables from subroutine calls needs the subroutine to echo it's expected return value and it's call needs an assignment with command substitution.
Something like this:
detect(){
    ONLINE=$(ifconfig | grep -cs 'status: active')
    echo $ONLINE
}

if [[ $(detect) -eq 1 ]]
then
    echo "Online"
else
    echo "Offline"
fi

Also, use -eq to test numeric equality.
Finally, the shortest way to do what you want is
ifconfig | grep -q 'status:active' && echo "online" || echo "offline"


text:
Q: Prove that $\sum\limits_{r=1}^n (sr^{-1} -r^{-3}) -s \log n$ has a limit as $n \to \infty$, $\forall s>1$ Prove that if $s >1$, then $\displaystyle {\sum_{r=1}^n} \left( {\frac{s}{r}- \frac{1}{r^3}} \right) - s \log n$ tends to a limit as $n \to \infty$ ($s$ being fixed), and that if this limit is $\phi (s)$ then [also show that] $0 \le \left[ {\phi (s) + \frac {1}{s-1}} \right] \le (s-1)$
From A Course of Mathematical Analysis by Shanti Narayan pp.332.
Edit: Solved! $\displaystyle {\lim_{n \to \infty} \sum_{r=1}^n} \left( {\frac{s}{r}- \frac{1}{r^3}} \right) - s \log n$
$= \displaystyle {\lim_{n \to \infty} \sum_{r=1}^n} \left( {\frac{s}{r}} \right) - s \log n -\displaystyle {\lim_{n \to \infty} \sum_{r=1}^n} \left( {\frac{1}{r^3}} \right)$
$=s \gamma - \zeta(3)$ [$\gamma$ := Euler-Mascheroni constant].
Now the inequality, which I suppose to be wrong (but actually it is not), was proved using Mathematical Induction.
Thanks to all.

A: Hint:  Check the definition of the Euler-Mascheroni constant for two terms.  The third term converges easily.

A:
Here is a nice way to see $\displaystyle\sum_{k=1}^{n-1} \frac{1}{k} - \log n $ converges (which essentially answers the first question). I have shaded in the "error" when estimating $\log n$ with the sum, and then shifted those regions horizontally. Clearly, as we take higher partial sums, the sum of the errors will increase. We can always slide them to fit into the $1$ by $1$ rectangle on the left, so it is bounded as well and hence converges. Now it is your exercise to convert this into a rigorous proof.


text:
Q: IOS 10.3.3 Iphone Safari beforeunload, unload, pagehide wont work I'm trying to catch beforeunload, unload, pagehide events on iPhone Safari (602.1) IOS 10.3.3. But it seems that on iPhone these events don't fire, and the funny part is that on iPad which has same versions of browser and IOS, the events do fire. The only difference that I noticed was that iPad gives you the tab option but iPhone doesn't. Is there any way to catch these events on iPhone IOS 10.3.3?
Note: These events do fire on iPhone IOS 8.4.1.

A: I use event pagehide with (partial) success, see supported Events in Apple Guides.
The only situation that pagehide does not work is on iPhone 10, and when the website is stored to the application 'springboard'. The web application (build with Vuejs) looks like a native App. Leaving the 'app' does not fire pagehide. On older iPhones and iPads in the same situation, pagehide fires.
window.addEventListener('pagehide', () => {
// do something
}