Angular js images upload

Question: I generate some images on frontend and I want to send them directly to backend for further processing. How can I do that without using a form data? Are there any options?
Image is generated from canvas (print screen actually) and should be posted to server as it is generated.
I use Node js for backend (Express server) and Angular for frontend.
Any help or insights are welcome!
Thanks in advance.
Answer: So you need to:

draw on the canvas
var canvas = document.createElement('canvas');
canvas.width = 600;
canvas.height = 600;
var context = canvas.getContext('2d');

context.beginPath();
context.moveTo(100, 150);
context.lineTo(450, 50);
context.lineWidth = 10;

// set line color
context.strokeStyle = '#ff0000';
context.stroke();

encode the canvas data to a format of your choice (say jpg)
function dataURItoBlob(dataURI) {
  var binary = atob(dataURI.split(',')[1]);
  var array = [];
  for (var i = 0; i < binary.length; i++) {
    array.push(binary.charCodeAt(i));
  }
  return new Blob([new Uint8Array(array)], {
    type: 'image/jpeg'
  });
}

function canvasToJPG(cvs, done) {
  var quality = 90; // jpeg quality

  if (cvs.toBlob) // some browsers has support for toBlob
    cvs.toBlob(done, 'image/jpeg', quality / 100);
  else
    done(dataURItoBlob(cvs.toDataURL('image/jpeg', quality / 100)));
}

send it on the wire using AngularJS $http
$http
({
    method: 'POST',
    url: '/upload',
    headers: {'Content-Type': 'image/jpeg'},
    data: data,
    transformRequest: []
})
.success(function ()
{
    alert('image uploaded :)');
})
.error(function (err)
{
    console.log('upload error',err);
    alert('something went wrong :( ');
});

4a. get it from your ExpressJS route on node (say streaming it on the fs)
    app.post('/upload', function(req, res, next) {
      var wstream= fs.createWriteStream('uploaded.jpg'); // say you want to write the file to disk

      req.pipe(wstream) // pipe the http request body to the file stream
         .on('error',next) // something went wrong with the fs, return 500
         .on('finish',function () {
             res.status(204).send(); // success!
         });
    });

4b. get it from your ExpressJS route on node (say you want the raw JPG buffer)
    app.post('/upload', function(req, res, next) {
      var buff= [];

      req.on('data',function (data)
         {
            buff.push(data);
         })
         .on('error',next)
         .on('end',function () {
             fs.writeFile('uploaded.jpg',Buffer.concat(buff),function (err)
             {
                 if (err) return next(err); // something went wrong with the fs, return 500

                 res.status(204).send(); // success!
             });
         });
    });

The complete sample:

var myapp = angular.module('myapp', []);

myapp.controller('upload', function($scope, $http) {
  $scope.drawAndUpload = function() {
    var canvas = document.createElement('canvas');
    canvas.width = 600;
    canvas.height = 600;
    var context = canvas.getContext('2d');

    context.beginPath();
    context.moveTo(100, 150);
    context.lineTo(450, 50);
    context.lineWidth = 10;

    // set line color
    context.strokeStyle = '#ff0000';
    context.stroke();

    var upload = function(data) {
      $http
        ({
          method: 'POST',
          url: '/upload',
          headers: {
            'Content-Type': 'image/jpeg'
          },
          data: data,
          transformRequest: []
        })
        .success(function() {
          alert('image uploaded :)');
        })
        .error(function(err) {
          console.log('upload error', err);
          alert('something went wrong :( ');
        });
    };

    canvasToJPG(canvas, upload);
  };
});

function dataURItoBlob(dataURI) {
  var binary = atob(dataURI.split(',')[1]);
  var array = [];
  for (var i = 0; i < binary.length; i++) {
    array.push(binary.charCodeAt(i));
  }
  return new Blob([new Uint8Array(array)], {
    type: 'image/jpeg'
  });
}

function canvasToJPG(cvs, done) {
  var quality = 90; // jpeg quality

  if (cvs.toBlob) // some browsers has support for toBlob
    cvs.toBlob(done, 'image/jpeg', quality / 100);
  else
    done(dataURItoBlob(cvs.toDataURL('image/jpeg', quality / 100)));
}

  <title>My Angular App</title>

  <button ng-click="drawAndUpload()">Draw & Upload</button>

var express = require('express'),
    fs = require('fs');
var app = express();

app.use(express.static('www'));

app.post('/upload', function(req, res, next) {
  var buff= [];

  req.on('data',function (data)
     {
        buff.push(data);
     })
     .on('error',next) // something went wrong with the fs, return 500
     .on('end',function () {
         fs.writeFile('uploaded.jpg',Buffer.concat(buff),function (err)
         {
             if (err) return next(err);

             res.status(204).send(); // success!
         });
     });
});

app.listen(8080);
Comment: Thank you for your very detailed solution! I've managed to do kinda the same thing, I also use a library for generating image from my js animation and transforming it to canvas and than to png :) the only problem I seem to have is that I have to send an image like every second to server and node won't accept(?) anything except blob.
Comment: I'm not sure I got your problem here... You don't want to send a Blob?
Comment: No, I don't :) I want it to be jpg/png :)
Comment: Well in my example the Blob contains the JPG bytes.. Looks like your library is returning to you something else maybe?
Comment: I have a custom function for converting canvas to png - but then it's converted to blob to send to the server side.
Comment: Oh, I see! You use Buffer.concat() to transform blob back to image? I've never used it before, gonna read some docs :) Thanks!
Comment: On 4b Buffer.concat() is just reassembling the blob, which travels chunked on the wire, into the server memory, once "reassembled" the blob IS the image (it contains the actual bytes of the JPG) so you can save it to a .jpg file or whatever... I'm not sure what you need to do with that file/image... On 4a instead i'm streaming those chunks directly to a file on the server filesystem...
Comment: Yeah, I've figured that out:) Thanks, it works just fine! After all images are in the /temp folder I'm using ffmpeg to make a video out of them :)

Angular js images upload


Error loading C:\windows\system32\sshnas21.dll

Question: I'm using vista ultimate 32 bit. When i login to my machine.
Error loading C:\windows\system32\sshnas21.dll
The specified module could not be found.
I don't know how to resole this. Can any one help me?
Answer: A Google search shows that sshnas21.dll is malicious. I don't know how to resolve it, but you should probably scan for viruses or something.


How to apply a "mixin" class to an old-style base class

Question: I've written a mixin class that's designed to be layered on top of a new-style class, for example via
class MixedClass(MixinClass, BaseClass):
    pass

What's the smoothest way to apply this mixin to an old-style class?  It is using a call to super in its __init__ method, so this will presumably (?) have to change, but otherwise I'd like to make as few changes as possible to MixinClass.  I should be able to derive a subclass that makes the necessary changes.
I'm considering using a class decorator on top of a class derived from BaseClass, e.g.
@old_style_mix(MixinOldSchoolRemix)
class MixedWithOldStyleClass(OldStyleClass)

where MixinOldSchoolRemix is derived from MixinClass and just re-implements methods that use super to instead use a class variable that contains the class it is mixed with, in this case OldStyleClass.  This class variable would be set by old_style_mix as part of the mixing process.
old_style_mix would just update the class dictionary of e.g. MixedWithOldStyleClass with the contents of the mixin class (e.g. MixinOldSchoolRemix) dictionary.
Is this a reasonable strategy?  Is there a better way?  It seems like this would be a common problem, given that there are numerous available modules still using old-style classes.
Comment: would I be out of line for suggesting a conversion of the old style class to a new style class?
Comment: @aaronasterling: If I could cause it to be retroactively updated in all installations of the standard library, I would definitely do that.
Answer:
This class variable would be set by
  old_style_mix as part of the mixing
  process.

...I assume you mean: "...on the class it's decorating..." as opposed to "on the class that is its argument" (the latter would be a disaster).

old_style_mix would just update the
  class dictionary of e.g.
  MixedWithOldStyleClass with the
  contents of the mixin class (e.g.
  MixinOldSchoolRemix) dictionary.

No good -- the information that MixinOldSchoolRemix derives from MixinClass, for example, is not in the former's dictionary.  So, old_style_mix must take a different strategy: for example, build a new class (which I believe has to be a new-style one, because old-style ones do not accept new-style ones as __bases__) with the appropriate sequence of bases, as well as a suitably tweaked dictionary.

Is this a reasonable strategy?

With the above provisos.

It seems like this would be a common
  problem, given that there are numerous
  available modules still using
  old-style classes.

...but mixins with classes that were never designed to take mixins are definitely not a common design pattern, so the problem isn't common at all (I don't remember seeing it even once in the many years since new-style classes were born, and I was actively consulting, teaching advanced classes, and helping people with Python problems for many of those years, as well as doing a lot of software development myself -- I do tend to have encountered any "reasonably common" problem that people may have with features which have been around long enough!-).
Here's example code for what your class decorator could do (if you prefer to have it in a class decorator rather than directly inline...):
>>> class Mixo(object):
...   def foo(self):
...     print 'Mixo.foo'
...     self.thesuper.foo(self)
...
>>> class Old:
...   def foo(self):
...     print 'Old.foo'
...
>>> class Mixed(Mixo, Old):
...   thesuper = Old
...
>>> m = Mixed()
>>> m.foo()
Mixo.foo
Old.foo

If you want to build Mixed under the assumed name/binding of Mixo in your decorator, you could do it with a call to type, or by setting Mixed.__name__ = cls.__name__ (where cls is the class you're decorating).  I think the latter approach is simpler (warning, untested code -- the above interactive shell session is a real one, but I have not tested the following code):
def oldstylemix(mixin):
    def makemix(cls):
        class Mixed(mixin, cls):
            thesuper = cls
        Mixed.__name__ = cls.__name__
        return Mixed
    return makemix


Change shape parameters in a beta distribution based in each datapoint

Question: I am new to Bayesian statistics and I have been trying to implement a Beta Binomial model from a PhD thesis in rjags. The thesis describes prior distribution for the variables but I am stuck in how to implement the following part of the model:
$p_{j k} \mid \alpha_{j k}, F_{k} \sim \begin{cases}\operatorname{Beta}\left(\alpha_{j k}\left(1-F_{k}\right) / F_{k},\left(1-\alpha_{j k}\right)\left(1-F_{k}\right) / F_{k}),\right. & \text { if } G_{j k}=0 \\ \text {Uniform }[0,1], & \text { if } G_{j k}=1\end{cases}$
Depending on the value of $p_{j k}$ (an observed variable), we assume either a Beta or a Uniform distribution: if the value falls within a standard deviation from the mean we consider that it was drawn from the above Beta, otherwise we consider it an Uniform-drawn value. I reckon that the Uniform is a special case of Beta distribution, so I guess the key is to code JAGS to test the fit of each value of $p_{j k}$ to the Beta and then change the shape parameters to (1,1) if the input value falls outside that range ($G_{j k}$ is actually indicating the result of this test, with 0 signing success).
In short, I would like to add an if statement before the prior distribution of $p_{j k}$, if that is possible, or something equivalent, and then change the Beta shape parameters accordingly. I could not find a solution in JAGS manual or anywhere else, any help is welcomed.
Edit
So far, I could think of the likelihoods as follows (I've set alpha to 1, Fk to 0.5 and sum 1 to parameter beta when $p_{j k}$ is beyond alpha$\pm$SD the so that I can get a Beta(1,1), that is, a Uniform(0,1)). But I am not sure this translates to the model and if will work properly in JAGS.
<code>    library("rjags")

    set.seed(8361289)
    model_string = "model {
   for (j in 1:length(SNP)) {   #iterate though SNPs
      alpha[j] <- ifelse(Padmix[j]>alpha[j]+(alpha[j]*Fk[j]*(1-alpha[i])), 1, alpha[j])
      alpha[j] <- ifelse(Padmix[j]<alpha[j]-(alpha[j]*Fk[j]*(1-alpha[i])), 1, alpha[j])
      Fk <- ifelse(Padmix[j]>alpha[j]+(alpha[j]*Fk[j]*(1-alpha[i])), 0.5, Fk[j])
      Fk <- ifelse(Padmix[j]<alpha[j]-(alpha[j]*Fk[j]*(1-alpha[i])), 0.5, Fk[j])
      G[j] <- ifelse(Padmix[j]>alpha[j]+(alpha[j]*Fk[j]*(1-alpha[i])), 1, 0)
      G[j] <- ifelse(Padmix[j]<alpha[j]-(alpha[j]*Fk[j]*(1-alpha[i])), 1, 0)
      Padmix[j] ~ dbeta(alpha[j]*(1-Fk[j])/Fk[j], (1-alpha[j])*(1-Fk[j])/(Fk[j])+G[j]) # beta for allele frequency in admixed pop
      Xadmix[j] ~ dbin(Padmix[j], Nadmix[j]) # draw allele count from a bin with p=allele frequency (Padmix) and n=nonmiss alleles (Nadmix)
      Pdonor[j] ~ dbeta(x[donor[j]]+1, n[donor[j]]-x[donor[j]]+1)
      alpha[j] = sum(beta[donor[j]] * Pdonor[donor[j]])

        }
      Fk[j] ~ dbeta(1, 500)
      G[j] ~ dbern(0.001)

      for (d in 1:max(donor)) {
          beta[d] = anc_prop[d]
       }
      Padmix = MAF
      Nadmix = nonmiss_admix
      x = allele_count_donor
      n = nonmiss_donor

    }"
</code>
Detailed model description (in: Detecting signals of selection in the genomes of Native Americans and admixed Latin Americans. Mendoza-Revilla, 2018):
Answer: To simplify the distributional expression, define the quantities:
$$\begin{align}
R_k
&\equiv \frac{1-F_k}{F_k} \\[18pt]
A_{jk}
&\equiv \begin{cases}
\alpha_{j k} R_k & & & & & \ \ \text { if } G_{j k} = 0 \\[6pt]
1 & & & & & \ \ \text { if } G_{j k} = 1 \\[6pt]
\end{cases} \\[18pt]
B_{jk}
&\equiv \begin{cases}
\alpha_{j k} (1- R_k) & & & \text { if } G_{j k} = 0 \\[6pt]
1 & & & \text { if } G_{j k} = 1 \\[6pt]
\end{cases}
\end{align}$$
You then have:
$$p_{j k} \mid \alpha_{j k}, F_{k} \sim \text{Beta}(A_{jk}, B_{jk}).$$
This form allows you to state the conditional distribution in a simple form based on previously stipulated parameters.  It should be simple to implement this in JAGS.


Do Harmonicas come in different keys?

Question: I am wondering if Harmonicas come in different keys. I have never played one and am confused about how they skip all the chromatic notes and stay in one key when they are playing.
Answer: https://en.wikipedia.org/wiki/Harmonica#Diatonic Yes, harmonicas come in keys, but they also make chromatic harmonicas that will play in any key.  Of course, with flexibility comes complexity, so a chromatic harp takes some additional manipulation (a chromatic key) to make the notes.
Comment: Not only different keys, but also different scales.  I have a harmonic minor harmonica, for example.  (Which I more often play as if it's Major Phrygian.)
Answer: When you blow, the harmonica produces the 1st, 3rd and 5th notes of a major scale. When you suck, you get the 2nd, 4th, 6th and 7th. You select precisely which note by narrowing your mouth aperture or by blocking unwanted notes with your tongue.
Blues players usually have several instruments in different keys. They often play the one in C when the blues is in G. The reason is that the one in G has an F# they don't need while the one in C has an F-natural they do. The rule is to use the one that's a fourth higher than the rest of the band.
Comment: @Tetsujin: I hadn't heard that but yes, that's right. A useful reminder for a beginner or for a singer who's branching out! Drummers don't always need to be reminded "Pointy end away from you" but I tell 'em anyway.
Comment: I wondered why I keep dropping my sticks ;) As the joke goes, the difference between a drummer & a drum machine is you only have to punch information into a drum machine once. ;)
Comment: Heh heh! Looking at our passports, the customs guys used to ask, "Work or vacation?" "Work," we'd say. "Music." "How many musicians?" "Seven", we'd say. "And a drummer."
Comment: Someone once said, '4th up for blues, same key for country'. Does that make sense to you? I've never played harp so I've no clue.
Comment: Thanks. It sounds like an interesting instrument. I will have to get one. I looked up some female harmonica players. I will have to listen to them.  http://www.harmonicalinks.com/women-harmonica-players.html#:~:text=Store%3A%201%20Lady%20A%202%20Louise%20Hoffsten%203,Vazquez%2010%20Jill%20%22Chilly%22%20Kurtz%20More%20items...%20
Comment: You're welcome. I can play tunes on one but I never did learn how to bend the notes properly, or how to impersonate a train.

Do Harmonicas come in different keys?


jquery jScrollPane ipad issue

Question: I am pulling my hair out with an scroll issue with iPad/iPhone...
I am using the fantastic jScrollPane plugin which works a treat on desktop browsers but on iPad/iPhone the div doesnt scroll (to do with touch events or something?)
I have tried all the fixes:
http://snipplr.com/view/41051/jscrollpane-ipadiphoneipodios-scoll-support/
(i think old version of jScrollPane so not sure where this fits in)
http://code.google.com/p/jquery-ui-for-ipad-and-iphone/
just didnt work full stop seemingly
https://github.com/aFarkas/jScrollPane/commit/553612cb26a390004a9aa63ab0511e2b668bcf8c#diff-1
script/jquery.touchdrag.js: applied and didnt seem to work either
Any ideas anyone? My client is impatient :/
A.
Comment: just to add:https://github.com/aFarkas/jScrollPane/commit/553612cb26a390004a9aa63ab0511e2b668bcf8c#diff-1 works if you use the supplied jScrollPane to (beta 5) I was using beta 6 which didnt work
Comment: Glad you figured out a way to get it to work... I will integrate that patch into the up to date version of jScrollPane ASAP (jScrollPane is my plugin) - I'm really busy with client work at the moment so haven't had a chance... This is the issue where I am keeping track of all of the possible solutions: https://github.com/vitch/jScrollPane/issues#issue/14
Answer: Just saw this questions is a bit old, anyway, I post my research here:
My version is jscrollpane v2.0.0beta10
I am also using Kelvin Luck's jscrollpane directly from his site.
I have just tried our website, it seems newer version is working without problem.
Just made a scroll demo here extracted from my site
Only using the basic code like
<code>$('.scrollbar-area').jScrollPane({
    showArrows: true,
    horizontalGutter: 10 // must set for IE running properly
});
</code>
I have tested in iPad 2.0(iOS 6.01), I have no iPhone for testing.
When I drag the content, it work in iPad. The scrollbar itself does not work though.

jquery jScrollPane ipad issue


OpenCV and iOS in an iPhone

Question: We have built a desktop application in java which uses OpenCV.
We would like to build a similar app for iPhone. Is OpenCV available by default in iOS?
If that is not the case, is the user required to download and install openCV separately for iPhone to use the app dependent on OpenCV?
Is there a way build the app in such a way that all of its dependencies are self-contained i.e. even if the app uses OpenCV, the user need not install OpenCV separately? If so how to do it? I can't find any tutorial.
Answer: No open CV is not in objective-c by default so you have to download the library and install it first them develop the app and compile it with the library.
http://opencv.org/downloads.html
Yes, you can build it as self contained app if you add the framework to the dependencies section in Xcode. Apple will not allow the user to download and install stuff on the iphone each app is downloaded separately.

OpenCV and iOS in an iPhone


PHP filter field behavior with Rules - can't use curl_exec

Question: I am on Drupal 7. I am trying to use Rules to execute custom PHP code. I am using PHP filter in order to achieve that. Inside that PHP filter I will use curl. The idea is to communicate with a remote API.
I already have one Drupal website running this code I want to use and it works like a charm. On this website I am using Rules, PHP filter and curl.
The issue is that I am porting the EXACT same code to a new website using the same set of tools (Rules, PHP filter, curl), but I can't save my code into PHP filter.
The field will allow me to save this
<code>$data = array(
'User'          => 'someuser',
'Password'      => 'somepassword',
'Subject'       => 'Something',
'Message'       => 'Something',
'StampToSend'   => $account->created,
'MessageTypeID' => 1
);

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "https://someurl.com");
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_FAILONERROR, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
</code>
When I add the last line "$response = curl_exec($curl);", then Drupal won't save my Rule. No error messages, no messages in the Drupal logs, no anything. It will just fail to save the field. I can save all the code above, and Rules with PHP filter will accept it. When adding the curl_execute line, it simply won't save.
Any ideas on what I could do? Thank you!
Answer: I solved the issue by moving the code to a custom module, then everything worked. My best guess is that the PHP filter is somehow interpreting the code and filteirng out stuff it considers innapropriate.


Show node hit counts in a VIEW?

Question: I have googled and found a few articles:
http://nossdutytask.com/drupal_config/step_by_step_enable_view_post_access_counter_on_drupal
Only I don't want to show the counter as a block but as a field in a VIEW. I followed the above article but when I add fields to my view I cannot find any stat or counter or anything.
Is this possible without writing a custom module or tweaking my template.php and populating this value programmatically?
Answer: You need to enable the Statistics module from admin/modules.
Configure what you want to track from admin/config/system/statistics
Then edit your view.  Add a Field.  There will be a category called Content Statistics that you can filter on.  Choose the stat you want, and then configure it.

The above is for Drupal 7 / Views 3.  The steps are mostly the same for Drupal 6 and Views 2 or Views 3, but the labels are a little different.
Just keep in mind that Statistics module can cause performance problems on busy sites.  You may also want to check out Radioactivity, and see if that will work better for you:

This module provides a field type which can be used as a hotness
  metric or a regular view counter for entities and for much much more.
  In essense, entities receiving attention (views or actions defined by
  Rules) are heated while inactive ones slowly cool down.

Radioactivity does integrate with Views and a few places.
Comment: I have two installs of drupal and I enabled the stats on the wrong one while developing so I didn't see it under the VIEWS of the proper site...my bad thanks again :)

Show node hit counts in a VIEW?


WebAPI batch request filters

Question: When a batch request is made to a "Microsoft" Web-API, does every item in the batch passes by the filters or the batch passes once "as a whole"?!?
Answer: Im very sorry if i misunderstood your question (lol), please do not mark me down.
This is an advanced topic, and if you are referring to the batch ping command, then further notes about using it can be found here. To answer your question, Technicaly its piece by piece (literally bit by bit) passing through the checker programs(or filters) in the computers at Microsoft. But from an executing standpoint, a piece to be executed it loaded up until complete before it is executed. Hope i helped. PS: The ping command uses Internet Control Message Protocol.

WebAPI batch request filters


Is this the right way to code Dining philosopher using semaphore without any deadlock at all?

Question: My logic to solve this puzzle is just to make left and right chopstick free, then philosopher can grab and eat.  And I don't write a condition to break the while loop because I assume those philosophers eat and think 24/7/.
Is my solution deadlock free now?  Feel free to give me advice. I am quite new to multithreading
import java.util.concurrent.Semaphore;
import java.util.concurrent.ThreadLocalRandom;

public class Main {

    static int philosopher = 5;
    static philosopher philosophers[] = new philosopher[philosopher];
    static chopstick chopsticks[] = new chopstick[philosopher];

    static class chopstick {

        public Semaphore mutex = new Semaphore(1);

       public synchronized void grab() {
            try {

                mutex.acquire();

            }
            catch (Exception e) {
                e.printStackTrace(System.out);
            }
        }

        void release() {
            mutex.release();
        }

        boolean isFree() {
            return mutex.availablePermits() > 0;
        }

    }

    static class philosopher extends Thread {

        public int number;
        public chopstick leftchopstick;
        public chopstick rightchopstick;

        philosopher(int num, chopstick left, chopstick right) {
            number = num;
            leftchopstick = left;
            rightchopstick = right;
        }

        public synchronized void run(){
 // Program wil run forever since I did not  write exit statement.
 //  Only grab when left and right chopsticks are free
            while (true) {
                if(leftchopstick.isFree() & rightchopstick.isFree() ) {
                     leftchopstick.grab();
                     rightchopstick.grab();
                     System.out.println("philosopher " + (number+1) + " grabs left chopstick.");
                     System.out.println("philosopher " + (number+1) + " grabs right chopstick.");

                     eat();
                     leftchopstick.release();
                     System.out.println("philosopher " + (number+1) + " releases left chopstick.");
                     rightchopstick.release();
                     System.out.println("philosopher " + (number+1) + " releases right chopstick.");
                }

            }
        }

        void eat() {
            try {
                int sleepTime = ( 1000);
                System.out.println("philosopher " + (number+1) + " eats for " + sleepTime  + "miliseconds");
                Thread.sleep(sleepTime);
            }
            catch (Exception e) {
                e.printStackTrace(System.out);
            }
        }

    }

    public static void main(String argv[])  {

        for (int i = 0; i < philosopher; i++) {
            chopsticks[i] = new chopstick();
        }

        for (int i = 0; i < 5; i++) {
            philosophers[i] = new philosopher(i, chopsticks[i], chopsticks[(i + 1) % philosopher]);
            philosophers[i].start();
        }

        while (true) {
            try {
                // sleep 1 sec
                Thread.sleep(1000);

                // check for deadlock
                boolean deadlock = true;
                for (chopstick f : chopsticks) {
                    if (f.isFree()) {
                        deadlock = false;
                        break;
                    }
                }

                if (deadlock) {

                    System.out.println("Dead lock occurs cause Everyone grab left chopstick at the same time");
                    break;
                }
            }
            catch (Exception e) {
                e.printStackTrace(System.out);
            }
        }

        System.out.println("Exit The Program!");
        System.exit(0);
    }

}

Comment: IMO, what makes Dining Philosophers such a perennial favorite is that there is no single "right way." Any solution that is not susceptible to deadlock is "right" in some sense, but it lets the student try out different strategies, and compare how they perform. (Note: Philosophers only want to "think" or "eat," but they sometimes are forced to _wait._ A "high performing" solution would be one that minimizes the total time they spend waiting, and minimizes the variation in wait time from one philosopher to the next.)
Comment: The solution you've shown here is the "classic" incorrect solution.
Answer: Here is one way that your program, in theory, could deadlock:

All the chopsticks are free,
All of the philosophers simultaneously look at the chopsticks, and see that they are free (leftchopstick.isFree() && rightchopstick.isFree()),
All of the philosophers simultaneously grab their left chopstick,
Each of them now is stuck, waiting for his neighbor to the right to put down his their right (the neighbor's left) chopstick.

Problem 2: The condition that no chopstick is free is insufficient to prove a deadlock. Two philosophers could be eating at the same time (i.e., four chopsticks in-use) while a third philosopher is holding the fifth chopstick in his left hand, waiting for the right-hand neighbor to put chopsticks down. None of the five chopsticks is free in that case, but the two philosophers who are eating eventually will finish, and put their chopsticks down, and the program will continue to run...
...Or, at least, it would have done if your main thread had not declared a deadlock, and aborted the program.

Both of the problems that I've highlighted here have the same root: You appear to believe that the testing and acquiring of chopsticks happens _atomically.
if(leftchopstick.isFree() & rightchopstick.isFree() ) {
    leftchopstick.grab();
    rightchopstick.grab();
    ...
}

That is to say, You seem to think that no other philosopher can act while one philosopher is looking at chopsticks and picking them up. But that isn't true:  After philosopher P has seen that their left chopstick is free, the neighbor to the left could pick it up while P is looking to the right. After P has decided that both are free, the left neighbor still could win the race to pick up the left chopstick, and even if leftchopstick.grab() succeeds, the neigbor to the right still could win the race to grab the other one.
Comment: I see, do you have any solutiont to make this puzzle deadlock free?


From EJB 2.0 to EJB 3.0

Question: Here Is the code that I have to create an EJB 2.0
How can I convert this so can be used for EJB 3.0
java.lang.Object ejbHomeStub = initCtx.lookup(ejbJNDIName);
EJBHome ejbHome = (EJBHome)
    javax.rmi.PortableRemoteObject.narrow(ejbHomeStub, EJBHome.class);
EJBMetaData ejbMetaData = ejbHome.getEJBMetaData();
Class ejbHomeClass = ejbMetaData.getHomeInterfaceClass();
//get ejb object of home interface type
ejbHome = (EJBHome) javax.rmi.PortableRemoteObject.narrow(ejbHome, ejbHomeClass);
//create ejb remote object
Method ejbMethodCreate = ejbHomeClass.getDeclaredMethod(EJB_CREATE, null);
ejbRemoteObj = (EJBObject) ejbMethodCreate.invoke(ejbHome, null);

Comment: See http://www.javaworld.com/javaworld/jw-08-2006/jw-0814-ejb.html
Comment: I appreciate the reply, I have reviewd that article before but my question is a little bit more speciffic. How can I create the ejbRemoteObj in a **generic** way withotu using the home since it is gone in EJB3
Answer: If you mean "how do I add EJB 3.0 interfaces to my EJB 2.0 JARs", then you don't need to convert the client or bean since EJB 3.0 is backwards compatible with EJB 2.0.  Instead, just update ejb-jar.xml to remove the XSD, add XSD+xmlns, and update the version attribute of <ejb-jar/>.
If you mean "how do I convert this to annotations", then use the @RemoteHome annotation on the bean class, and keep your interfaces the same.
If you mean "how do I convert the EJB to use business interface instead of homes", then you can't do that directly, since you have to know the type of the business interface a priori:
java.lang.Object businessObjectStub = initCtx.lookup(ejbJNDIName);
BusinessObject businessObject = (BusinessObject)
    javax.rmi.PortableRemoteObject.narrow(businessObjectStub, BusinessObject.class);

(Some application servers do not require a narrow for EJB 3.0, but WebSphere Application Server 7.0 does.)
Comment: Thank you for the reply. I meant the third suggestion that you had. I am calling different beans from a servlet. we used to specify the ejbJNDIName (as it shown in my code. And the code is generic so it could handle any type of bean with a home interface. But EJB3 do not have a home interface. I do not want to create one because it kills all the purpose of having EJB3. I am just trying to figure it out how to do the "generic" call without specifying the BusinessObject
Comment: I would say the greatest benefit of EJB 3 is annotations, not the remove of home interfaces.  In any case, I don't know how to do the equivalent on WebSphere Application Server 7.0.

From EJB 2.0 to EJB 3.0


How to output content type title on page.tpl.php?

Question: So I am using this code to output nodes title:
<?php print render($title_prefix); ?>
<?php if ($title): ?>
<?php print $title; ?>
<?php endif; ?>
<?php print render($title_suffix); ?>

What code do I need to output the content type's name (i.e. content type is Article, so output 'Article' inside each Article content type node page next to node title, above or below it)?
Comment: @AyeshK yes you do: http://drupal.stackexchange.com/questions/6626/is-node-always-available-in-page-tpl-php
Comment: You don't have a $node in page.tpl.php
Answer: In D7 there is node_type_get_name
node_type_get_name($node)

Parameters

$node: A node object or string that indicates the node type to return

Return value

The node type name or FALSE if the node type is not found.
Comment: This shoud be used in addition to the check isset($node) to avoid notices from PHP
Answer: You can access the $node object in page.tpl.php typically, as long as a $node object exists (i.e. you are on a node page). So you can use:
if (isset($node)) {
  // do something with $node
}

If you want to inspect $node (or anything else for that matter), you can use Devel module. When installed and enabled, it provides a function, dpm(), that will let you inspect arrays, objects, etc. as long as you are logged in as a user with permissions to view it. so dpm($node) will allow you to inspect the $node object.
The value closest to what you want is probably $node->type, but as MPD pointed out, that will give you a machine name, with spaces converted to underscores.
If you want to do it without writing any code, your best option is probably to use Views or Panels to pull that value and display it.
If you don't want to use those, here's how you would do it with a block:

Create a block for the content type you want to display.
Make the content "My Content Type Name" or whatever.
Set the block to display in whatever region you want.
Set the block to only display on content of "My Content Type Name".
Save the block.
Comment: http://php.net/print
Comment: $node->type is just the machine name, not the pretty name
Comment: Thanks for helping, but like I mentioned, I am a beginner and I have no experience on PHP at all. All I know is how to paste in code to template.php and etc. I am a designer - not a programmer, sadly. So I am pretty much not sure what to write in.
Answer: If article is your content type machine name ,
<?php
if($node_details->type == 'article'){
   print 'Article or $node_details->type';
 }
?>

it will print your content type name in all of is node.Print this in you page.tpl before print $content so that you can print it before the node title.
Comment: if you don't know the machine name of your content type, simply print the $node_details = node_load(arg(1)); and get the value of $node_details->type, this is the machine name of your content type .
Comment: `$node->type` will give you the machine name faster. If the thing being viewed is a node, you will have access to the `$node` object.


WPF: Visual studio like error buttons

Question: I want to get this.
buttons http://www.shrani.si/f/X/6Y/24Jhn9D3/buttns.png
Everything works so far, buttons act as filter and are bind to the grid control.
All i want is the icons and counter on the button.
Whats the correct way of implementing those?
<code><ToggleButton x:Name="IsErrorShown" Margin="4" Width="100" Content="{lex:LocText Errors, Assembly=Client}">
</code>
I have tried adding image like this:
<code>            <ToggleButton x:Name="IsErrorShown" Margin="4" Width="100" Content="{lex:LocText Errors, Assembly=Client}">
            <StackPanel>
                <Image Source="Resources/Warning"/>
            </StackPanel>
        </ToggleButton>
</code>
but i get error that prop. Content is defined more then once.
Answer: A WPF Button (or ToggleButton) is a content control, into which you can put anything.
I haven't checked, but these buttons probably have a horizontal stack panel or a DockPanel, with an Image and then one or two TextBlocks.   You could make a template for these, and also use binding to set the TextBlock Text content from your viewmodel.
Snoop ( http://snoopwpf.codeplex.com/ ) is a great tool for finding out how other people have built things in WPF.
The Adam Nathan WPF book is excellent, and if you don't have it you should get it.   http://www.amazon.co.uk/Windows-Presentation-Foundation-Unleashed-WPF/dp/0672328917
Here's an example:
<code>  <ToggleButton Height="24" Width="100">
    <DockPanel>
      <Image Source="c:\\temp\\me.jpg" Margin="3"/>
      <TextBlock Text="20 Errors"/>
    </DockPanel>
  </ToggleButton>
</code>
Comment: I added an example.  Don't forget to vote-up stuff you like, otherwise your teeth will fall out and you'll be covered in boils.
Comment: thanx for your reply. I forgot to mention i have togglebuttons, and since im abit in a hurry i havent got the time to read the entire book. Well, i am going to, i just have to push this problem first.

WPF: Visual studio like error buttons


How to filter Date Views with correctly timezone

Question: I am using latest Drupal 8.2.5 for Live-score website. I have the Views for display all games daily. It's including DateTime for schedule and storing on Europe/London timezone (by default).
On the views FILTER CRITERIA, I added Match_Date_Fields between:

Today
+1 day

For getting the matchs from today events and next events.
So, the views will filter by default timezone (london), sure. But when the visitor access to my site from Thailand. This filter seem to wrong. Because here difference between timezone from London to Thailand.
For example: The game is play on "January 15, 2017 19:45" for London timezone, but from Thailand it's "January 16, 2017 02:45".
I made it successfully print with depends on the local's time zone. But have no idea How to filter with correctly local's timezone?
Answer: Ok, I made it working.
My solution is created a custom drupal 8 module with the file: .views_execution.inc inside your module folder.
Inside that, I added function modulename_views_query_alter($view, $query) with:
<code>//Filter by timezone for bettingsafe's local ip
switch ($view->element['#name']){
    case 'league_match':
        $key = 0;
        foreach ($query->where as $key => $value){
            $key_2 = 0;
            foreach ($value['conditions'] as $key2 => $condition){
                $length = strlen('DATE_FORMAT');
                if (substr($condition['field'], 0, $length) === 'DATE_FORMAT'){
                    $condition['field'] = str_replace('DATE_FORMAT(<date field>', 'DATE_FORMAT(CONVERT_TZ(<date field>, <from timezone>, <to timezone>')', $condition['field']);
                    $query->where[$key]['conditions'][$key_2]['field'] = $condition['field'];
                }
                $key_2+=1;
            }
            $key+=1;
        }
    break;
}
</code>
From my server Centos, I install the tool CONVERT_TZ:
<code>shell> mysql_tzinfo_to_sql /usr/share/zoneinfo | mysql -u root mysql -p<sql root's password>
</code>
Restart mysqld and clear Drupal cache.
Hope that's will help someone.


Prove that the sequence ${{a_n}}$ converges.

Question: It's given that:
$$a_{n+1}=\int_{0}^{a_n} \sin^4(t^2) dt%$  $$
$$a_1=1$$
In order to prove that ${a_n}$ Converges I thought about showing that the sequence is monotonic (Increasing or Decreasing) and also that it is bounded
(from above or below).
this is a graph of the function $f(x)=\sin^4(x)$ and we can deduce that  $f(x)=\sin^4(t^2) \le 1.$

Monotonicity: I chose Induction method to show that the sequence is monotinic. by substituting $n=1$ :
$a_{2}=\int_{0}^{1} \sin^4(t^2) dt%$
($a_2$ must be positive because it describes the area below the function in                              the interval $[0,1]$.)
$a_2$ describes an area that is surely less than $1$, and we can be sure by the graph.
$a_{3}=\int_{0}^{a_2} \sin^4(t^2) dt%$

its obvious that $a_3$'s area is less that $a_2$ and so on, this means that the sequence is monotonic decreasing. and it must be decreasing to zero.

bounded series: also I want to show this by induction.

do you guys have any hints how to prove both things by induction?
Answer: Since $\sin^4 x\le x^4$ and thus
$$
0\le a_{n+1}\le\int_0^{a_n}t^8\,dt=\frac19a_n^9
$$
one gets the estimate
$$
0\le a_{n}\le \sqrt[4]{3}\left(\frac{a_1}{\sqrt[4]3}\right)^{9^{n-1}}.
$$
By the sandwich lemma, the limit is $0$.
Comment: Nice solution :) +1
Comment: elegant in its simplicity
Answer: We have $$0\leq a_{2}=\int_{0}^{1}\sin^{4}\left(t^{2}\right)dt\leq\int_{0}^{1}dt\leq1
 $$ then if we consider $$0\leq a_{n+1}=\int_{0}^{a_{n}}\sin^{4}\left(t^{2}\right)dt\leq a_{n}\leq1
 $$ so the sequence is bounded, non negative and monotone decreasing.


Drupal Form API Callback For Displaying a Table on the Same Page

Question: I'm at an absolute loss as to how display a table and a form on the same page.
My objective is to publish information comparing our user data with our billing gateways data. My first thought was to create a dummy form item that can have it's values replaced by the submit handler akin to this Table and Form in the same page but that didn't appear to work with my callback.
My next attempt was to create a embedded form that upon a successful submission callback replaced information in the original render array. The idea of the code is to publish the 'one' in all the values before the submit button is called and 'two' after it is called. Here is that code:
function test_lookup_page($email = NULL){
    $hinput = array('One Customer Information' => 'aci', 'Two Customer Information' => 'uci');

    $header = array(
        'Legend' => array(
          'data'  => t('Legend'),
          'id'    => 'head-legend',
          'class' => 'col-legend',
        ),
      );

    foreach ($hinput as $hkey => $hvalue){

         $ckey[$hkey] = array(
          'data' => $hkey,
          'id'    => 'head-' . $hvalue,
          'class' => 'col-' . $hvalue,
        );
    $header = array_merge($header, $ckey);
    }

      // Table rows
      $rows = array(
        array(
          // Column 1
            'customer' => array(
            'data'  => t('Customer Account'),
            'id'    => 'row1-legend',
            'class' => 'col-legend',
          ),
            'One Customer Information' => array(
            'data' => 'first',
            'id' => 'row1-aci',
            'class' => 'col-aci',
          ),
            'Two Customer Information' => array(
            'data' => 'first',
            'id' => 'row1-uci',
            'class' => 'col-uci',
          ),
        ),
          array(
          // Column 2
          'billing' => array(
            'data'  => t('Billing'),
            'id'    => 'row2-legend',
            'class' => 'col-legend',
          ),
            'One Customer Information' => array(
            'data' => 'first',
            'id' => 'row2-aci',
            'class' => 'col-aci',
          ),
            'Two Customer Information' => array(
            'data' => 'first',
            'id' => 'row2-uci',
            'class' => 'col-uci',
          ),
        ),
          array(
          // Column 3
          'shipping' => array(
            'data'  => t('Shipping'),
            'id'    => 'row3-legend',
            'class' => 'col-legend',
          ),
            'One Customer Information' => array(
            'data' => 'first',
            'id' => 'row3-aci',
            'class' => 'col-aci',
          ),
            'Two Customer Information' => array(
            'data' => 'first',
            'id' => 'row3-uci',
            'class' => 'col-uci',
          ),
        ),
        array(
          // Column 1
          'subscription' => array(
            'data'  => t('Subscription(s)'),
            'id'    => 'row4-legend',
            'class' => 'col-legend',
          ),
          'One Customer Information' => array(
            'data' => 'first',
            'id' => 'row4-aci',
            'class' => 'col-aci',
          ),
            'Two Customer Information' => array(
            'data' => 'first',
            'id' => 'row4-uci',
            'class' => 'col-uci',
          ),
        ),

      );

        $build = array(
        'header_text' => array(
          '#type' => 'markup',
          '#markup' => '
' . t('To add additional content to a form page, you can use a page callback and return a render array like this.') . '
',
            '#theme' => 'table',
            '#header' => $header,
            '#rows' => $rows,
        ),

        'test_order_admin_form' => drupal_get_form('test_order_admin_settings', $email),

      );
      return $build;
    }

  function test_order_admin_settings($form, &$form_state, $email = NULL) {

$form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Submit',
    '#submit' => array('test_order_lookup'),
);

return ($form);

}
  function test_order_lookup($form, &$form_state) {

     $hinput = array('One Customer Information' => 'aci', 'Two Customer Information' => 'uci');

     $header = array(
      'Legend' => array(
        'data'  => t('Legend'),
        'id'    => 'head-legend',
        'class' => 'col-legend',
      ),
    );

     foreach ($hinput as $hkey => $hvalue){

       $ckey[$hkey] = array(
        'data' => $hkey,
        'id'    => 'head-' . $hvalue,
        'class' => 'col-' . $hvalue,
      );
      $header = array_merge($header, $ckey);
   }

// Table rows
        $rows = array(
        array(
          // Column 1
            'customer' => array(
            'data'  => t('Customer Account'),
            'id'    => 'row1-legend',
            'class' => 'col-legend',
          ),
            'One Customer Information' => array(
            'data' => 'second',
            'id' => 'row1-aci',
            'class' => 'col-aci',
          ),
            'Two Customer Information' => array(
            'data' => 'second',
            'id' => 'row1-uci',
            'class' => 'col-uci',
          ),
        ),
          array(
          // Column 2
          'billing' => array(
            'data'  => t('Billing'),
            'id'    => 'row2-legend',
            'class' => 'col-legend',
          ),
            'One Customer Information' => array(
            'data' => 'second',
            'id' => 'row2-aci',
            'class' => 'col-aci',
          ),
            'Two Customer Information' => array(
            'data' => 'second',
            'id' => 'row2-uci',
            'class' => 'col-uci',
          ),
        ),
          array(
          // Column 3
          'shipping' => array(
            'data'  => t('Shipping'),
            'id'    => 'row3-legend',
            'class' => 'col-legend',
          ),
            'One Customer Information' => array(
            'data' => 'second',
            'id' => 'row3-aci',
            'class' => 'col-aci',
          ),
            'Two Customer Information' => array(
            'data' => 'second',
            'id' => 'row3-uci',
            'class' => 'col-uci',
          ),
        ),
         array(
          // Column 1
          'subscription' => array(
            'data'  => t('Subscription(s)'),
            'id'    => 'row4-legend',
            'class' => 'col-legend',
          ),
          'One Customer Information' => array(
            'data' => 'second',
            'id' => 'row4-aci',
            'class' => 'col-aci',
          ),
            'Two Customer Information' => array(
            'data' => 'second',
            'id' => 'row4-uci',
            'class' => 'col-uci',
          ),
        ),

      );

        $build = array(
        'header_text' => array(
            '#theme' => 'table',
            '#header' => $header,
            '#rows' => $rows,
        ),

      );

       return ($build);

       }

Answer: The submit handler isn't the right place to build a display, the core form builder functions don't actually assign the return value to anything so it's essentially ignored.
The normal process for this sort of thing is to set $form_state['rebuild'] = TRUE in your submit handler, generate the table and add it back on to the $form_state, and then let the form builder function decide what to display depending on the existence of that value.
This is a skeleton example which should help:
function MYMODULE_some_form($form, &$form_state) {
  if (isset($form_state['table'])) {
    $form['table'] = $form_state['table'];
  }
  else {
    // Otherwise build the form as normal
    $form['some_field'] = array(
      '#type' => 'textfield',
      // etc...
    );
  }

  return $form;
}

function MYMODULE_some_form_submit($form, &$form_state) {
  $form_state['table'] = function_to_generate_table($form_state);
  $form_state['rebuild'] = TRUE;
}

There are various different permutations of that (depending on where you want to build the table based on the form state values; it could be the submit handler, form function or a helper function), just put your code wherever you feel most comfortable with it.
Comment: You're welcome, glad I can help so much :)
Comment: Thank you so much for your answer @Clive, I don't know what drupal.stackexchange.com would be without you. I really really appreciate how many things I've learned from you.


dotnet restore not copying NETStandard.Library and other framework packages

Question: I have a PC which is not allowed to connect to any network. I need to work on this PC on a Net Standard project. I worked in this scenario before with Net Framework projects just using the nuget.exe options to save packages to a folder, copying the folder to the isolated PC and using nuget to restore packages from that folder.
But doing this with a Net Standard project using dotnet restore mechanism fails because there are missing packages like NETStandard.Library.
The command I used to create the offline package folder is:
dotnet restore solution.sln --packages offline_cache

And after copying the folder to the isolated machine I use:
dotnet restore solution.sln --source offline_cache

Answer: Sounds like you want to be running dotnet publish https://learn.microsoft.com/en-us/dotnet/core/tools/dotnet-publish
Note that if you are using PackageReferences then nuget restore will only install the dependencies in your global cache, not copy them locally https://learn.microsoft.com/en-us/nuget/consume-packages/package-restore


não permitir selecionar domingos com PHP

Question: Estou a escrever um formulário em html e php para que o utilizador possa escolher uma data para marcar, no entanto não queria que o utilizador escolhesse domingos.
 <input type="datetime-local" id="datetime" name="datetime" value="<?php echo $current_date; ?>" min="<?php echo $current_date; ?>T10:00" max="T17:30" step="900" required>

como poderia fazer isso?
Answer: Infelizmente, não é possível restringir diretamente a escolha de dias específicos com o elemento HTML "datetime-local".
Aqui esta uma solução que pode solucionar esse problema
Como seu input esta dentro de um formulário, você pode usar $_POST['submit'] é uma variável associativa do PHP que representa o valor do botão de envio de um formulário HTML.
Depois você pode usar a função date do PHP para verificar o dia da semana do valor escolhido pelo usuário e validar se não é domingo.
exemplo
if (isset($_POST['submit'])) { //verifica se o formulario foi enviado
    $selectedDate = $_POST['datetime'];
    $dayOfWeek = date('w', strtotime($selectedDate));

    if ($dayOfWeek == 0) {
        echo '';
    } else {
        // Processar o formulário
    }
}

Na variavel $dayOfWeek esta sendo para validar o dia da semana 0 para domingo, 1 para segunda-feira, etc...
Comment: usei javascript e o flatpickr e depois nas configuraçoes do mesmo usei um função dentro do disable e funcionou, obrigada na mesma!


Usar VBA no excel para buscar dados em arquivos .docm localizados em subdiretorios

Question: Bom dia,
Estou com seguinte problema em um código VBA que utilizo no Excel para puxar dados de formulários criados no Word.
Se os arquivos .docm estiverem dentro da mesma pasta eu consigo puxar todos os dados que necessito dos formulários sem problema, o problema é que o número de arquivos ficou mt grande e foi necessário separa-los em subdiretórios para uma melhor organização.
Segue abaixo meu código:
Sub getWordFormData()
    Dim wdApp As Object, myDoc As Object
    Dim myFolder As String, strFile As String
    Dim i As Long, j As Long
    myFolder = ThisWorkbook.Path & "\"

    If Len(Dir(myFolder)) = 0 Then
        MsgBox myFolder & vbCrLf & "Not Found", vbInformation, "Cancelled - getWordFormData"
        Exit Sub
    End If

    Application.ScreenUpdating = False
    Set wdApp = CreateObject("Word.Application")

    With ActiveSheet
        .Cells.Clear
        With .Range("A1:F1")
            .Value = Array("Nome", "NIS", "CPF", "Endereço", "CEP", "Bairro")
            .Font.Bold = True
        End With

        strFile = Dir(myFolder & "\*.docm", vbNormal)
        i = 1

        While strFile <> ""
            i = i + 1

            On Error Resume Next

            Set myDoc = wdApp.Documents.Open(Filename:=myFolder & "\" & strFile, ReadOnly:=True, AddToRecentFiles:=False, Visible:=False)

            .Cells(i, 1).Value = myDoc.txtNome.Text
            .Cells(i, 2).Value = myDoc.txtNis.Text
            .Cells(i, 3).Value = myDoc.txtCpf.Text
            .Cells(i, 4).Value = myDoc.txtEnd.Text
            .Cells(i, 5).Value = myDoc.txtCep.Text
            .Cells(i, 6).Value = myDoc.Combobox1.Value

            myDoc.Close SaveChanges:=False
            strFile = Dir()
        Wend

        wdApp.Quit
        Application.ScreenUpdating = True

    End With

End Sub

Existe alguma forma de modificar este código para que ele consiga buscar os dados dos formulários .docm que estão dentro dos subdiretórios?
Edit
Exemplo: Tenho a pasta do mês de junho e dentro dela tenho 50 pastas cada uma com um formulário .docm, queria executar o excel de dentro da pasta junho e pegar os dados dos formulários que estão dentro dos subdiretórios.
Desde já muito obrigado!!!
Comment: Mude o caminho do diretório? `myFolder = ThisWorkbook.Path & "\"` para `myFolder = ThisWorkbook.Path & "\Subdiretorio\"`, em que `ThisWorkbook.Path` é o caminho do arquivo Excel. Ou você pode adicionar uma variável de subdiretório, em que é possível escolher qual pasta é escolhida. Ou digitando manualmente, ou com um combobox
Comment: Bom dia, obrigado pela sugestão. Mas o que preciso seria que o código buscasse dentro de diversos subdiretórios automaticamente. Por exemplo: Tenho a pasta do mês de junho e dentro dela tenho 50 pastas cada uma com um formulário .docm, queria executar o excel de dentro da pasta junho e pegar os dados dos formulários de dentro dos subdiretórios. Deu pra entender?
Answer: Há várias maneiras de contornar este problema, duas delas são:

O usuário escolhe a subpasta;
Você recebe os dados de todas as Subpastas.

Escolher a subpasta
Um código de exemplo de como escolher a pasta desejada, utilizando o FileDialog, então myFolder seria alterado para:
    Dim fso As Object
    Dim myFolder As String

    Set fso = CreateObject("Scripting.FileSystemObject")
    With Application.FileDialog(msoFileDialogFolderPicker)
        .Title = "Escolha a pasta"
        .Show
    End With
    On Error Resume Next
    myFolder = Application.FileDialog(msoFileDialogFolderPicker).SelectedItems(1) & "\"

    If myFolder = "" Then
        GoTo CleanExit                           'Se a pasta estiver vazia
    End If

    'Seu código aqui

CleanExit:

    Set fso = Nothing

Dados de todas as subpastas
Ou os dados de todas as subpastas podem ser obtidos com a seguinte função em um módulo:
Option Explicit
Public myFolder As String
Sub teste()
    Dim subpastas As Variant

    subpastas = Listar_Subpastas

    For i = LBound(subpastas) To UBound(subpastas)
        Debug.Print subpastas(i)
    Next i
End Sub

Public Function Listar_Subpastas() As Variant
    ''''''''''''''''''''
    '==== Arquivos ===='
    ''''''''''''''''''''
    Application.Calculation = xlCalculationManual
    Application.ScreenUpdating = False
    Application.EnableEvents = False
    Dim xPath As String
    Dim xWs As Worksheet
    Dim fso As Object, folder1 As Object
    Dim ncell As Long
    Dim fso_FOLDER As Object
    Dim fso_FILE As Object
    Dim vaArray     As Variant
    Dim i As Long, j As Long

    Set fso = CreateObject("Scripting.FileSystemObject")
    On Error Resume Next
    xPath = ThisWorkbook.Path & "\"
    Set fso_FOLDER = fso.GetFolder(xPath)

    If xPath = "" Then
        GoTo CleanExit                           'Se a pasta estiver vazia
    End If

    'https://stackoverflow.com/a/31428399/7690982
    'Encontra todos os Arquivos
    ReDim vaArray(1 To fso_FOLDER.Subfolders.Count)
    i = 1
    If fso_FOLDER.Files.Count > 0 Then
        ''Loop through each SubFolder in Folder
        For Each fso_FILE In fso_FOLDER.Subfolders
            vaArray(i) = fso_FILE
            i = i + 1
        Next fso_FILE
    Else
        MsgBox "Nenhuma subpasta encontrada em " & xPath
    End If

    'For i = LBound(vaArray) To UBound(vaArray)
    '    Debug.Print vaArray(i)
    'Next i

    Listar_Subpastas = vaArray

    'Sair do código
CleanExit:

    Set fso = Nothing
    Set fso_FOLDER = Nothing
    Application.Calculation = xlCalculationAutomatic
    Application.ScreenUpdating = True
    Application.EnableEvents = True
End Function

Ou um código pode ser realizado para ao invés de obter as subpastas do mesmo caminho que o arquivo Excel, o usuário possa selecionar a pasta principal.
E uma ComboBox ComboBox1 pode ser criada em um formulário Userform1 com as subpastas. Então um botão pode ser criado para atribuir o caminho da subpasta desejada em uma variável global, no caso do exemplo myFolder:

E o código do formulário para preencher a ComboBox e o botão:
Private Sub CommandButton1_Click()
    myFolder= ComboBox1.Value
    Unload Me
End Sub

Private Sub UserForm_Initialize()
    Dim subpastas As Variant
    Dim i As Long
    With ComboBox1
        .Clear
        subpastas = Listar_Subpastas

        For i = LBound(subpastas) To UBound(subpastas)
            .AddItem subpastas(i)
        Next i
    End With
End Sub

Comment: Obrigado pela resposta. Desculpe a minha ignorância, mas essa e apenas a terceira vez que lido com VBA e não tenho muito conhecimento. Poderia me indicar como faria pra aplicar sua segunda opção "Dados de todas as subpastas" juntamente com o código que coloquei na pergunta? Tentei de diversas formas e não obtive sucesso. Consigo ver a lista com as subpastas mas não consigo puxar os dados dos .docm que estão dentro delas pra planilha. Muito obrigado novamente!!!
Comment: @FabricioAndrade Editei a resposta, você utiliza a variável global `myFolder` no Userform. E deleta no seu código a linha `myFolder = ThisWorkbook.Path & "\"`. Ou substitui a variável `myFolder` pela variável global com o Subdiretório desejado.
Comment: Muito obrigado estou conseguindo desenvolver o que queria com suas dicas. Agora se não for pedir demais, teria como, usando o FileDialog selecionar varias pastas de uma vez ou selecionar uma e ele pegar todas as subpastas? Achei como fazer com arquivos mas não com pastas. Obrigado novamente!!!
Comment: @FabricioAndrade Crie outra pergunta sobre isso, se não a resposta começa a ficar muito grande e foge da sua dúvida inicial. Pois este é um site de Q & A, para ajudar outras pessoas com a mesma dúvida no futuro.


online retail data time series model using R

Question: I am new to time-series modeling. I have to create a time-series from the data found at https://archive.ics.uci.edu/ml/datasets/Online+Retail. I have figured out how to aggregate the data, so now I have the data in following format with total revenue for each day. What would be best way to construct time series using R function ts() from this to forecast monthly or daily sales?
Comment: Given the revision, this seems a better fit for SO.
Answer: Usually what is done with transaction data is indeed aggregating.

Define your target and time horizons: What do you want predict exactly? Sales of the next day given all previous days? Sales of the next month given only the previous 12 months? Sales at each hour of the day?
Build an aggregated dataset: Aggregate sales for each day or month or other timespan depending on what you decided earlier.
Apply suitable model: Depending on how you aggregate the data it can be fed to a ARIMA (e.g. if you make it such that 1 record = 1 day) directly or into a linear regression (e.g. if 1 record = aggregation of previous $N$ days) or other models.
Comment: The prediction I am trying to make is sales for next month. I aggregated the data as sales for each day. So, the new data has the dates in one column in the format 2012-12-01 and total sales for that day in another column say 50000.50. How do I construct a time series from this using ts() to apply models?


Why could the fumble in the Browns/Jets game not be advanced?

Question: In the game between the Cleveland Browns and the New York Jets on 12/27/2020, Baker Mayfield fumbled on the final Cleveland posession, at 1:25 remaining.
The ball was fumbled during an attempted quarterback sneak on fourth and 1.  The ball was recovered by Kareem Hunt and subsequently advanced beyond the line of scrimmage; however, the referees ruled that the ball was down at the point that Hunt recovered the fumble, as he was not allowed to advance the fumble.
Why was he not allowed to advance the fumble?  I understand the rule to only apply to forward fumbles; as this appears to have been a fumble backwards, why was this rule enforced?
Comment: If you are interested in the part I left out in my edit - the idea of how rule enforcement might change over time (the idea of a "precedent"), you might want to ask that separately, as a question that's not related to this exact thing; that's an interesting question, and not one really related to this but still interesting.
Answer: Two different rules could actually apply here, and neither mentions "forward" fumbles being advanceable anywhere in the current rulebook.
First is the rule for Fourth Down Fumbles, Rule 8.7.5:

If a fourth-down fumble occurs during a play from scrimmage:

(c) If the recovery or catch is by a teammate of the player who fumbled, the ball is dead, and the spot of the next snap is the spot of the fumble, or the spot of the recovery if the spot of the recovery is behind the spot of the fumble.

And then there is the rule for Fumble after the Two-Minute Warning:

If a fumble by either team occurs after the two-minute warning:

(c) If the recovery or catch is by a teammate of the player who fumbled, the ball is dead, and the spot of the next snap is the spot of the fumble, or the spot of the recovery if the spot of the recovery is behind the spot of the fumble.

Both would apply to this down (which was on 4th and 1, after the two-minute warning for the second half).
You are most likely confused due to the wording - as there are two different potential spots depending on if the fumble is recovered behind or forward from the spot of the fumble.  Once Mayfield fumbled, there were two possibilities of where the ball might be spotted, unless Mayfield recovered his own fumble:

The spot Mayfield fumbled (~1 yard behind the line to gain)
The spot the ball was recovered, if that spot is behind the point Mayfield was at when he fumbled

No other result would have been possible, unless Mayfield recovered his own fumble.  This has been the case for decades - since 1978, when the rule was introduced.  This article by Football Zebras explains that in some detail.  Note that the ball is dead immediately upon recovery by any other player than the original ball carrier - similar to a punt being touched by the punting team.  Once Hunt recovered the ball (and had possession), the play was over, and nothing else could occur (for either team).
Comment: Thank you sir for your time and knowledge. So it is safe to assume that a center snaps the ball and it is fumbled during the snap ,that only the center himself can advance the ball correct ? If the QB picks up the ball, he can not throw it, or hand it off because the ball is dead correct ?
Comment: @DavidCarelli I think that might be a different question, unless you're suggesting this particular play involved an aborted snap.  I think I know the answer to it, but don't actually see any clear evidence that I'm correct; hopefully someone else will, if you ask it as a separate question.
Comment: (And to be clear, I'm pretty sure there's a difference between a "butt fumble" like in the classic Jets game, and a center snapping the ball over someone's head or similar; if the QB took possession of the ball, even to bobble it, he's the fumbler.)
Answer: This is a 2 parter. First part will be the rule enforcing the call, second will be the reason behind the rule.
There is a special rule surrounding fumbles after the 2 minute warning of either half. Article 6. Fumble After Two-Minute Warning of the NFL rulebook states:

If a fumble by either team occurs after the two-minute warning:
a) The ball may be advanced by any opponent.
b) The player who fumbled is the only player of his team who is permitted to recover and advance the ball.
c) If the recovery or catch is by a teammate of the player who fumbled, the ball is dead, and the spot of the next snap is the spot of the fumble, or the spot of the recovery if the spot of the recovery is behind the spot of the fumble.
Note: The restrictions in (b) and (c) are applicable during a Try throughout the game.

So when Kareem Hunt recovered the ball, the ball was called dead since he was not the original fumbler.
[Second Part] Now we get to the more interesting question, why is there such a rule? The answer is the The Holly Roller, you can see the play here:

 The 1978 Raiders fumbled their way to victory in a game trailing by six and 10 second left. Their QB Ken Stabler intentionally fumbled the ball right before getting sacked. You can see #40 also intentionally throwing the ball towards the endzone instead of taking the possession where it ends up getting scored by Raiders and giving them the win. Although the play was legal, it was clearly a loophole in the NFL rules, which was patched by the above rule in that immediate off season.


In how many ways can a salesperson visit $15$ different offices during the week?

Question: Consider the following question:

I am able to get the answer matched in the book for the part a and b but not part c.
I tried part a as:
Factorial[15]

1,307,674,368,000

Part b as:
FactorialPower[15,4]

32,760

But can't get the book's answer for part c. Please help.
The book is saying the answer to part c should be:

13,650
Comment: If she must visit $15$ different offices over those five days, the answer is simply $15!$.  If she is allowed to visit the same office on more than one day, calculate the number of ways she can visit three of the fifteen offices on any given day, then multiply the results.
Answer: The book says that you do $\text{FactorialPower}[15,3]*5$. It is a little strange of an answer. It seems like the question is asking how many ways can you visit three different offices on a single day if the day can be any weekday.
Answer: So, just to recap:
A) The ways in which to visit the 15 offices is to choose 1 of the 15, then 1 of the 14, then.... 15!
B) To only visit 4 on Monday, choose 1 of the 15, then 1 of the 14, then 1 of the 13, then 1 of the 12.... 15!/11!
C) Given what you reported the answer to be I'm assuming you don't have to visit all 15 offices, just any 3 different ones on a given day. By that logic, on 1 day it would take you 15!/12! ways to visit 3 offices on Monday. With 5 days in the week, it would have 5*(15!/12!) ways in which to visit 3 offices each day.
Edit I think Stacker beat me to it.


For the equation $x^3 -y^3 + x-y=0$, how many real functions on $-\infty <x < \infty$ does this equation define?

Question: I'm able to factor the equation $x^3-y^3+x-y=0$ to $(x-y)(x^2 + y^2 + xy + 1)=0$ to  get that the only factor of the equation is $y=x$. But, I'm also told that there is one function, namely $f(x) = x$, that the equation defines. I'm kind of confused about what this is supposed to mean. Are we defining a function such that every $x \in (-\infty, \infty)$ is mapped to $0$ by  $g(x) = x^3-y^3+x-y$?
Comment: Isn't $f(x)=x$ really just same as $y=x$ [i.e. $y-x=0$] in another notation?
Comment: The equation says $x^3 + x = y^3 + y$.
Answer: Because for any real numbers $x,y$,
$$x^2+y^2+xy+1\ge \frac{1}{2}[(x+y)^2+x^2+y^2]+1\ge 1,$$
we know that
$$x^3-y^3+x-y=0\iff x-y=0.$$
Hence, the subset of $\mathbb{R}^2$ defined by the equation is exactly the line $y=x$. It is the graph of $f(x)=x$.


Pular Registro dentro de um while

Question: Gostaria de saber como é que eu pulo um registro dentro de um while?
Por exemplo, quando o tipo for 2 ele pula
while($pessoa = mysqli_fetch_object($query)){
  if($pessoa->tipo == 2){break;}
//continua a exibição de pessoa
}

Porém, ao executar isso ele para a execução de todo o while, como resolver?
Comment: Pode fazer algo como `if($pessoa->tipo != 2){ //executa todas ações...}` quando o tipo for 2 nenhum registro será exibido. Se precisar que apenas um registro do tipo 2 seja pulado adicione um flag para controlar isso.
Comment: Dá uma olhada:https://pt.stackoverflow.com/questions/207170/para-que-serve-o-controle-de-fluxo-continue
Answer: Usar o comando break irá quebrar o loop realmente. Para você continuar normalmente use o continue;
Ou seja..
while($pessoa = mysqli_fetch_object($query)){
  if($pessoa->tipo == 2)
    continue;
 //  não irá executar os comandos que tiverem após essa condição.
}

Comment: `if($pessoa->tipo != 2)`
Comment: No caso ele quer pular o 2, então deveria ser diferente, e não igual, se for igual, ele só vai continuar a ação quando o valor for 2
Comment: Ou isso ... mas cada tem sua opção.
Comment: Então testa primeiro e depois fala o resultado.
Answer: Só executa a condição se diferente de 2
 while($pessoa = mysqli_fetch_object($query)){
    if($pessoa->tipo != 2){
     //continua a exibição de pessoa
    }
 }

Answer: Pode montar uma lógica que 'exclua' os registro do tipo 2, pergutando na comparação o tipo é diferente de dois? Em código fica dessa forma:
while($pessoa = mysqli_fetch_object($query)){
  if($pessoa->tipo != 2){
    //executa todas as ações ... dos demais tipos
  }
}

Answer: Todas as respostas já satisfazem a sua necessidade, mas proponho ainda uma abordagem diferente:
while($pessoa = mysqli_fetch_object($query)){
  if( in_array($pessoa->tipo, array(/* 2,...outros valores que devem ser pulados*/) ) ){
    continue;
  }
}

Ou ainda
while($pessoa = mysqli_fetch_object($query)){
  if( ! in_array($pessoa->tipo, array(/* 2,...outros valores que devem ser pulados*/) ) ){
    /* Seu código */
  }
}

Desse modo acredito ficar um pouco mais fácil definir em quais registros (Se for mais de um) ele deve pular.
https://repl.it/IpE9
Answer: Se você quer ignorar o tipo de 2 completamente, seria ideal não obtê-los do banco de dados, usando por exemplo:
$query = "SELECT * FROM tabela WHERE tipo != 2";

Se o  2 é tipo máximo, pode usar o tipo < 2.
Dessa forma o mysqli_fetch_object irá obter apenas os valores onde o  tipo não é 2, sem necessidade de tratar isto no PHP.

Uma outra opção, diferente das demais, é utilizar o GOTO, alá jmp:
while($pessoa = mysqli_fetch_object($query)){

  if($pessoa->tipo === '2'){
     goto fim;
  }

  echo 'Você não é 2!';  // Executa o que tem que fazer.

  fim: // Se ele for `2` ele vem direto para cá. :D
}

Teste isto.

Pular Registro dentro de um while


Spring boot fails to start with Hibernate when there are lots of objects in DB

Question: My Spring boot version is 2.0.3
<code><parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.3.RELEASE</version>
    <relativePath /> <!-- lookup parent from repository -->
</parent>
</code>
When there are thousands of tables, indexes, sequences in the DB, the application  bootstrapping takes hours.
After some investigating, I find it's trying to retrieve database schema information when creating the EntityManagerFactory. Here are the 3 different callstacks during the initialization.
<code>            SequenceInformationExtractorLegacyImpl.extractMetadata(ExtractionContext) line: 46
        DatabaseInformationImpl.initializeSequences() line: 65
        DatabaseInformationImpl.<init>(ServiceRegistry, JdbcEnvironment, DdlTransactionIsolator, Namespace$Name) line: 59
        Helper.buildDatabaseInformation(ServiceRegistry, DdlTransactionIsolator, Namespace$Name) line: 132
        GroupedSchemaMigratorImpl(AbstractSchemaMigrator).doMigration(Metadata, ExecutionOptions, TargetDescriptor) line: 96
        SchemaManagementToolCoordinator.performDatabaseAction(Action, Metadata, SchemaManagementTool, ServiceRegistry, ExecutionOptions) line: 183
        SchemaManagementToolCoordinator.process(Metadata, ServiceRegistry, Map, DelayedDropRegistry) line: 72
        SessionFactoryImpl.<init>(MetadataImplementor, SessionFactoryOptions) line: 312
        SessionFactoryBuilderImpl.build() line: 462
        EntityManagerFactoryBuilderImpl.build() line: 892
        SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(PersistenceUnitInfo, Map) line: 57
        LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory() line: 365
        LocalContainerEntityManagerFactoryBean(AbstractEntityManagerFactoryBean).buildNativeEntityManagerFactory() line: 390
        LocalContainerEntityManagerFactoryBean(AbstractEntityManagerFactoryBean).afterPropertiesSet() line: 377
        LocalContainerEntityManagerFactoryBean.afterPropertiesSet() line: 341
        DefaultListableBeanFactory(AbstractAutowireCapableBeanFactory).invokeInitMethods(String, Object, RootBeanDefinition) line: 1767
        DefaultListableBeanFactory(AbstractAutowireCapableBeanFactory).initializeBean(String, Object, RootBeanDefinition) line: 1704
        DefaultListableBeanFactory(AbstractAutowireCapableBeanFactory).doCreateBean(String, RootBeanDefinition, Object[]) line: 581
        DefaultListableBeanFactory(AbstractAutowireCapableBeanFactory).createBean(String, RootBeanDefinition, Object[]) line: 503
        DefaultListableBeanFactory(AbstractBeanFactory).lambda$doGetBean$0(String, RootBeanDefinition, Object[]) line: 317
        214649627.getObject() line: not available
        DefaultListableBeanFactory(DefaultSingletonBeanRegistry).getSingleton(String, ObjectFactory<?>) line: 222
        DefaultListableBeanFactory(AbstractBeanFactory).doGetBean(String, Class<T>, Object[], boolean) line: 315
        DefaultListableBeanFactory(AbstractBeanFactory).getBean(String) line: 199
        AnnotationConfigServletWebServerApplicationContext(AbstractApplicationContext).getBean(String) line: 1089
        AnnotationConfigServletWebServerApplicationContext(AbstractApplicationContext).finishBeanFactoryInitialization(ConfigurableListableBeanFactory) line: 859
        AnnotationConfigServletWebServerApplicationContext(AbstractApplicationContext).refresh() line: 550
        AnnotationConfigServletWebServerApplicationContext(ServletWebServerApplicationContext).refresh() line: 140
        SpringApplication.refresh(ApplicationContext) line: 759
        SpringApplication.refreshContext(ConfigurableApplicationContext) line: 395
        SpringApplication.run(String...) line: 327

        InformationExtractorJdbcDatabaseMetaDataImpl.processTableResults(ResultSet) line: 393
        InformationExtractorJdbcDatabaseMetaDataImpl.getTables(Identifier, Identifier) line: 336
        DatabaseInformationImpl.getTablesInformation(Namespace) line: 120
        GroupedSchemaMigratorImpl.performTablesMigration(Metadata, DatabaseInformation, ExecutionOptions, Dialect, Formatter, Set<String>, boolean, boolean, Set<Identifier>, Namespace, GenerationTarget[]) line: 65
        GroupedSchemaMigratorImpl(AbstractSchemaMigrator).performMigration(Metadata, DatabaseInformation, ExecutionOptions, Dialect, GenerationTarget...) line: 207
        GroupedSchemaMigratorImpl(AbstractSchemaMigrator).doMigration(Metadata, ExecutionOptions, TargetDescriptor) line: 114
        SchemaManagementToolCoordinator.performDatabaseAction(Action, Metadata, SchemaManagementTool, ServiceRegistry, ExecutionOptions) line: 183
        SchemaManagementToolCoordinator.process(Metadata, ServiceRegistry, Map, DelayedDropRegistry) line: 72
        SessionFactoryImpl.<init>(MetadataImplementor, SessionFactoryOptions) line: 312
        SessionFactoryBuilderImpl.build() line: 462
        EntityManagerFactoryBuilderImpl.build() line: 892
        SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(PersistenceUnitInfo, Map) line: 57
        LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory() line: 365
        LocalContainerEntityManagerFactoryBean(AbstractEntityManagerFactoryBean).buildNativeEntityManagerFactory() line: 390
        LocalContainerEntityManagerFactoryBean(AbstractEntityManagerFactoryBean).afterPropertiesSet() line: 377
        LocalContainerEntityManagerFactoryBean.afterPropertiesSet() line: 341
        DefaultListableBeanFactory(AbstractAutowireCapableBeanFactory).invokeInitMethods(String, Object, RootBeanDefinition) line: 1767
        DefaultListableBeanFactory(AbstractAutowireCapableBeanFactory).initializeBean(String, Object, RootBeanDefinition) line: 1704
        DefaultListableBeanFactory(AbstractAutowireCapableBeanFactory).doCreateBean(String, RootBeanDefinition, Object[]) line: 581
        DefaultListableBeanFactory(AbstractAutowireCapableBeanFactory).createBean(String, RootBeanDefinition, Object[]) line: 503
        DefaultListableBeanFactory(AbstractBeanFactory).lambda$doGetBean$0(String, RootBeanDefinition, Object[]) line: 317
        1800649922.getObject() line: not available
        DefaultListableBeanFactory(DefaultSingletonBeanRegistry).getSingleton(String, ObjectFactory<?>) line: 222
        DefaultListableBeanFactory(AbstractBeanFactory).doGetBean(String, Class<T>, Object[], boolean) line: 315
        DefaultListableBeanFactory(AbstractBeanFactory).getBean(String) line: 199
        AnnotationConfigServletWebServerApplicationContext(AbstractApplicationContext).getBean(String) line: 1089
        AnnotationConfigServletWebServerApplicationContext(AbstractApplicationContext).finishBeanFactoryInitialization(ConfigurableListableBeanFactory) line: 859
        AnnotationConfigServletWebServerApplicationContext(AbstractApplicationContext).refresh() line: 550
        AnnotationConfigServletWebServerApplicationContext(ServletWebServerApplicationContext).refresh() line: 140
        SpringApplication.refresh(ApplicationContext) line: 759
        SpringApplication.refreshContext(ConfigurableApplicationContext) line: 395

        TableInformationImpl.indexes() line: 122
        TableInformationImpl.getIndex(Identifier) line: 138
        GroupedSchemaMigratorImpl(AbstractSchemaMigrator).applyUniqueKeys(Table, TableInformation, Dialect, Metadata, Formatter, ExecutionOptions, GenerationTarget...) line: 370
        GroupedSchemaMigratorImpl.performTablesMigration(Metadata, DatabaseInformation, ExecutionOptions, Dialect, Formatter, Set<String>, boolean, boolean, Set<Identifier>, Namespace, GenerationTarget[]) line: 85
        GroupedSchemaMigratorImpl(AbstractSchemaMigrator).performMigration(Metadata, DatabaseInformation, ExecutionOptions, Dialect, GenerationTarget...) line: 207
        GroupedSchemaMigratorImpl(AbstractSchemaMigrator).doMigration(Metadata, ExecutionOptions, TargetDescriptor) line: 114
        SchemaManagementToolCoordinator.performDatabaseAction(Action, Metadata, SchemaManagementTool, ServiceRegistry, ExecutionOptions) line: 183
        SchemaManagementToolCoordinator.process(Metadata, ServiceRegistry, Map, DelayedDropRegistry) line: 72
        SessionFactoryImpl.<init>(MetadataImplementor, SessionFactoryOptions) line: 312
        SessionFactoryBuilderImpl.build() line: 462
        EntityManagerFactoryBuilderImpl.build() line: 892
        SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(PersistenceUnitInfo, Map) line: 57
        LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory() line: 365
        LocalContainerEntityManagerFactoryBean(AbstractEntityManagerFactoryBean).buildNativeEntityManagerFactory() line: 390
        LocalContainerEntityManagerFactoryBean(AbstractEntityManagerFactoryBean).afterPropertiesSet() line: 377
        LocalContainerEntityManagerFactoryBean.afterPropertiesSet() line: 341
        DefaultListableBeanFactory(AbstractAutowireCapableBeanFactory).invokeInitMethods(String, Object, RootBeanDefinition) line: 1767
        DefaultListableBeanFactory(AbstractAutowireCapableBeanFactory).initializeBean(String, Object, RootBeanDefinition) line: 1704
        DefaultListableBeanFactory(AbstractAutowireCapableBeanFactory).doCreateBean(String, RootBeanDefinition, Object[]) line: 581
        DefaultListableBeanFactory(AbstractAutowireCapableBeanFactory).createBean(String, RootBeanDefinition, Object[]) line: 503
        DefaultListableBeanFactory(AbstractBeanFactory).lambda$doGetBean$0(String, RootBeanDefinition, Object[]) line: 317
        473666452.getObject() line: not available
        DefaultListableBeanFactory(DefaultSingletonBeanRegistry).getSingleton(String, ObjectFactory<?>) line: 222
        DefaultListableBeanFactory(AbstractBeanFactory).doGetBean(String, Class<T>, Object[], boolean) line: 315
        DefaultListableBeanFactory(AbstractBeanFactory).getBean(String) line: 199
        AnnotationConfigServletWebServerApplicationContext(AbstractApplicationContext).getBean(String) line: 1089
        AnnotationConfigServletWebServerApplicationContext(AbstractApplicationContext).finishBeanFactoryInitialization(ConfigurableListableBeanFactory) line: 859
        AnnotationConfigServletWebServerApplicationContext(AbstractApplicationContext).refresh() line: 550
        AnnotationConfigServletWebServerApplicationContext(ServletWebServerApplicationContext).refresh() line: 140
        SpringApplication.refresh(ApplicationContext) line: 759
        SpringApplication.refreshContext(ConfigurableApplicationContext) line: 395
        SpringApplication.run(String...) line: 327
</code>
It's fetching the data from DB, unfortunately no fetchSize is specified on ResultSet or Statement. So, when there are thousands of DB objects, such kind of operations will be very time consuming. By default each time only fetching 10 records. The "jdbc.fetch_size" setting doesn't apply to these code logics.
<code>        try {
        final ResultSet resultSet = statement.executeQuery( lookupSql );
        try {
            final List<SequenceInformation> sequenceInformationList = new ArrayList<SequenceInformation>();
            while ( resultSet.next() ) {
                sequenceInformationList.add(
                        new SequenceInformationImpl(
                                new QualifiedSequenceName(
                                        null,
                                        null,
                                        identifierHelper.toIdentifier(
                                                resultSet.getString( 1 )
                                        )
                                ),
                                -1
                        )
                );
            }
            return sequenceInformationList;
        }
</code>
Is there any suggestion to mitigate this performance issue? Or could it be improved in the future Hibernate versions?
Comment: Thank you, Ryan. However it seems this setting doesn't work, the above code logic  will still be triggered.
Comment: Have you looked at the hibernate.temp.use_jdbc_metadata_defaults property? I'm wondering if that could be used to just switch off this loading behaviour rather than speed it up. See https://stackoverflow.com/questions/14445838/hibernate-startup-very-slow
Comment: Might be worth also trying hibernate official forums or raising an issue as I don't know whether the hibernate team monitors SO
Answer: Currently it seems the only workaround is to disable ddl-auto. Comment the below setting can mitigate the issue
<code>#spring.jpa.hibernate.ddl-auto=update
</code>
Comment: This is correct. It is also mentioned in the docs of spring boot: https://docs.spring.io/spring-boot/docs/current/reference/html/howto-database-initialization.html if someone needs further information. But also be aware that this will switch on the default behaviour of spring boot which varies between embedded databases and not embedded ones.


Android alarmmanager cancel and start not working

Question: I have the following code to set an alarm when the main activity starts and cancel when logging out
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ...

    // Schedule alarm
    Intent intent = new Intent(this, MyReceiver.class);
    alarmIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    if (PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_NO_CREATE) == null) {
        alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME, 0, AlarmManager.INTERVAL_DAY, alarmIntent);
    }
}

private void logOut() {
    if (alarmManager != null) {
        alarmIntent.cancel();
        alarmManager.cancel(alarmIntent);
    }

    Intent i = new Intent(MainActivity.this, LoginActivity.class);
    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
    startActivity(i);

    finish();
}

But when I log out, log back in, and enter the main activity the code alarmManager.setInexactRepeating() is never reached.
Answer: That line will never be reached, because your PendingIntent that you are checking will always exist, because you are creating that PendingIntent two lines earlier. Since the PendingIntent exists, the FLAG_NO_CREATE call will still return it, and that will not equal null.
Answer: That's because your if statement evaluates to false. According to your code, you will have an instance of a PendingIntent with that request every time you hit the if block.


AVD doesn't boot. Stuck on "Android" logo

Question: My virtual machine of a Nexus 5 with Google API 21 System image x86 does not boot up. This is the logcat output from the machine. It is a loop, so I post only a part of it.
This is the most relevant part, in my honest opinion. I think that is the crash of something. It happens on KitKat image and Lollipop image.
D/dalvikvm( 1868): GC_CONCURRENT freed 313K, 10% free 8273K/9144K, paused 22ms+37ms, total 248ms
D/dalvikvm( 1868): GC_CONCURRENT freed 869K, 10% free 8638K/9576K, paused 31ms+34ms, total 282ms
D/dalvikvm( 1868): GC_FOR_ALLOC freed 17K, 10% free 8640K/9576K, paused 96ms, total 96ms
I/dalvikvm-heap( 1868): Grow heap (frag case) to 9.053MB for 577450-byte allocation
F/libc    ( 1868): Fatal signal 11 (SIGSEGV) at 0xbd49815c (code=1), thread 1868 (system_server)
I/DEBUG   (  923): *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
I/DEBUG   (  923): Build fingerprint: 'generic_x86/sdk_x86/generic_x86:4.4.2/KK/999428:eng/test-keys'
I/DEBUG   (  923): Revision: '0'
I/DEBUG   (  923): pid: 1868, tid: 1868, name: system_server  >>> system_server <<<
I/DEBUG   (  923): signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr bd49815c
I/DEBUG   (  923):     eax e2d739aa  ebx 0000003f  ecx 00000035  edx 0000000a
I/DEBUG   (  923):     esi bd498060  edi b9690470
I/DEBUG   (  923):     xcs 00000073  xds 0000007b  xes 0000007b  xfs 00000000  xss 0000007b
I/DEBUG   (  923):     eip b644e900  ebp a0410020  esp bfcb9840  flags 00200286
I/DEBUG   (  923):
I/DEBUG   (  923): backtrace:
I/DEBUG   (  923):     #00  pc 0003b900  /system/lib/libcrypto.so (bn_mul_mont+944)
I/DEBUG   (  923):
I/DEBUG   (  923): stack:
I/DEBUG   (  923):          bfcb9800  bfcba36c  [stack]
I/DEBUG   (  923):          bfcb9804  00000000
I/DEBUG   (  923):          bfcb9808  bfcb98a8  [stack]
I/DEBUG   (  923):          bfcb980c  00000000
I/DEBUG   (  923):          bfcb9810  00000000
I/DEBUG   (  923):          bfcb9814  00000000
I/DEBUG   (  923):          bfcb9818  b4e119fc  /system/lib/libdvm.so
I/DEBUG   (  923):          bfcb981c  00000075
I/DEBUG   (  923):          bfcb9820  00000000
I/DEBUG   (  923):          bfcb9824  bfcb9f4c  [stack]
I/DEBUG   (  923):          bfcb9828  00000010
I/DEBUG   (  923):          bfcb982c  b766825b  /system/lib/libc.so (__sfvwrite+411)
I/DEBUG   (  923):          bfcb9830  bfcba027  [stack]
I/DEBUG   (  923):          bfcb9834  b4e11ad0  /system/lib/libdvm.so
I/DEBUG   (  923):          bfcb9838  00000010
I/DEBUG   (  923):          bfcb983c  00000002
I/DEBUG   (  923):     #00  bfcb9840  bfcb9e8c  [stack]
I/DEBUG   (  923):          bfcb9844  b9690470  [heap]
I/DEBUG   (  923):          bfcb9848  b968ff10  [heap]
I/DEBUG   (  923):          bfcb984c  b969024c  [heap]
I/DEBUG   (  923):          bfcb9850  b9690020  [heap]
I/DEBUG   (  923):          bfcb9854  2cb9d869
I/DEBUG   (  923):          bfcb9858  bfcba02c  [stack]
I/DEBUG   (  923):          bfcb985c  b9690250  [heap]
I/DEBUG   (  923):          bfcb9860  8511d85f
I/DEBUG   (  923):          bfcb9864  432bf275
I/DEBUG   (  923):          bfcb9868  a3cd7bc4
I/DEBUG   (  923):          bfcb986c  5ae2ef9c
I/DEBUG   (  923):          bfcb9870  a951d3c8  /system/lib/libwebviewchromium.so (gpu::gles2::GLES2Implementation::GetBooleanv(unsigned int, unsigned char*)+120)
I/DEBUG   (  923):          bfcb9874  ee0f795a
I/DEBUG   (  923):          bfcb9878  f899d6f3
I/DEBUG   (  923):          bfcb987c  3c3cf1aa
I/DEBUG   (  923):
I/DEBUG   (  923): memory map around fault addr bd49815c:
I/DEBUG   (  923):     b97d1000-b97f2000 rw- [heap]
I/DEBUG   (  923):     (no map for address)
I/DEBUG   (  923):     bfc9c000-bfcbd000 rw- [stack]
I/ServiceManager(  919): service 'telephony.registry' died
I/ServiceManager(  919): service 'scheduling_policy' died
I/ServiceManager(  919): service 'sensorservice' died
I/ServiceManager(  919): service 'appops' died
I/ServiceManager(  919): service 'display' died
I/ServiceManager(  919): service 'power' died
I/ServiceManager(  919): service 'batterystats' died
I/ServiceManager(  919): service 'usagestats' died
E/installd(  929): eof
E/installd(  929): failed to read size
I/installd(  929): closing connection
D/Zygote  ( 1595): Process 1868 terminated by signal (11)
I/Zygote  ( 1595): Exit zygote because system server (1868) has terminated
I/ServiceManager(  919): service 'media.audio_flinger' died
I/ServiceManager(  919): service 'media.player' died
I/ServiceManager(  919): service 'media.camera' died
I/ServiceManager(  919): service 'media.audio_policy' died
I/Netd    ( 1896): Netd 1.0 starting
W/InterfaceController( 1896): Warning (dlopen failed: library "/system/lib/libnetcmdiface.so" not found) while opening the net interface command library
I/mediaserver( 1898): ServiceManager: 0xb8ee7d40
I/AudioFlinger( 1898): Using default 3000 mSec as standby time.
I/CameraService( 1898): CameraService started (pid=1898)
D/EmulatedCamera_QemuClient( 1898): Emulated camera list:
D/EmulatedCamera_FakeCamera( 1898): Initialize: Fake camera is facing back
V/EmulatedCamera_Device( 1898): initializeWhiteBalanceModes with auto, 1.000000, 1.000000
V/EmulatedCamera_Device( 1898): initializeWhiteBalanceModes with incandescent, 1.380000, 0.600000
V/EmulatedCamera_Device( 1898): initializeWhiteBalanceModes with daylight, 1.090000, 0.920000
V/EmulatedCamera_Device( 1898): initializeWhiteBalanceModes with twilight, 0.920000, 1.220000
V/EmulatedCamera_Device( 1898): setWhiteBalanceMode with white balance auto
D/EmulatedCamera_FakeCamera( 1898): Initialize: Fake camera is facing front
V/EmulatedCamera_Device( 1898): initializeWhiteBalanceModes with auto, 1.000000, 1.000000
V/EmulatedCamera_Device( 1898): initializeWhiteBalanceModes with incandescent, 1.380000, 0.600000
V/EmulatedCamera_Device( 1898): initializeWhiteBalanceModes with daylight, 1.090000, 0.920000
V/EmulatedCamera_Device( 1898): initializeWhiteBalanceModes with twilight, 0.920000, 1.220000
V/EmulatedCamera_Device( 1898): setWhiteBalanceMode with white balance auto
I/CameraService( 1898): Loaded "Emulated Camera Module" camera module
I/AudioPolicyManagerBase( 1898): loadAudioPolicyConfig() loaded /system/etc/audio_policy.conf
D/AndroidRuntime( 1897):
D/AndroidRuntime( 1897): >>>>>> AndroidRuntime START com.android.internal.os.ZygoteInit <<<<<<
W/linker  ( 1897): libdvm.so has text relocations. This is wasting memory and is a security risk. Please fix.
I/AudioFlinger( 1898): loadHwModule() Loaded primary audio interface from Generic audio HW HAL (audio) handle 1
I/AudioFlinger( 1898): HAL output buffer size 1024 frames, normal mix buffer size 1024 frames
I/AudioMixer( 1898): found effect "Multichannel Downmix To Stereo" from The Android Open Source Project
I/AudioFlinger( 1898): Using module 1 has the primary audio interface
I/AudioFlinger( 1898): AudioFlinger's thread 0xb5fc0010 ready to run
W/AudioFlinger( 1898): Thread AudioOut_2 cannot connect to the power manager service
W/AudioFlinger( 1898): Thread AudioOut_2 cannot connect to the power manager service

Otherwise, this is the complete log:
http://pastebin.com/Ci7Ah97W
Host system:
Mac OS X 10.10.1 Yosemite

Android Studio 1.0.1

Build #AI-135.1641136, built on December 11, 2014

JRE: 1.6.0_65-b14-466.1-11M4716 x86_64

JVM: Java HotSpot(TM) 64-Bit Server VM by Apple Inc.

The specs of the machise are:
Name: Nexus_5_API_21

CPU/ABI: Google APIs Intel Atom (x86)

Path: /Users/matteo/.android/avd/Nexus_5_API_21.avd

Target: Google APIs (API level 21)

Skin: nexus_5

SD Card: /Users/matteo/.android/avd/Nexus_5_API_21.avd/sdcard.img

Snapshot: no

hw.lcd.density: 480

hw.dPad: no

avd.ini.encoding: UTF-8

hw.camera.back: emulated

disk.dataPartition.size: 200M

hw.gpu.enabled: yes

runtime.network.latency: none

skin.dynamic: no

hw.keyboard: yes

runtime.network.speed: full

hw.device.hash2: MD5:2fa0e16c8cceb7d385183284107c0c88

hw.ramSize: 1572864

tag.id: google_apis

tag.display: Google APIs

hw.sdCard: yes

hw.device.manufacturer: Google

hw.mainKeys: no

hw.accelerometer: yes

hw.trackBall: no

hw.device.name: Nexus 5

hw.sensors.proximity: yes

hw.battery: yes

AvdId: Nexus_5_API_21

hw.sensors.orientation: yes

hw.audioInput: yes

hw.camera.front: emulated

hw.gps: yes

avd.ini.displayname: Nexus 5 API 21

snapshot.present: no

vm.heapSize: 64

runtime.scalefactor: auto

I tried to change the amount of RAM (from 512 to 3 GB but my physical RAM is 4GB), host GPU on/off, enabling/disabling snapshot but nothing changes. The output are always the same.
Comment: You should add the relevant information to your question. Do not put information on sites like Pastebin and then ask folks to go offsite. You can update your question by clicking *Edit*.
Comment: The log is bigger than the permitted size (30000 lines, log are 100000+ lines). I'll add the part, in my opinion, most relevant. Thanks.
Answer: I had the same problem. It helped me to remove old HAX and install new one updated.