How do I make java wait for boolean to run funciton

Question: I'm sure this is pretty simple but I can't figure out and it sucks I'm up on suck on (what should be) an easy step.
ok. I have a method that runs one function that give a response. this method actually handles the uploading of the file so o it takes a second to give a response. I need this response in the following method. sendPicMsg needs to complete and then forward it's response to sendMessage. Please help.
b1.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {

        if(!uploadMsgPic.equalsIgnoreCase("")){

            Log.v("response","Pic in storage");
            sendPicMsg();
                    sendMessage();
            }else{
                    sendMessage();
                }

1st Method
public void sendPicMsg(){
Log.v("response", "sendPicMsg Loaded");
if(!uploadMsgPic.equalsIgnoreCase("")){

  final SharedPreferences preferences = this.getActivity().getSharedPreferences("MyPreferences", getActivity().MODE_PRIVATE);
    AsyncHttpClient client3 = new AsyncHttpClient();
    RequestParams params3 = new RequestParams();

    File file = new File(uploadMsgPic);

    try {
        File f = new File(uploadMsgPic.replace(".", "1."));
        f.createNewFile();

        //Convert bitmap to byte array
        Bitmap bitmap = decodeFile(file,400);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        bitmap.compress(CompressFormat.PNG, 0 /*ignored for PNG*/, bos);
        byte[] bitmapdata = bos.toByteArray();

        //write the bytes in file
        FileOutputStream fos = new FileOutputStream(f);
        fos.write(bitmapdata);

        params3.put("file", f);

    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    params3.put("email", preferences.getString("loggedin_user", ""));
    params3.put("webversion", "1");
    client3.post("http://*******.com/apiweb/******upload.php",params3, new AsyncHttpResponseHandler() {

      @Override
      public void onSuccess(String response) {
          Log.v("response", "Upload Complete");

          refreshChat();
        //responseString = response;
        Log.v("response","msgPic has been uploaded"+response);
        //parseChatMessages(response);
        response=picurl;
        uploadMsgPic = "";

        if(picurl!=null){
            Log.v("response","picurl is set");
        }
        if(picurl==null){
                Log.v("response", "picurl no ready");
                };

      }

  });

    sendMessage();

}

  }

2nd Method
public void sendMessage(){

  final SharedPreferences preferences = this.getActivity().getSharedPreferences("MyPreferences", getActivity().MODE_PRIVATE);
  if(preferences.getString("Username", "").length()<=0){
      editText1.setText("");
      Toast.makeText(this.getActivity(), "Please Login to send messages.", 2);
      return;
  }
    AsyncHttpClient  client = new AsyncHttpClient();
    RequestParams params = new RequestParams();
    if(type.equalsIgnoreCase("3")){
        params.put("toid",user);
         params.put("action", "sendprivate");
    }else{
        params.put("room", preferences.getString("selected_room", "Adult Lobby"));
         params.put("action", "insert");

    }
    Log.v("response", "Sending message "+editText1.getText().toString());
params.put("message",editText1.getText().toString() );
params.put("media", picurl);

 params.put("email", preferences.getString("loggedin_user", ""));
params.put("webversion", "1");

  client.post("http://peekatu.com/apiweb/*********.php",params, new AsyncHttpResponseHandler() {

      @Override
      public void onSuccess(String response) {

          refreshChat();
        //responseString = response;
        Log.v("response", response);
        //parseChatMessages(response);
        if(picurl!=null)
        Log.v("response", picurl);
      }

  });

  editText1.setText("");
    lv.setSelection(adapter.getCount() - 1);

  }

Comment: How do I make sure response in ready before next function starting?
Comment: Looks like onSuccess() method is a callback, You could use a synchronizer(http://download.java.net/jdk7/archive/b123/docs/api/java/util/concurrent/SynchronousQueue.html) while calling sendPicMsg() and call sendMessage() only when onSuccess() notifies the synchronizer
Answer: Don't mix this IO and RPC intensive with your client thread. When your button is clicked, start another thread which handles the communication.
In that thread (potentially a separate class) you send the picture and wait for response; at the same time mark your button to be disabled to avoid clicking again. Then when you receive response, send the message again. Afterwards, raise an event back to the GUI thread, enable the button and display the message.
Answer: An easy way to solve this; call your method sendMessage() after the sendPicMsg() in the "onSuccess()" method
Answer: From what I understand, you need serial execution of background tasks.
What I do in the case is use a class that extends AsyncTask, takes some sort of listener in its constructor and calls the listener's callback in onPostExecute.
A quick example:
class ExampleTask<T,S,U> extends AsyncTask<T,S,U>
{
    public interface ExampleListener
    {
        public void onTaskCompleted(boolean success);
    }

    private ExampleListener mListener;

    public ExampleTask(ExampleListener listener)
    {
        mListener = listener;
    }

    ...
    @Override
    protected void onPostExecute(U result)
    {
        ...
        if (mListener != null)
        {
            mListener.onTaskCompleted(yourBooleanResult);
        }
    }
}

Just pass a new ExampleListener implementation that calls the second method.
Here's an implementation of the listener:
ExampleListener sendMessageListener = new ExampleListener()
{
    public void onTaskCompleted(boolean success)
    {
        if(success)
            sendMessage();
    }
}

Comment: Hello I believe this solution may solve be but can I get a bit of clarification on how to implement this.
Comment: Thank you for your answer. But I don't know where to start. Would you happen to have any examples?
Comment: I can't give you a full example due to a tight schedule. Edited the answer to include an example of the listener. Move the code from your first method to an ExampleTask's doInBackground method, pass in the listener in the constructor and you should be good to go!
Comment: anybody have a min to talk walk me thru this solution? please


Is it possible to limit output bandwidth between eth0 and lo?

Question: I'm trying to limit the bandwidth between my eth0 output (nginx proxy) to my loopback inteface  (apache) by filtering on destination port.
Incoming Packet -> Eth0 -> 0.0.0.0:80 Nginx -> tc qdisc class/iptable mangle 2525port -> 127.0.0.1:2525 Apache

I don't know if it's even possible I'm just experimenting.
My rules are the followings :
tc qdisc add dev eth0 root handle 1:0 htb
tc class add dev eth0 parent 1:0 classid 1:10 htb rate 2mbps ceil 2mbps prio 0
tc filter add dev eth0 parent 1:0 prio 0 protocol ip handle 10 fw flowid 1:10

iptables -A OUTPUT -t mangle -p tcp --dport 2525 -j MARK --set-mark 10

I also tried to with FORWARD chain but its still the same.
Comment: You have an fundamental misunderstanding. Nginx will use the loopback interface to connect to Apache.
Comment: Yes I realised that and corrected my configuration, it's now working well on loopback.
Answer: As Andrew mentionned I was wrong by thinking that I should filter the eth0. As soon as I changed the configuration to loopback instead of eth0 everything worked fine.


VLC : Couldn't extract youtube video URL / youtube.luac

Question: Following my question here : VLC : which file to update VLC Lua youtube script on Mac OS X?
I bumped again today about the infamous message : " lua stream error: Couldn't extract youtube video URL, please check for updates to this script"
Obviously I did follow what was working a year ago, but it doesn't work.
Anyone having the same issue ?
Comment: please paste text instead of pictures next time
Comment: regarding the error, you can blame google for this
Comment: https://code.videolan.org/videolan/vlc/-/issues/27529
Answer: do you still have this issue?
i use follow youtube.luac
https://github.com/videolan/vlc/blob/master/share/lua/playlist/youtube.lua
I have renamed the old one and created a new one with notepad++ with the 1115 line from github and saved it in the vlc\lua\playlist folder.
Hope this will solve your problem :-)


Why is my RAIDZ2 pool larger than the expected size calculation?

Question: I'm building a RAIDZ2 ZFS system, using Ubuntu 13.10 as a base system, and zfsonlinux's packages, having 6 disks dedicated to the pool data and a couple of SSD partitions to do ZIL log and L2ARC cache. My HDDs are all 2.0 TiB (in fact: slightly less than 2.0 TiB) drives.
Yet, once the pool was created, zpool list unexpectedly reports a pool having 10.9 TiB size, 1.93 MiB allocated, and 10.9 TiB free.  How is it getting nearly 11 TiB free in a RAIDZ2 having a total of 12.0 TiB of disks? I was expecting to have a mere 8.0 TiB of free space (4.0 TiB being allocated to parity).
Oh, this is apparently a very similar question to ZRAID1 pool size bigger than expected, but about RAIDZ2 instead of RAIDZ... I'll post this anyway, in case anyone cares about RAIDZ2 for their searches.
Answer: It turns out that each drive is 1.82TiB. That, times 6 = 10.9TiB. I suppose zpool reports the total physical space available for filesystem labour (ie: data + parity) as opposed to just the space available for user data without the parity factored in.
In fact, the "duplicate question" has a perfectly good answer already, quoted here (added dashes for clarity):

zpool list - shows the size of the pool, which is the size of all the
  disks.
zfs list - shows the usable file systems sizes in the
  pool.

PS. Maybe we should have a "raidz2" tag.
Comment: Because: http://nex7.blogspot.com/2013/03/readme1st.html - There are serious compromises to using RAIDZ(1,2,3) in your ZFS arrays. Performance, expandability, complexity...
Comment: *(don't use raidz or raidz2!!)*
Comment: @ewwhite the article you mentioned did include some limitations performance-wise for building a "raidz(2)", it also included decent advices for someone building a "raidz(2)". There is also compromises in building mirror vdevs, and of course compromises in raidz alternative: soft/hard raid.


Simplest way to run a python application the receives data from a web application, processes/manipulates it then pushes it back to the front end

Question: Goal: A frontend that receives a twitter username that is sent to a python script that then scrapes that users timeline (https://twitter.com/username) then simulates text with that user's tweets using Markov Chains. Finally, this output is returned to the front end.
I don't need help with the actual python coding or frontend. I am just lost on how to "actually start working on this", specifically as to what tools to use to execute python scripts and use these in conjunction with a frontend (preferably reactjs).
Thank you so much for your time and advice
Comment: try node-gyp with express
Answer: You can use to approaches:

You have to use a python backend web server either Flask or Django (Flask os recommended for this particular purpose). Send the twitter username from the frontend to the python server using Ajax, axios, or fetch API. Do your processing and then send your output to the frontend in the response of that request.
Use web Sockets for more dynamic feel


How to find the same records and do an action for each rails

Question: I'm trying to solve a huge problem.
Context : e-commerce subject. I have multiple Products, that customers can add into a Cart. Each Product can have multiple DeliveryMods (Exemple: express, low cost).
I want to find each time where the DeliveryMods of the Products are different, and create a LogisticalCart for each. The result would look like :

Product1 : DeliveryMods = a & b
Product2 : DeliveryMods = b
Product3 : DeliveryMods = a & b

Product1 and Product3 have the same DeliveryMods, but not Product2.
2 combinations of DeliveryMods, so 2 LogisticalCart to create.
Result : 2 LogisticalCart created.
I've tried a lot of things, and I don't know how to do with it. Any solutions please ?
Important :
Product & DeliveryMod relation is a "has_and_belongs_to_many" with join table.
Code try (don't work) :
<code>  @products = current_cart.products
    @products.each do |product|
      @delivery_mods = Array.new
      @delivery_mods << product.delivery_mods
      if @delivery_mods.all? { |item| item.eql?item}
        @logistical_cart = LogisticalCart.new
        @logistical_cart.save
     end
   end
</code>
Answer:
Product1 and Product3 have the same DeliveryMods

Does it mean, that Product1 and Product3 have delivery_mods with the same ids? Do you need to pass anything else, besides delivery_mod_ids? Please, clarify all the details at once :)
<code>@products = current_cart.products
mod_ids_uniq = @products.map(&:delivery_mod_ids).uniq
mod_ids_uniq.each do |ids|
  LogisticalCart.create(delivery_mod_ids: ids)
end
</code>
Comment: Hi @Vasilisa, it's exactly what I was looking for! Thanks. A precision please, how can I pass an object in this hash at **each .time** ? I want to add things like `@new_cart.delivery_mods = products.delivery_mods` with the `LogisticalCart.create`
Comment: @Gdebrick, if my answer works for you, please, accept it as correct


Border around row spanned table

Question: Hello I have created table using td and row span. Now I want to make the structure clearer by bolding the major category as such

https://plnkr.co/edit/4JM61bhjSqWR512PaWcS?p=preview
How can I achieve this?
I fear that I have to manually color each cell boarder one by one? It seems that boarder and coloring attribute either concern td or tr element. Hence is it possible to span such effect across column?
Answer: try this:

    A
    B
    C
     Input
     Input

    D
     Input
     Input

    E
     Input
     Input

    B
    F
     Input
     Input

    G
     Input
     Input

    H
     Input
     Input

    A
    B
    C
     Input
     Input

    D
     Input
     Input

    E
     Input
     Input

    F
     Input
     Input

    B
    G
     Input
     Input

    H
     Input
     Input

and this css :
th,
td {
  border: 1px solid black;
}

tbody .colored td[rowspan]:not(:first-child) {
  border-left: 2px solid red;
  border-top: 2px solid red;
  border-bottom: 2px solid red;
}

tbody .colored td:nth-of-type(n+2) {
  border-top: 2px solid red;
}

tbody tr td:last-child {
  border-right: 2px solid red;
}

tbody tr:last-child td:nth-child(n+1) {
  border-bottom: 2px solid red;
}

https://plnkr.co/edit/VYFXhZf0fnZqmr1BN1z6?p=preview
Comment: it's not a clean solution I mean, but I think it fixes your issue. I'll try to use more css classes to design the borders
Comment: Thank you! when you specified 2,3,4 rowspan. Is that bruteforce? I will have a dynamic data (longer table etc.) but the structure does not change, will it work then?
Comment: yes it is! but if the structure remains the same so all the cells with rowspan 2, 3 and 4 will have a border, so this won't be a problem.
Comment: I see! Is it possible to make it generally and not stick to only 2,3,4. Sometimes myrow span go up to 20+ haha. My table is dynamic
Comment: ok try this: https://plnkr.co/edit/VYFXhZf0fnZqmr1BN1z6?p=preview. This selects all td with rowspan attribute exept the first cells in every row. I hope this helps
Comment: Thank you so much! however, there is a few bug, I updated my plunkr and you can see some line is not drawn! I am playing around with css but I am quite confused right now!
Comment: I have updated my plunkr and it is perfectly working now! Thank you for giving me a head start

Border around row spanned table


Unable to get a class method to work in loops

Question: I'm new to JS (or coding in general) and I'm experimenting with a few things to learn. I'm playing around with class methods in a loop for no reason other than to screw around and hopefully learn a thing or two, but I'm unable to get the desired result.
Here is the code:
class CD extends Media {
  constructor(title, artist) {
    super(title);
    this._artist = artist;
    this._songTitles = [];
  }
  get songTitles() {
    return this._songTitles;
  }
  addSong(song) {
    if (typeof song === 'string') {
      this._songTitles.push(song)
    } else {
      console.log('You need to input the song title as a string.');
    }
  }
  shuffle() {
  const songList = this.songTitles;
  const randomIndex = Math.floor(Math.random() * songList.length);
  return songList[randomIndex];
  }
};

const flowerBoy = new CD('Flower Boy', 'Tyler, The Creator');
flowerBoy.addSong('Foreword (feat. Rex Orange County)');
flowerBoy.addSong('Where This Flower Blooms (feat. Frank Ocean)');
flowerBoy.addSong('Sometimes...');
flowerBoy.addSong('See You Again (feat. Kali Uchis)');

const songs = flowerBoy.songTitles;
while (flowerBoy.shuffle() != 'Sometimes...') {
  const randomIndex = Math.floor(Math.random() * songs.length);
  console.log(flowerBoy.songTitles[randomIndex]);
};

What I'm trying to achieve is a loop that'll continue to shuffle through the flowerBoy.songTitles array until it comes across the string 'Sometimes...'. I think I've managed to achieve the loop part because thee output always shows a different amount of songs, however the loop won't stop at 'Sometimes...' and at times will stop at a different song.
Any help would be appreciated, thanks!
Comment: You're not logging the song that `.shuffle()` returned, you log some random other song - completely independent from the random selection that `.shuffle()` is doing
Answer: class CD extends Media {
  constructor(title, artist) {
    super(title);
    this._artist = artist;
    this._songTitles = [];
  }
  get songTitles() {
    return this._songTitles;
  }
  addSong(song) {
    if (typeof song === 'string') {
      this._songTitles.push(song)
    } else {
      console.log('You need to input the song title as a string.');
    }
  }
  shuffle() {
    const songList = this.songTitles;
    const randomIndex = Math.floor(Math.random() * songList.length);

    return songList[randomIndex];
  }
};

const flowerBoy = new CD('Flower Boy', 'Tyler, The Creator');

flowerBoy.addSong('Foreword (feat. Rex Orange County)');
flowerBoy.addSong('Where This Flower Blooms (feat. Frank Ocean)');
flowerBoy.addSong('Sometimes...');
flowerBoy.addSong('See You Again (feat. Kali Uchis)');

const songs = flowerBoy.songTitles;

const shuffleFlowerBoy = () => {
  const song = flowerBoy.shuffle();
  console.log(song);
  if (song !== 'Sometimes...') {
    return shuffleFlowerBoy();
  }

  return song;
}

shuffleFlowerBoy();

Comment: Hi, I tried this code and it will always output ``'Sometimes...'``, without outputting any of the other songs in the array.
Comment: Yeah thats exactly what your code was doing. What is it that you want to happen?, otherwise add a console log into to shuffle func - Edited code to reflect
Answer: The problem you had in your code is that you're not displaying the value that was used in the loop condition as Bergi said.
class CD extends Media {
  constructor(title, artist) {
    super(title);
    this._artist = artist;
    this._songTitles = [];
  }
  get songTitles() {
    return this._songTitles;
  }
  addSong(song) {
    if (typeof song === 'string') {
      this._songTitles.push(song)
    } else {
      console.log('You need to input the song title as a string.');
    }
  }
  shuffle() {
    const songList = this.songTitles;
    const randomIndex = Math.floor(Math.random() * songList.length);
    return songList[randomIndex];
  }
};

const flowerBoy = new CD('Flower Boy', 'Tyler, The Creator');
flowerBoy.addSong('Foreword (feat. Rex Orange County)');
flowerBoy.addSong('Where This Flower Blooms (feat. Frank Ocean)');
flowerBoy.addSong('Sometimes...');
flowerBoy.addSong('See You Again (feat. Kali Uchis)');

const songs = flowerBoy.songTitles;
let song = flowerBoy.shuffle();
while (song != 'Sometimes...') {
  console.log(song);
  song = flowerBoy.shuffle();
};


Multithread TCP Server with POCO C++ libraries

Question: I'm trying to develop a TCP Server with POCO C++ libraries.
I found some examples here.
At first I tried example from Alex but shutdown event didn't work. EchoServer have the same problem.
So, then I tried Cesar Ortiz example and got a unusual problem. After some time server throws an error:
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
["src/ErrorHandler.cpp", line 60]
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

And connections got connection timeout error, new connections as well.
Example with eventhandler semeed more correct, but I don't know how can I fix shutdown event.
Answer: If all you want is multi-threaded TCP server, then "out of the box" Poco::Net::TCPServer will do - it is multi-threaded internally.
Start with defining the connection, this one will just echo back whatever you send to it:
class EchoConnection: public TCPServerConnection {
public:
  EchoConnection(const StreamSocket& s): TCPServerConnection(s) { }

  void run() {
    StreamSocket& ss = socket();
    try {
      char buffer[256];
      int n = ss.receiveBytes(buffer, sizeof(buffer));
      while (n > 0) {
        ss.sendBytes(buffer, n);
        n = ss.receiveBytes(buffer, sizeof(buffer));
      }
    }
    catch (Poco::Exception& exc)
    { std::cerr << "EchoConnection: " << exc.displayText() << std::endl; }
  }
};

Then, run the server and send it some data:
TCPServer srv(new TCPServerConnectionFactoryImpl<EchoConnection>());
srv.start();

SocketAddress sa("localhost", srv.socket().address().port());
StreamSocket ss(sa);
std::string data("hello, world");
ss.sendBytes(data.data(), (int) data.size());
char buffer[256] = {0};
int n = ss.receiveBytes(buffer, sizeof(buffer));
std::cout << std::string(buffer, n) << std::endl;

srv.stop();

Comment: Thanks for reply Alex. As I said, now I use the second example like yours, but I can't find the cause of a bug with 'src/errorhandler.cpp' message. After this server accepts connections, but doesn't send or receive bytes for new connections and throw 'connection timeout' for existing connections.
Comment: You must be throwing an exception somewhere in your connection handler. Since it runs in a thread, it ends up in the default error handler. Exception is probably not a descendant from std::exception, so ErrorHandler does not know anything about it. But you are not providing enough info for a definite answer on what the problem is. Best to run your code in debugger and step through it to find where is the source of your problem.
Comment: As I said, I use the example of Cesar Ortiz, I just changed 'run' function - [here](http://hastebin.com/lokadobeve.coffee) As I found out, when a connection couldn't get data because it in queue, but I can't understand why? When current connections reach 16, all new connections are added to queue and refused after. In params I set maxqueued(3), maxthreads(20) and threadidletime(100)


Modelling an ER diagram situation

Question: I have two entities named "Main office" and "Branch office", which belong to some company. The main office can have 1 or more branch offices.
But, a company can have only one Main office, which is a central place for all other main offices. How should I model this situation?

Use 2 entities, Main and Branch, where Main will have a boolean attribute Central. I think this is bad as it will lead to transitive dependency?
Have 3 entities, Main, Branch and Central, where the Central office table will have only one row?
Or, in the end, to have 2 entities Main and Branch, where Main will be in relationship with itself.

EDIT:
A company can have more than one main office.
Comment: What is the difference between the main office and the central office?  And, is your question about how to set up the logical diagram for the entities or what tables to have in the database?
Comment: Your edit contradicts what you said earlier: *company have only one Main office*. Please present yout requirements so that your post is consistent.
Comment: Probably you should revisit the names of your entities, they are prone to ambiguity.
Answer: For modeling purposes, you would probably have three entities:  company, main office, branch offices.  Company would have a 1 to many relationship with main office; main office would have a 0 to many relationship with branch office.  This seems to capture the logical structure of the data.
I think you are also asking about the physical structure.  Logical structures can be mapped directly onto physical structures, but that is not necessary.  The question becomes how the data is going to be used.
One reasonable implementation of the logical model would have a company table and single offices table, with:

a flag that specifies whether it is a main office or a branch office
a self-join key for branch offices to point back to the main office, with the constraint that the "match back" has to be a main office
a bunch of fields common to all offices
a small number of fields common to one or the other type

Another reasonable implementation would put main offices and branch offices in different tables.  This comes closer to the logical model of the data.  However, I imagine that a lot of queries would be union'ing these two tables, making the single table approach more efficient in practice (but not necessarily).
Unfortunately, relational databases don't implement the idea of class inheritance very well.
Answer: Create Entity Company and Entity Office.  Create 1 to M relationship from Company to Office.  Office has a type - either Main or Branch.  Create 1 to M relationship from Office to itself.  This recursive relationship is the association of a branch office to a main office.  Finally add a 1 to 1 relationship from Office back to Company, with a role name to distinguish the relationship as identifying the Central Office.
You could also make Office a super type and make Main and Branch sub-types.  This would enable you to model a 1 to M relationship from Main to Branch and more explicitly show the business rule.
It would be great if I could paste an ER model fragment in here!  The key point is that Office is the only real entity here, and main and branch are sub-types of Office.  Central is not an entity at all but is a relationship role between an office and the company.
Answer: Make a one-to-one relationship between Main office and Company, then a many-to-one between Branch office and Main office.
There is no direct relationship between Branch office and Company, but it can be easily inferred transitively through the Main office.
Answer: You may want to use inheritance in your E-R model. You have a generic Office superclass and Branch/Main subclasses. Company will have a Many to One relationship with Main Office and a One to One relationship with Main Office to represent the central office.

Modelling an ER diagram situation


Quais as diferenças entre os conceitos de polimorfismo e sobrescrita em OOP?

Question: Fiquei um pouco confuso ao pesquisar sobre polimorfismo. O conceito de polimorfismo assemelha-se ao conceito de sobrescrita. Quais as diferenças entre polimorfismo e sobrescrita em OOP?
Comment: Em poucas palavras: **Polimorfismo** é a capacidade de um objeto de assumir diversas formas, de modo que um objeto **X**, se polimórfico, poderia assumir por exemplo a forma do objeto **Y**. Uma das maneiras de implementar polimorfismo é através da herança. **Sobrescrita** é a capacidade de um objeto de oferecer uma implementação para um comportamento do objeto cuja forma ele assumiu. Assim, se X herda Y e sobrescreve um comportamento de Y, quando X assumir a forma de Y (for usado num lugar onde Y era esperado) e o tal comportamento for invocado, será executada a implementação de X e não de Y.
Comment: @Caffé, boa respota
Answer: São coisas relacionadas. A sobrescrita é usada para alcançar o polimorfismo. Não é o único mecanismo mas é o mais usado na maioria das linguagens mainstream.
O polimorfismo é a característica que pode usar um objeto no lugar de outro como se fosse o objeto esperado. Para isto funcionar direito é necessário que o mecanismo exista para garantir que está acessado os membros corretos.
Uma situação comum é esperar um objeto e receber um outro que é descendente deste esperado. Se chamar um método deste objeto, ele vai chamar o método do objeto esperado ou do objeto concreto descendente que foi recebido?
Sem a sobrescrita, ele iria chamar o método do objeto esperado, do pai. Mas em geral não é o que se deseja. A sobrescrita informa que este método do objeto filho deve ser usado no lugar e atende ao requisito do polimorfismo.
Evidentemente que há casos em que não se deseja esta substituição, não se quer o polimorfismo em situação específica. Aí a sobrescrita não deve ser utilizada. Algumas linguagens lidam melhor com isto do que outras.
Em uma pergunta sobre o tema eu falo sobre como pode funciona o mecanismo usando o exemplo de linguagens que não possuem o polimorfismo nativamente.
Usando o exemplo já dado em outra resposta (linguagem fictícia) veja como funciona o polimorfismo:
class A {
    metodo1() { print "A"; }
    metodo2() { print "A"; }
}

class B extends A {
    override metodo1() { print "B"; }
    metodo2() { print "B"; }
}

void executa(A obj) { //note que ele receberá sempre algo do tipo A
    obj.metodo1();
    obj.metodo2();
}

executa(new A()); //imprime A e A
executa(new B()); //imprime B e A

O primeiro exemplo não ocorre polimorfismo. O objeto esperado deve ser do tipo A e realmente é o que é enviado.
O segundo exemplo ocorre polimorfismo no metodo1(). Foi enviado um objeto do tipo B para um método que esperava receber algo do tipo A. Isto é possível porque o tipo B deriva de A, ou seja atende todos os requisitos de A. Como o método foi sobrescrito, ele chamará a versão do objeto concreto, ou seja de B.
Mas no metodo2() o polimorfismo não ocorre porque não houve a sobrescrita. Então como o método executa() espera algo do tipo A ele vai procurar em A mesmo o que executar. Ele não assumiu outra forma.
A forma mais comum de realizar isto internamente na linguagem é através de uma tabela de ponteiros para os métodos (vtable). Quando há a sobrescrita, o endereço do método da classe derivada é usado no lugar do endereço do método original. Quando for feita uma chamada deste método, ao invés de ele simplesmente chamar o método por seu endereço conhecido, ele vai procurar nessa tabela qual é o endereço a ser chamado.
Um exemplo mais concreto usando classe abstrata seria criar um manipulador de log. Claro que isto não faz uso de "boas práticas", é uma forma simplificada:
abstract class interface Log {
    bool save(string msg) {
        if (processMedia(msg)) {
            print "logou!";
            return true;
        } else {
            print "o log falhou!";
            return false;
        }
    }
    virtual bool processMedia(string msg);
}

class LogFile extends Log {
    override bool processMedia(string msg) {
        try {
            //salva em arquivo aqui
            return true;
        } catch (IOException ex) {
            return false;
        }
    }
}

classe LogMail extends Log {
    override bool processMedia(string msg) {
        try {
            //envia por e-mail aqui
            return true;
        } catch (SMTPException ex) {
            return false;
        }
}

bool logou = new LogFile().save("deu um erro X aqui neste trecho");

Coloquei no GitHub para referência futura.
Isso vai gravar a mensagem de erro em arquivo. Note que chamou o método que só existe no tipo abstrato. Não tem problema porque ele existe no tipo concreto que é derivado de Log. E dentro deste método haverá uma chamada ao processMedia() que só existe de fato na classe derivada. Aí ocorreu um polimorfismo.
Lembrando que em interface sempre ocorre o polimorfismo (pelo menos nas maioria das linguagens com este mecanismo). Qualquer operação que espere uma interface não poderá executar nada da própria interface, afinal ela não possui implementação. Sempre deverá chamar o método do contrato implementado no tipo concreto.
Comment: @DavidSchrammel Porque a intenção é **esconder** o método da classe pai em vez de sobrescrevê-lo no senso do polimorfismo. Este exemplo não considera o comportamento Java. Se considerasse, a segunda saída indicada estaria errada já que em Java os métodos são virtuais por padrão e a sobrescrita sempre vai ocorrer. Este exemplo provavelmente considera o comportamento do C#, onde, por outro lado, se você não está sobrescrevendo um método virtual (o que é indicado pela palavra-chave *override*) mas ao invés o está escondendo, é recomendado explicitar sua intenção usando a palavra chave *new*.
Comment: Apenas complementando que além do exemplo não ser em Java, ele não se aplica ao Java pois, ao contrário do exemplo, em Java não é possível esconder (ou "reintroduzir", como é chamado em outras linguagens) um método de instância da classe pai. O primeiro exemplo portanto considera detalhes específicos de alguma linguagem (ele serviria em C# e Delphi, por exemplo) e não a orientação a objetos de maneira geral (ele não serve em Java e Ruby, por exemplo, pois nestas linguagens o método quando redeclarado na classe filha será sempre *override*).
Comment: No teu exemplo 1 por qual motivo o metodo2() da classe B não tem o `@override` sendo que ele tem a mesma assinatura da classe A ?
Comment: @DavidSchrammel editei para ficar mais claro que a linguagem é fictícia e não Java. Nem C#. Eu tinha usado um exemplo "abstrato" na outra pergunta e segui ele nesta já que ela é um complemento da outro. O exemplo 2 é quase Java, mas também não é :)


How do I take the response from one JMeter rest sampler and use it as input to another?

Question: I have a JMeter test that has a rest sampler that outputs a value as such in the response data:
{"Var1":"xxxxx-xxxxxxxx-xxxxxxxxxx"}
I need to take that out put (Var1) and use it as input for the next rest sampler in the following test step. I have a line in a BeanShell pre-processor that says:
String clearText = "somestring1" + "_" + var1 + ":" + "somestring2";
where var1 is derived from a Regular Expression Extractor from the preceding RestSampler (that is how I got the out put {"Var1":"xxxxx-xxxxxxxx-xxxxxxxxxx"} ).
Problem: I get a void for var1 in the output of the second rest sampler.
What am i doing wrong? how can i get the value from the output of the first rest sampler and use it as input in the second rest sampler??
Thanks.
ironmantis7x
Comment: Check jmeter logs for any error. Use debug sampler to see what are your other variables. Provide your test plan and logs.
Answer: Are you sure that your Regular Expression Extractor is correctly obtaining Var1? If you're testing RESTful API it's better to use JSON Path Extractor available via JMeter Plugins (you will need Extras with Libs Set).
Configure JSON Path Extractor as follows:

Reference Name: Var1 or whatever you like
JSON Path: $.Var1 this one assumes your response.

So you would be able to provide the variable value as ${Var1} or ${__V(Var1)} to 2nd request.
See Using the XPath Extractor in JMeter (Scroll down to "Parsing JSON") for more details on how to properly install the extension and build up JSON Path queries.
Hope this helps.
Answer: If your API returns response in JSON format then use below solution :
#1 To use this parameter within same thread group:-
a] Right click on Thread Name --> click on "Add" --> click on "Post Processors"  -->  select "Json Extractor"
b] On 'Json Extractor" window, select below values :
Variable Names == test                //give any variable name(user-defined)
JSON Path expressions == $.[0].name   //this will pick value of "name" param from API's Json response
c] Now to use ${test} to pass this value to other API as input. By using ${test} you can use it anywhere.
#2 To use this ${test} parameter in other thread group :-
a] Right click on Thread Name --> click on "Add" --> click on "Post Processors"  -->  select "Json Extractor"
b] On 'Json Extractor" window, select below values :
Variable Names == test                //give any variable name(user-defined)
JSON Path expressions == $.[0].name   //this will pick value of "name" param from API's Json response
c] Right click on First Thread Name(where variable value is populated) --> click on "Add" --> click on "Assertions"  -->  select "BeanShell Assertions"
d] Under "script" section paste below code :
${__setProperty(test, ${test})};
e] Now you can access this first API's response value using ${__property(test)}
variable


Fit a distribution to a combinatorial problem

Question: In my previous question titled "Conditional combinations of balls in bowls", is there a distribution to fit $k$ when $d \gg M$? I mean, when $d$ is so large, what is the distribution of the total number of balls?
$M$ can be a number between $4$ to $64$ and $d$ (number of bowls) is very large, about $10000$. Each bowl can have $0,1,2,\ldots,M$ balls in it with equal probability. What is the distribution of total number of balls $k$?  $\Pr(k=k_0)=$?
Comment: Is this homework?
Comment: "...with equal probability" is helpful but ambiguous. Perhaps you could describe the process by which the bowl populations and $k$ are determined?
Comment: @whuber Seems to me that the OP is saying the probability is 1/(M+1) for each number of balls from 0 to M.
Comment: @Michael Yes, but that leaves a huge amount of latitude. Is $k$ fixed in advance? Are there other possible dependencies among the bowl populations?
Comment: @whuber K is a random variable, so it is not fixed.  Although not stated I would assume that each bowl's contents is independent of the others and 0<=k<=dM is the constraint on k.
Comment: @Michael According to the referenced question, "There are $k$ balls...," suggesting $k$ is *not* a random variable. So let's not assume anything and just let the OP clarify his question. There's little point in making up some interpretation that might or might not conform to the original intention.
Comment: @whuber Yes I got confused. It seems that k is fixed and the distribution is for the way the k balls get distributed in the d bowls. But the notation used is confusing because he writes P(k=k$_0$).
Comment: Well, thank you guys, actually K is a random variable. Thank you so much Henry.
Answer: Using uppercase $K$ for a random variable and lowercase $m,d,k_0$ for constants:
The number of balls in a particular bowl has a discrete uniform distribution with mean $\frac{m}{2}$ and standard deviation $\sqrt{\frac{m^2+2m}{12}}$.
Add up a large number $d$ of these i.i.d. then the the distribution of sum $K$ with mean $\frac{md}{2}$ and standard deviation $\sqrt{\frac{(m^2+2m)d}{12}}$ can be approximated  using the central limit theorem, remembering $K$ is discrete with integer spacing.
So $$\Pr(K=k_0) \approx \Phi \left( \frac{k_0 +\frac12 -\frac{md}{2}}{\sqrt{\frac{(m^2+2m)d}{12}}}  \right)- \Phi \left( \frac{k_0-\frac12 -\frac{md}{2} }{\sqrt{\frac{(m^2+2m)d}{12}}}  \right) \approx \phi \left( \frac{k_0-\frac{md}{2}}{\sqrt{\frac{(m^2+2m)d}{12}}}  \right) $$ where $\Phi$ is the cumulative distribution function and $\phi$ is the probability density function of a standard normal distribution.


Unable to access web application running on a certain machine

Question: Tried deploying a simple web application (jboss 5.1, jboss seam 2.2.1) on a machine. But for some weird reason, I am unable to access the application using http://localhost:8080/<my-app>.
Any access to the application on a IE 8 browser, just gets re-directed to the search page with a string "localhost:8080".
Couple of observations:-

I tried switching off the firewall protection on the machine, but this didn't help
I tried switching off the Avast virus protection software process, but this didn't help.
Tried starting JBoss application server using run.bat -b 0.0.0.0 (didn't help)

Any ideas on what is happening here?
Comment: did you take a look at exception when deploying your war file?
Comment: the war file deployed just fine
Answer: Is it possible that the hosts file on that machine is not set correctly?  Try http://127.0.0.1:8080/ instead.
Comment: I tried it with localhost, 127.0.0.1, 192.168.1.2 (from ipconfig) - none of them seemed to work
Comment: Is is possible something else is running on port 8080?  Have you checked jboss' startup logs?
Comment: I was looking at the console logs and everything looked normal to me.
Comment: You mentioned IE specifically, have you tried other browsers?  Also can you access the JMX console (http://localhost:8080/jmx-console) or one of the other built in JBoss administrative pages?
Comment: the machine didn't have other browsers, so I couldnt try it. Since the default page itself wasn't available, I didn't try the jmx-console
Answer: You running on *nix? See if your web-server is running on this port. You can use netstat -an for this purpose.
Post your results, and then we can help you further.
Comment: well this is a stupid answer.. you have already mentioned you using anti-virus n all.. so your box has to be a windows. pls ignore.
Comment: jboss application server prints information saying that it started on port 8080. I didn't run netstat though
Comment: try pinging your machine on 8080 port. Also I would check if java process is still running or not..
Comment: java process is definitely running. How do you check if the process is running on port 8080 (one mechanism is via netstat -an). are there any other ways
Comment: Not sure about similar utilities for windows. (One option would be to install Cygwin to run Unix commands on your windows box. But there's gotta be smarter solutions than that.)
Comment: This is not a dev machine and I don't think will be able to install Cygwin. I can only rely on the tools which are provided by the OS.


Evaluate the following integral : $ \int \frac{3 z^{3}-8 z+5}{\sqrt{z^{2}-4 z-7}} d z $

Question:
Question: Find the value of the following integral $$
\int \frac{3 z^{3}-8 z+5}{\sqrt{z^{2}-4 z-7}} d z
$$

My approach: I factorised the numerator as $(z-1)(3z^{2}+3z-5)$, then I substituted the function in denominator under the roots as $u$, but this only complicated things further, please help
Answer: hint :
derivative of the denominator $z^2-4z+7$ is equal to $2z-4$
now you can write $$3z^3-8z+5=l(z^2-4z-7)(2z-4) +k(z^2-4z+7)+m(2z-4)+n$$ by comparing coefficient.


¿How to compaire nested logit models using anova in R?

Question: I have two logit models:

Model A:

model_logit_house <- glm( health_status ~ sex + age + weight + study_level + chronic_ill +  laboral_situation +
                           sport_frec   + GHQ_12 + income_level +
                           n_bedrooms + indust_pollution +    delinquency, # study variables
                         data = model_data, family = binomial(link = "logit"),na.action = "na.omit")

Model B (a nested model from Model A):

model_logit <- glm( health_status ~ sex + age + weight + study_level + chronic_ill +  laboral_situation +
                           sport_frec   + GHQ_12 + income_level +,
                       data = model_logit_house$model, family = binomial(link = "logit"))

c(age,weight,GHQ_12,income_level) are continuous variables, the rest variables are cualitatives (factor).
I want to analyze if the housing characteristics (study variables) have influence on the health status. All variables are significant in both models. However, I want to do an analysis of variance (ANOVA) between these two models for to be sure that model A is better than model B. So:
anova(model_logit,model_logit_house)
And the output is:
  Resid. Df Resid. Dev Df Deviance
1     16805      15439
2     16802      15420  3   18.644

How do I interpret this table? Can the interpretation of this table tell me if there is an influence between the housing characteristics and the health status? If not. How can I compaire these two models with an ANOVA in R?
Answer: The deviance terms you see in anova, is the binomial deviance, a sum of errors of the predictions. So if your model predicts better, then the deviance gets lower.
If you include some more terms, and the deviance decreases substantially, this suggest the variables have explanatory power or some association with the dependent variable. And you already saw that with the significant p-values for the coefficients.
You can test this using a likelihood ratio test, implemented under anova, I use a example dataset below:
data = iris
data$Species=ifelse(data$Species=="versicolor",1,0)
full_model = glm(Species ~ .,data=data,family=binomial)
red_model = glm(Species ~ Sepal.Width,data=data,family=binomial)

anova(red_model,full_model,test="Chisq")
Analysis of Deviance Table

Model 1: Species ~ Sepal.Width
Model 2: Species ~ Sepal.Length + Sepal.Width + Petal.Length + Petal.Width
  Resid. Df Resid. Dev Df Deviance Pr(>Chi)
1       148     151.93
2       145     145.07  3   6.8562  0.07662 .

Essentially, if your included variables are significant under the Wald test(when you do summary(..)), then the likelihood ratio ratio should give a similar result. You can check more about this here.
Comment: Then, looking the deviance difference from my models `18.664` and knowing that when I execute the Chi-square with anova this value is `Pr(>Chi) = 0.0003` ¿Can we conclude that the study variables has explanatory power on the health-status?
Comment: Hi @JuanLuisAndiónTápiz, more or less yes.


Vue js return wrong datetime from Laravel/MySQL DB

Question: I don't know why, but when I display the datetime from a DB record in Vue JS, it's not the same datetime from the DB record.
Just before sending the records to the vue, I looked with the DD function if the records has the right datetime and everything is correct.
But when I'm looking at the record into the vue with a console.log in the mounted hook, it shows the datetime with like 4 more hours..
In DB record I get:  2022-10-31 21:30:00

In Vue js template I get: 2022-10-31 1:30:00

Why is that? I tried moment.js to try to format it, but it doesn't work. I can't find anything about this.
But when I do console.log(new Date) it's giving me the good datetime.
It seems like the vue's changing my datetime somehow.
The datetime from MySQL is just the datetime created_at columns from laravel when storing data.
Here's my vue js template, nothing special
<template>

    <AppLayout title="Alerte">
        <template #header>

                Alerte

        </template>

                        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor"
                            class="bi bi-bell-fill" viewBox="0 0 16 16">
                            <path
                                d="M8 16a2 2 0 0 0 2-2H6a2 2 0 0 0 2 2zm.995-14.901a1 1 0 1 0-1.99 0A5.002 5.002 0 0 0 3 6c0 1.098-.5 6-2 7h14c-1.5-1-2-5.902-2-7 0-2.42-1.72-4.44-4.005-4.901z" />
                        </svg>

                            Liste des alertes
                            Géré vos alertes selon la page

                            <svg xmlns="http://www.w3.org/2000/svg" width="40" height="40" fill="currentColor"
                                v-if="alerts.actives.length > 0" class="bi bi-exclamation-triangle" viewBox="0 0 16 16">
                                <path
                                    d="M7.938 2.016A.13.13 0 0 1 8.002 2a.13.13 0 0 1 .063.016.146.146 0 0 1 .054.057l6.857 11.667c.036.06.035.124.002.183a.163.163 0 0 1-.054.06.116.116 0 0 1-.066.017H1.146a.115.115 0 0 1-.066-.017.163.163 0 0 1-.054-.06.176.176 0 0 1 .002-.183L7.884 2.073a.147.147 0 0 1 .054-.057zm1.044-.45a1.13 1.13 0 0 0-1.96 0L.165 13.233c-.457.778.091 1.767.98 1.767h13.713c.889 0 1.438-.99.98-1.767L8.982 1.566z" />
                                <path
                                    d="M7.002 12a1 1 0 1 1 2 0 1 1 0 0 1-2 0zM7.1 5.995a.905.905 0 1 1 1.8 0l-.35 3.507a.552.552 0 0 1-1.1 0L7.1 5.995z" />
                            </svg>

                                Alerte(s) en cours
 0" class="ml-1">[{{ alerts.actives.length }}]

                                Toutes les alertes présentement en cours

 0">

                                        <Exclamation :nb="alert.degree" :size="25" class="animate-fade"/>

                                        {{ alert.description }}
                                        [{{ alert.created_at }}]

                                Aucune alerte pour le moment

                            <svg xmlns="http://www.w3.org/2000/svg" width="40" height="40" fill="currentColor"
                                class="bi bi-journal-text" viewBox="0 0 16 16">
                                <path
                                    d="M5 10.5a.5.5 0 0 1 .5-.5h2a.5.5 0 0 1 0 1h-2a.5.5 0 0 1-.5-.5zm0-2a.5.5 0 0 1 .5-.5h5a.5.5 0 0 1 0 1h-5a.5.5 0 0 1-.5-.5zm0-2a.5.5 0 0 1 .5-.5h5a.5.5 0 0 1 0 1h-5a.5.5 0 0 1-.5-.5zm0-2a.5.5 0 0 1 .5-.5h5a.5.5 0 0 1 0 1h-5a.5.5 0 0 1-.5-.5z" />
                                <path
                                    d="M3 0h10a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2v-1h1v1a1 1 0 0 0 1 1h10a1 1 0 0 0 1-1V2a1 1 0 0 0-1-1H3a1 1 0 0 0-1 1v1H1V2a2 2 0 0 1 2-2z" />
                                <path
                                    d="M1 5v-.5a.5.5 0 0 1 1 0V5h.5a.5.5 0 0 1 0 1h-2a.5.5 0 0 1 0-1H1zm0 3v-.5a.5.5 0 0 1 1 0V8h.5a.5.5 0 0 1 0 1h-2a.5.5 0 0 1 0-1H1zm0 3v-.5a.5.5 0 0 1 1 0v.5h.5a.5.5 0 0 1 0 1h-2a.5.5 0 0 1 0-1H1z" />
                            </svg>

                                Historique d'alertes
                                Liste de toute les alertes selon la page

                                Page
                                <select v-model="selectedPage" @change="changeTable"
                                    class="w-full border-[1px] border-gray-50 rounded-md shadow-md focus:ring-0 hover:cursor-pointer">
                                    <option v-for="page in pages" :value="page">{{ page }}</option>
                                </select>

                                <AlertTable :alerts="selectedAlerts"></AlertTable>

    </AppLayout>

</template>

Thank you!
Comment: could you show how you are trying to show on front end?
Comment: It might be a timezone issue on your frontend. Please add the code related to your question. So, someone can understand the specific issue and assist you :)
Comment: Its done! But there's nothing special
Answer: maybe the problem with timezone.suggest to use timestamp as usual.and then use   moment-timezone to format it.
for example:
import moment from 'moment-timezone';
moment.tz.setDefault('utc');

Comment: Thanks, but it didn't work!


Protocol Buffers packages issue

Question: I am new to Protocol Buffers, and I have just added the library / build requirements for my Maven project. I now have a .proto file in my source repository that has little to nothing in it:
package com.christopher.kade;
option java_package= "protocol";

message Protocol {
    required int32 id = 1;
    required string name = 2;
}

But I've found myself facing a problem when it comes to packages, the following file creates a protocol package in my com.christopher.kade one and I get an error message stating that:

Package name 'protocol' does not correspond to the file path 'com.christopher.kade.protocol'.

What is the good approach in order to generate my class in my current package? Therefore I would have:
com.christopher.kade
|- client.proto
|- MyGeneratedClass.java
|- MyClass.java

Answer: The mistake is in this line

option java_package= "protocol";

Change it to

option java_package= "com.christopher.kade";

and you are good!

Protocol Buffers packages issue


Apache2 and PHP5 won't work together

Question: I installed the latest apache web server on my system using all default configs (simply ./configure, make, make install). Then I was trying to tie PHP5 into it but I can never get it working.
First thing I did was try and get it to work with these settings:
./configure --with-apxs2=/usr/local/apache2/bin/apxs prefix=/usr/local/apache2/php --with-config-file-path=/usr/local/apache2/php --enable-force-cgi-redirect --disable-cgi --enable-shared

That was giving me this error when I was trying to 'make install':
Warning! dlname not found in /usr/local/apache2/modules/libphp5.la.
Assuming installing a .so rather than a libtool archive.
chmod 755 /usr/local/apache2/modules/libphp5.so
chmod: cannot access `/usr/local/apache2/modules/libphp5.so': No such file or directory
apxs:Error: Command failed with rc=65536

So I tired configuring with no options (other than apxs2) and was able to make and make install. This is the output of that make install:
Installing PHP SAPI module:       apache2handler
/usr/local/apache2/build/instdso.sh SH_LIBTOOL='/usr/lib64/apr-1/build/libtool' libphp5.la /usr/local/apache2/modules
/usr/lib64/apr-1/build/libtool --mode=install cp libphp5.la /usr/local/apache2/modules/
l    ibtool: install: cp .libs/libphp5.so /usr/local/apache2/modules/libphp5.so
libtool: install: cp .libs/libphp5.lai /usr/local/apache2/modules/libphp5.la
libtool: install: warning: remember to run `libtool --finish /home/max/Desktop/localhost/php-5.3.6/libs'
chmod 755 /usr/local/apache2/modules/libphp5.so
[activating module `php5' in /usr/local/apache2/conf/httpd.conf]
Installing PHP CLI binary:        /usr/local/bin/
Installing PHP CLI man page:      /usr/local/man/man1/
Installing build environment:     /usr/local/lib/php/build/
Installing header files:          /usr/local/include/php/
Installing helper programs:       /usr/local/bin/
  program: phpize
  program: php-config
Installing man pages:             /usr/local/man/man1/
  page: phpize.1
  page: php-config.1
Installing PEAR environment:      /usr/local/lib/php/
[PEAR] Archive_Tar    - already installed: 1.3.7
[PEAR] Console_Getopt - already installed: 1.3.0
[PEAR] Structures_Graph- already installed: 1.0.4
[PEAR] XML_Util       - already installed: 1.2.1
[PEAR] PEAR           - already installed: 1.9.2
Wrote PEAR system config file at: /usr/local/etc/pear.conf
You may want to add: /usr/local/lib/php to your php.ini include_path
/home/max/Desktop/localhost/php-5.3.6/build/shtool install -c ext/phar/phar.phar /usr/local/bin
ln -s -f /usr/local/bin/phar.phar /usr/local/bin/phar
Installing PDO headers:          /usr/local/include/php/ext/pdo/

I restarted the apache service and went to localhost to view a php file, and it didn't work (apache just indexes the .php files in the htdocs folder and lets me download them).
Any ideas?
Answer: Make sure, you have PHP included in the apache configuration file and that you have the correct handler set to it.
LoadModule php5_module /usr/lib/apache2/modules/libphp5.so
<IfModule mod_php5.c>
    <FilesMatch "\.ph(p3?|tml)$">
        SetHandler application/x-httpd-php
    </FilesMatch>
</IfModule>

Anyway: Are you sure, that you need Apache and PHP compiled from source? There are precompiled packages available for most Linux distributions and it's much easier to configure them.
Comment: I added that to my httpd.conf and I got this error when restarting the service: httpd: Syntax error on line 53 of /usr/local/apache2/conf/httpd.conf: Cannot load /usr/lib/apache2/modules/libphp5.so into server: /usr/lib/apache2/modules/libphp5.so: cannot open shared object file: No such file or directory
Comment: And OpenSuse does have packages from them but I wasn't sure on the defaults and they didn't show up in /usr/local
Comment: MaxMackie: If you search (find/local) your system, do you find a libphp5.so anywhere?  Perhaps you need to rebuild PHP and tell it where to install the apache module, or copy the module from some other directory.  The default OpenSuSE install directory is probably in /usr, not /usr/local
Comment: My config was just an example. According to your output the correct path could be /usr/local/apache2/modules/libphp5.so
Answer: If you're on a 64-bit OS (as it appears) you may be running into this bug which is due to different library paths for 64-bit files. There are two potential solutions listed at the end there:

Run ./configure with desired options
Edit ./libtool: add /usr/lib64 to sys_lib_search_path_spec AND sys_lib_dlsearch_path_spec
Make/Install

or

Use the bz2 PHP source download instead of the gz
Comment: Yeah I found those 2 fixes and they still didn't end up working.

Apache2 and PHP5 won't work together


Resources exceed limits big query

Question: SELECT A,B, C, D, E, F ,EXTRACT(MONTH FROM PARSE_DATE('%b',Month))
as MonthNumber,PARSE_DATETIME(' %Y%b%d ', CONCAT(CAST(Year AS STRING),Month,'1'))
as G FROM `XXX.YYY.ZZZ`
where A !='null' and B = 'MYSTRING' order by A,Year

The query processes about 20 GB per run.
My table ZZZ has 396,567,431 (396 million) rows with a size of 53 GB. If I execute the above query without a LIMIT clause , I get an error saying "Resources exceeded".
If i execute it with a LIMIT clause , then it gives the same error for larger limits.
I am writing a python script using the API that runs the query above and then computes some metrics and then writes the output to another table. It writes some 1.7 million output rows, so basically aggregates the first table based on column A i.e original table has multiple rows for column A.
Now I know we can set Allow large results to on and select an output table to get around this error but for the purposes of my script it doesn't server the purpose.
Also , I read that order by is the expesnive part causing this but below is my algorithm and I dont see a way around order by.
Also my script pages the query results 100000 rows at a time.
log=[]
    while True:
        rows, total_rows, page_token = query_job.results.fetch_data(max_results=100000, page_token=page_token)
        for row in rows:
            try:
                lastAValue=log[-1][0]
            except IndexError:
                lastAValue=None

            if(lastAValue==None or row[0]==lastAValue):
                log.append(row)
            else:
                res=Compute(lastAValue,EntityType,lastAValue)
                allresults.append(res)
                log=[]
                log.append(row)
        if not page_token:
            break

I have two questions :
Column A |  Column B ......
123      | NDG
123      | KOE
123      | TR
345      | POP
345      | KOP
345      | POL
The way I kept my logic is : I iterate through the rows and check if column A is same as last row column A. If same , then I add that row to an array. The moment I encounter a different column A i.e 345 , I send the first group of column A for processing , compute and add the data to my array. Based on this approach I had some questions :
1) I am effectively querying only once . So , I should be charged only for 1 query. Does big query charge as per totalRows/noOf pages ? i.e will individual pages from above code be separate query and charged separately ?
2) Assume page size in the above example would be 5 , what would happen is the 345 entries would be spread across pages , in this case will I lose information about the 6 th 345 -POL entry as it will be in a different page ? Is there a work around for this ?
3)Is there a direct way to get around the whole check the successive rows if they differ in values ? like a direct group by and get groups as array mechanism ? The above approach takes a couple of hours (estimated ) to run if i add a limit of 1 million.
4) How can I get around this error of Resources exceeded by specifying higher limits than 1 million.?
Comment: why not just group by and let bigquery do the aggregation?
Comment: I get this error : SELECT list expression references columns (B,C,D ) which is neither grouped nor aggregated
Comment: Do you mind to share that query in the original post?
Answer: You are asking BigQuery to produce one huge sorted result, which BigQuery currently cannot efficiently parallelize, so you get the "Resources exceeded" error.
The efficient way to perform this kind of queries is to allow your computation to happen in SQL inside of BigQuery, rather than extracting huge result from it, and doing post-processing in Python. Analytical functions is common way to do what you described, if the Compute() function can be expressed in SQL.
E.g. for finding value of B in last row before A changes, you can find this row using LAST_VALUE function, something like
select LAST_VALUE(B) OVER(PARTITION BY A ORDER BY Yeah) from ...

If you could describe what Compute() does, we could try to fill details.

Resources exceed limits big query


Should we use READ transaction?

Question: A few years ago I read ODL recommendation not to use READ operation but instead use Data Change Listener or some of its variation. Is it still valid recommendation?
Looking at the ODL code, I got impression that each transaction commit is applied to "In Memory Data Store" immediately during the commit simultaneously with sending notification to the listener. Is it correct?
Why in this case, reading is not as efficient as using the notification?
Answer: Where did you read this recommendation? It depends on your use case. Using a data tree change listener (DTCL) with your own cache is going to have faster access than issuing a read operation, especially in a clustered environment if the shard leader is remote. However maintaining your own cache via a DTCL is eventually consistent, meaning your cache may not have up-to-date data. This has to be considered for the use case. If you need strong consistency, then you must use read operations.
Comment: Actually, I am surprised by such solution. Updating the memory data store with each commit is not for free.  If even it does not affect CPU performance directly it definitely affects the memory consumption. The notifications are processed asynchronously. Each of them contains the data tree before and after.  Eventually, it affects CPU by increasing the time needed to GC.
I would prefer if the data store were updated in batch mode basing on the number of transactions and/or time iterval.

Should we use READ transaction?


If a morphism of abelian groups is an isomorphism when tensorized with $\mathbb{R}$, is it also an isomorphism when tensorized with $\mathbb{Q}$?

Question:
Question. Let $f : A \to B$ be a morphism between two abelians groups. Suppose that the induced morphism $\bar{f} : A \otimes_{\mathbb{Z}} \mathbb{R} \to B \otimes_{\mathbb{Z}} \mathbb{R}$ defined by $\bar{f}(a \otimes x) = f(a) \otimes x$ is an isomorphism. Is it necessarily the case that the induced morphism $A \otimes_{\mathbb{Z}} \mathbb{Q} \to B \otimes_{\mathbb{Z}} \mathbb{Q}$ is an isomorphism?

Motivation. In homotopy theory, a continuous map between based spaces $f : X \to Y$ is called a rational homotopy equivalence if $\pi_n(f) \otimes \mathbb{Q} : \pi_n(X) \otimes \mathbb{Q} \to \pi_n(Y) \otimes \mathbb{Q}$ is an isomorphism for each $n$. Similarly, it's called a real homotopy equivalence if $\pi_*(f) \otimes \mathbb{R}$ is an isomorphism. It's clear that a rational homotopy equivalence is a real homotopy equivalence: $(- \otimes_{\mathbb{Z}} \mathbb{Q}) \otimes_{\mathbb{Q}} \mathbb{R} \cong - \otimes_{\mathbb{Z}} \mathbb{R}$. Is the converse true?
Progress. When $A$ and $B$ are finitely generated abelian groups, the statement is true. Use the decomposition as a direct sum of a torsion group and a free abelian group, so that $A \otimes \mathbb{R} \cong \mathbb{R}^r$ and $B \otimes \mathbb{R} \cong \mathbb{R}^s$. Since there's an isomorphism, $r=s$, and the determinant $\det(f \otimes \mathbb{R})$ is nonzero; but this determinant is equal to $\det(f \otimes \mathbb{Q})$ (in fact it's an integer, equal to $\det(f)$), so $f \otimes \mathbb{Q}$ is also invertible.
I haven't been able to generalize that to abelian groups that are not finitely generated. I suspect the answer is that it's false, but I couldn't come up with a counterexample (surjectivity seems to be the main problem).
Comment: What you're asking is whether $\mathbb{R}$ is faithfully flat over $\mathbb{Q}$, don't you? Hint: $\mathbb{Q}\subset \mathbb{R} $ is a direct summand (as $\mathbb{Q}$-vector spa e).
Comment: Let me say that if $R\subset S$ is a ring extension and $R$ is a direct summand of $S$ (as an $R$-module), then $S$ is not necessarily $R$-flat. (Of course, this is not the case for field extensions.)
Comment: Dear @user26857, you're right. My hint was meant to point towards the *faithfully*. Of course, arguing via freeness as you did is quicker...
Comment: By the way, if anyone is reading this: a real homotopy equivalence is *not* what I wrote in my question. In general it's simply a morphism between the real minimal models of the spaces; it doesn't have to induce a continuous map!
Answer: $\mathbb R$ is a faithfully flat $\mathbb Q$-module (since it is free). Then the sequence $0\to A\otimes_{\mathbb Z}\mathbb Q\to B\otimes_{\mathbb Z}\mathbb Q\to0$ tensorized by the $\mathbb Q$-module $\mathbb R$ is exact, so it is exact.


Connecting to Out-of-Band devices from Virtual machine

Question: We recently had one of our locations go down for ~4 hours over the weekend due to a switch failure. Despite this being our agreed upon outage window, management was not happy with the outcome for a number of reasons.
This location is remote from all company IT resources so we had to send our remote Cisco vendor out to reprogram the Distribution switch replacement that was sent with an employee from a neighboring location.
Like they often say the best way to get your company interested in fire alarms is to have a fire. Management is now very interested in reducing this "unacceptable" time table as much as possible (They asked for 10 minutes, we laughed[Secretly of course].)
One of the things I have proposed in the past is to add a few layers of Out-of-Band to each location such as:

A Laptop/Micro PC with a 4G modem and Teamviewer connected with console cables to equipment.
A POTS line connected to a modem based Out of Band console server.

Our infrastructure is mostly centralized using VMWare in a single data center, we use SIP based VoIP.
I am having trouble finding the best way to be able to dial up and get a console session on a console server that has a built in modem from a virtual machine (WIN10). Management was very clear that we be able to connect Anytime/Anywhere to any location to have immediate access to program or troubleshoot switches.
I am ok with any solution that can solve this problem, including paid services, equipment, or Voodoo magic. I believe it would be acceptable to purchase a pots line for our data center but it would need to be able to be used from the VM.
We have a Cisco Call Manager in house but as we only use SIP we do not have a router that handles any T1 lines or other resources (Everything is over the DS3 we have).
Answer: There seems to be a disagreement about the service level here. Come to a compromise on what it should actually be before implementing something. Risk analysis of the downtime plus cost estimates of potential solutions will help guide the discussion.
Be sure to include costs of any additional staff needed to provide that kind of response time.
For this specific failure, a spare pre-programmed switch on site might be possible to install with remote hands. Automatic failover could also be done with a bit more design complexity.
I don't know how you would implement dial in from a Windows VM. The solution doesn't necessarily have to be a VM, if a small server with a modem works. Nor does it have to be dial up, if you can connect redundant cable/DSL/LTE  connections from different providers to the branch routers.


Read only certain columns from a text file

Question: I need to read from a text file and only get certain data from it. The text file has multiple lines, similar to below
12/05/2014 06:52 c:\BACKUPS\INT100\BACKUP\BACKUP.ZIP
12/05/2014 06:51 c:\BACKUPS\INT1000\BACKUP\BACKUP.ZIP

I need the date, time and the number (in this case 100 and 1000), but can't figure out how to get rid of the other stuff like "c:\backups\INT" and "\BACKUP\BACKUP.ZIP".
I thought of using a substring method but it will only partially work really. Plus the INT number can be between 1-9999.
This is what I've got at the moment read data from text file into DataTable and then into a GridView:
StreamReader readData = new StreamReader(@"c:\Users\1484814\desktop\date.txt");

DataTable listOFDates = new DataTable();
listOFDates.Columns.Add("Dates");

while (!readData.EndOfStream)
{
    string shortenLine = readData.ReadLine();

    // shortenLine = shortenLine.Substring(0, 35);

    listOFDates.Rows.Add(shortenLine);
}
gv_textFile.DataSource = listOFDates;

Comment: It has 'lots of lines', or 'all lines' like the example you shown? Is the path always the same (except the number)?
Comment: Are you familiar with the `string.Split()`
Comment: yeah path is always the same only thing that changes is the date and the int number (INT100, INT101, INT103 etc)
Answer: A possible solution
 StreamReader readData = new StreamReader(@"c:\Users\1484814\desktop\date.txt");

 DataTable listOFDates = new DataTable();
 listOFDates.Columns.Add("Dates", typeof(DateTime));
 listOFDates.Columns.Add("Numbers", typeof(int));

 while (!readData.EndOfStream)
 {
     string line = readData.ReadLine();
     string[] parts = line.Split(' ');
     DateTime dt = DateTime.ParseExact(string.Join(" ", parts[0], parts[1]), "dd/MM/yyyy hh:mm", CultureInfo.CurrentCulture, DateTimeStyles.None);
     int number = Convert.ToInt32(Regex.Match(parts[2], @"\d+").Value);
     listOFDates.Rows.Add(new object[] {dt, number});
 }
 gv_textFile.DataSource = listOFDates;

Of course, this assumes that your date part is exactly always in the above format and that your numbers inside the path are just present one time in that position.
Answer: If all lines are the same, you can get the dates and then the numbers with those one liners:
var text = File.ReadAllLines(@"c:\Users\1484814\desktop\date.txt");

var dates = text.Select(line => DateTime.Parse(line.Substring(0, 16)));
var numbers = text.Select(line => line.Substring(31, line.IndexOf(@"\BACKUP\") - 31));

For the dates, you take the start of string and parse it to a DateTime.
For the numbers, get to the number index, then take stuff until you hit the \BACKUP\ part (which is the minimal unique part after the number). The -31 is because Substring takes a length, not an end index.
If you extract the magic numbers:
const int END_OF_DATE = 16;
const int START_OF_NUMBER = 31;

var text = File.ReadAllLines(@"c:\Users\1484814\desktop\date.txt");

var dates = text.Select(line => DateTime.Parse(line.Substring(0, END_OF_DATE)));
var numbers = text.Select(line => line.Substring(START_OF_NUMBER, line.IndexOf(@"\BACKUP\") - START_OF_NUMBER));

You end up with two IEnumerables, which you can feed your rows with.
There's multiple ways to add your value afterwards, but if we follow what you were doing (adding manually each entry as a row), you could achieve that result by looping over the values with a for loop:
DataTable listOFDates = new DataTable();
listOFDates.Columns.Add("Dates");
listOFDates.Columns.Add("Numbers");
for (int i = 0; i < dates.Count(); i++)
{
    listOFDates.Rows.Add(dates[i], numbers[i]);
}

We can safely iterate both lists with the same index since we know they have the same size.
However this method requires you transform the previous LINQ queries into a list by adding .ToList() and the end of both dates and numbers queries. If you wish to keep it as a generic IEnumerable instead of a list, you can use .ElementAt(i) instead of [i].
Comment: This looks like a good solution but im not sure how to get the values from the two IEnumerables?
Answer: If "12/05/2014 06:51 c:\BACKUPS\INT1000\BACKUP\BACKUP.ZIP" is a consistent format, then you can do, assuming Lines is a string[] with the lines of your file:
string[] Lines= File.ReadAllLines("file.txt");

foreach(var Line in Lines)
{
 string[] Parameters= Line.Split(' ');
 string Date= Parameters[0];
 string Time= Parameters[1];
 string[] PathInfo= Parameters[2].Split('\\');
 int Number= Convert.ToInt32(PathInfo[2].Replace("Int",""));
}

If your path isn't always the same I can provide you with another example.
Answer: If you're working with a DataTable, you can also use OLEDB to work with the text file like a database. You'd interact with the file using SQL queries.
Just import System.Data.OleDb and use the OleDb objects (connection, datareader, etc) like you would any other database. You won't have stored procedures, of course, but you can use parameterized queries.
This also works for Excel files if you use the right connection string.
For more information:
http://www.connectionstrings.com/textfile/
This isn't the right approach all the time, but sometimes it's what you need.


Breakpoints do not stay on their line in debugger both in Chrome and VS Code

Question: I am stuck trying to figure out why my debuggers do not place the breakpoints on their appropriate lines.
As you can see in the graphics below, the breakpoints do not work as expected:
Misbehaving breakpoints in Chrome

For VS code this is the script I am running:
"test-script": "env-cmd -f ./config/dev.env nodemon --inspect-brk --exec 'babel-node ./tests/$TEST_SCRIPT'"
Disappearing breakpoints in VS Code

I'm not sure if this is a babel/webpack misconfig or something set wrong in the debuggers.

In .babelrc I have tried setting sourceMaps to true, "both",
and "inline" but that doesn't fix things.
In my webpack config I
have devtool = source-map and mode = development.

I would really prefer not to put console.log statements everywhere and use the debugger as it was intended so any help would be greatly appreciated.
Thanks!
Comment: I don't know if it's the same thing, but in other languages, when the breakpoint isn't in it's actual position, means that some code was added or removed after the compilation. Does this ring any bells?
Answer: That looks like what happens when you're transpiling async functions for target environments that don't have them. They end up being so thoroughly transformed so that regeneratorRuntime can handle them that even source maps can't help. I solve it by setting up the project not to transpile async functions during dev and debugging on a modern browser that supports them directly. Then we do testing on target pre-async browsers with the production (transpiled) build. If we have to track down a problem that only happens when transpiling (very rare), we turn it back on for dev and insert debugger; statements. :-|
Comment: Thanks TJ, I thought I was going crazy trying to figure this out. One of the answers to the link provided here questions mentions this **using the default env settings. If you change the env string to, say, chrome>60 (or, in fact, interestingly >4%!), the code is passed through as-is, as Chrome > 60 supports async/await and arrow functions natively.** which fixed it for me in both debuggers. https://stackoverflow.com/questions/52704820/disable-promise-transpilation-using-babel-preset-env
Comment: Is there any way to solve this without disabling the transpiling of async functions during dev? I mean sure that's a good way, but this may cause errors to slip through to prod unnoticed.
Maybe newer versions of babel will do better at the source mapping task ?
Comment: @sktguha - Effective source mapping of `async` function code to the resulting regenerator runtime state machine code appears to be a ***very*** hard problem. I've never seen it done well. But I've also never (literally never) seen a problem where production transpiled code using regenerator runtime had a bug that the equivalent `async` function code run directly did not.
Comment: "But I've also never (literally never) seen a problem where production transpiled code using regenerator runtime had a bug that the equivalent async function code run directly did not."
Oh I see. If no bug happens then yes, for better DX then the answer is good, yes.
Comment: @sktguha - Can't say it's never happened to someone else. :-) Just not to me.
Comment: @T.J.Crowder I see. Any scenario where you think this bug might occur ? I am thinking some weird combination of async, await and traditional .then code, with async success or failure callback for .then etc ?
Comment: @sktguha - Fundamentally, it would require that the transpiled code be incorrect. E.g., a bug in the transpiler.
Comment: Yes understood. I was trying to think of more specific case ok how the bug could occur. Could probably get an idea by looking at the GitHub issues on the relevant babel plugin


Custom container.html.twig

Question: I need to delete a div made by the container.html.twig. How can I rename this template to this specific region?

thx.
Comment: Possible duplicate http://drupal.stackexchange.com/questions/220237/override-a-template-for-only-one-route
Answer: Copy core template to your theme template folder (yourtheme/templates) core/themes/stable/templates/form/container.html.twig and clear caches.
Comment: I don't think this is the correct answer. I assume that they're asking how to specifically remove the container in that one instance, not sitewide. It only suggests a global template rather than ones that are more specific. The answer would probably really be to use a preprocess.

Custom container.html.twig


Otimização de Múltiplos POST via Ajax

Question: Eu tenho uma pequena aplicação, e fui construindo ela conforme fui conhecendo o Laravel, então hoje em dia tem coisas que vejo que estão erradas e procuro adequar às boas práticas de programação e um dos pontos-chave são as intermináveis inclusões no db, via ajax.
Bom para entenderem melhor a estrutura da aplicação é a seguinte:

O sistema é um grande banco de referências de texto, video, imagem, url, são entradas numa coluna do banco de dados;
O sistema possibilita uma reordenação dos itens, usando a função sortable do jQueryUI;
A grande questão é, atualmente tenho 448 entradas (ordenadas por id decrescente) e se por exemplo eu quiser definir que a última entrada que fiz, ex: #449, seja a primeira a ser exibida (no caso ordem:0), preciso mapear e mandar um post re-mapeando todas as outras entradas...

Minha principais dúvidas, são:

Como posso enviar as index atualizadas num post só, aliviando o DB?
Como gerar uma resposta depois que a lista for atualizada?

Vou postar apenas a função de update e a função do ajax, caso precisem de mais infos posto aqui.
//Controller
public
function updateOrdem() {
    $entries = $this->entrada->orderBy('ordem', 'ASC')->get();
    $itemID = Input::get('itemID');
    $itemPos = Input::get('itemPos');
    foreach($entries as $entry) {
        return DB::table('entradas')->where('id', '=', $itemID)->update(array('ordem' => $itemPos));
    }
}

//AJAX
$('#entradas ul').sortable({
    revert: true,
    cancel: "#entradas ul li span, .modal",
    stop: function (e, ui) {
        $.map($(this).find('li'), function (el) {
            var itemID = el.id
            var itemPos = $(el).index();
            console.log('pos' + itemPos);
            console.log('id' + itemID);
            $.ajax({
                type: "POST",
                url: "updateOrdem",
                data: {
                    itemID: itemID,
                    itemPos: itemPos
                },
                dataType: 'html',
                done: function () {
                    console.log('ok');
                }
            });
        });
    }
});

http://laravel.io/bin/MXE8
Answer: Para ter apenas um POST, utilize o .ajaxSuccess e dispare o callback por ele.
    $(document).ajaxSuccess(function() {

        $('#entradas ul').sortable({
            revert: true,
            cancel: "#entradas ul li span, .modal",
            stop: function (e, ui) {
                $.map($(this).find('li'), function (el) {
                    var itemID = el.id
                    var itemPos = $(el).index();
                    console.log('pos' + itemPos);
                    console.log('id' + itemID);
                    $.ajax({
                        type: "POST",
                        url: "updateOrdem",
                        data: {
                            itemID: itemID,
                            itemPos: itemPos
                        },
                        dataType: 'html',
                        done: function () {
                            console.log('ok');
                        }
                    });
                });
            }
        });
$( ".log" ).text( "O callback dispara aqui: " );
});

Agora com relação ao Loop que faz para inserir no DB, a única forma que vejo seria enviar um json com todos os valores e depois fazer uma função usando o .extract_json_value (caso seja MySql).
Como você está utilizando o Eloquent, não sei se seria legal ficar usando function... mas não vejo outra saída.
P.S: Não testei nada... é apenas uma sugestão.
Comment: Eu testei o .ajaxSuccess, no ambiente local que tenho apenas 7 entradas e ele está retornando múltiplas respostas também (as 7 no caso), além disso no load da página ele já está inserindo os callbacks (estranhamente no load ele insere 9 callbacks)
Comment: Você já tentou chamar o sortable totalmente vazio? Ex: `$('#elemento').sortable({ stop: function() { console.log('stop'); } });` e  `$('#elemento').sortable({ stop: function() { console.log('stop'); } });` . Dá uma olhada se ele dispara esses callbacks.

Otimização de Múltiplos POST via Ajax


Deviance residuals in Poisson GLM

Question: I am learning the concept of residuals in modelling. I performed a Poisson GLM for a 3x3 contingency table and I got the summary of the model. My question is: the deviance residual from the in-built function resid is differing from the residuals calculated manually using the formula 2 * (y * log(ifelse(y == 0, 1, y/mu)) - (y - mu)). Why are the values different? What am I doing wrong here?
Example:
counts=c(0,1,2,2,0,8,8,13,16)
outcome=gl(3,1,9)
treatment=gl(3,3)
mod=glm(counts~outcome+treatment,family=poisson())
resid(mod,type="deviance")
##         1          2          3          4          5          6          7
##-1.0954451  0.1694307  0.3374099  0.0000000 -2.3664319  1.1368934  0.2176802
##         8          9
## 0.7886223 -0.7609947
fitted.values=mod$fitted.values
dev= 2*(counts*log(ifelse(counts==0,1,counts/fitted.values))-(counts-fitted.values))
##             1             2             3             4             5
##  1.200000e+00  2.870677e-02  1.138454e-01 -2.928413e-23  5.600000e+00
##            6             7             8             9
## 1.292527e+00  4.738466e-02  6.219251e-01  5.791129e-01

My guess is that I am giving a value 1 for all zero counts here. If I applied the formula without imputing a value 1 then the result shows infinite. How are the deviance residuals being calculated in glm?
Answer: You're calculating the deviance per point. The deviance residual is $\textrm{sign}(y-\mu) \sqrt{d_i}$. You need to take the square root (after setting values less than zero, like the tiny residual value for observation 4, to zero), then apply the sign of the difference:
d.res <- sqrt(pmax(dev,0))
sign(counts-fitted.values)*d.res

Comment: Thank you very much.. But when I use pmax(dev,0) the result will not exactly same as I get in resid function because the negative value of dev is taken to be 0 here right?? How to sort this out?
Answer: I had a similar question. If you crack open stats:::residuals.glm you can find the relevant code:
d.res <- sqrt(pmax((object$family$dev.resids)(y, mu, wts), 0))
ifelse(y > mu, d.res, -d.res)

Deviance residuals in Poisson GLM


How we can get the value entered in search API autocomplete field in jQuery?

Question: I got a requirement to send the search text to GTM for tracking purpose. I have a field which is from search api autocomplete module. I am not getting the value in jQuery on click of submit button. I tried like below but no success:
var search_key = $('.path-frontpage .ui-autocomplete-input').attr('value');

Can anybody implemented such thing. Please help
DOM:
<input placeholder="Search MyP&O" data-drupal-selector="edit-keywords" data-search-api-autocomplete-search="search" class="form-autocomplete form-text form-control ui-autocomplete-input" data-autocomplete-path="/search_api_autocomplete/search?display=page&&filter=keywords" type="text" id="edit-keywords" name="keywords" value="" size="30" maxlength="128" autocomplete="off">

Comment: An obvious thing, but in your selector you've got .path-frontpage which will obviously only work when on the homepage. Are you definitely trying on your homepage?
Comment: Yes @Leigh. i'm trying there only.
Answer: This works for me:
var search_key = $('.path-frontpage .ui-autocomplete-input').val();

Comment: thanks for responding. But for me its showing empty value. I will post my DOM structure. Please check.


How to notate alternate/secondary melody in ABC

Question: I'm not able to find any indication that you can do this in ABC, and I was able to use a couple of Ideographic Space characters in the lyrics to make it kinda work and get the lyrics to align, but thought I'd ask anyway. Is there a way to notate the alternate notes for the melody of the second verse?
This is the sheet music I'm trying to replicate:
Answer: You can come fairly close:
X:0
T:lyrics alignment
K:none
M:none
%%score (V1 V2)
[V:V1] A2 A4 y/8 GF
[V:V2] A2 y/8 A2- AAGF
w: joke kid, __ it's a
w: pay kid, _ for what you

The required code segment is

%%score (V1 V2)
[V:V1] A2 A4 y/8 GF
[V:V2] A2 y/8 A2- AAGF
w: joke kid, __ it's a
w: joke kid, _ for what you

I tried using grace-notes to finesse the small-font notes, but they don't allow for a quarter-note, can't control the stem direction, and can't align lyrics to them.
Answer: This works on http://www.mandolintab.net/abcconverter.php but not in FiveLineSkink 2.0 Beta, so it might depend on the software you use:

    [| A2 A4- GF &\
     A2 A2 AAGF|]

The &\ is what allows us to express multiple voices.
Answer: The answer you seek I believe is here, in section 4.6.3
http://abcnotation.com/wiki/abc:standard:v2.1:proposals:clefs_voice_parameters:v2
Just in case it helps anyone else:
This is called a different 'voice'. The origin of this is harmony (chords) originate in people singing together. Chord literally means in accord - with one another in French. Usually the top voice is 1 and any addtional voices are 2, 3 or etc. By ABC notation do you mean tradition sheet music?
Comment: ABC is a notation system. You can read more here: http://abcnotation.com/wiki/abc:standard:v2.1. For a summary, have a look at the [Meta page.documentation](https://music.meta.stackexchange.com/questions/2782/documentation-for-abcjs?noredirect=1&lq=1)
Comment: I knew nothing about this. Reminds me of Lilypond


Gmap Location in views - exposed filter by distance/proximity and post code

Question: I am currently working with Drupal 7 and Location 7.x-3.4 module
I have created a view, choose the Gmap format, and added the post code and distance field in filter section, so that the visitors are able to search for the locations they want.
Gmap Settings:

Data Source = Location.module
Marker handling = Use single marker type

Here is my configuration for the Location: Distance / Proximity :

Expose this filter to visitors, to allow them to change it = 1
Filter type to expose = Distance / Proximity
Operator = Proximity (Circular)
Postal code = Blank
Distance = Blank
Origin = Postal Code (assume default country)
Filter identifier = distance

After saving the changes, the result is not changing. Is anyone knows what's wrong with my configuration above? Please help..
Comment: What do you mean by "the result is not changing"? Do you mean when a user entersa value into the exposed filter and submits it doesn't work, or something else?
Comment: Also it's worth pointing out that this doesn't relate to the gmap module, it relates to the location module. What version of the location module are you using.
Comment: Hi Rooby, I'm currently using 7.x-3.4

When I hit submit, it doesn't work.
Comment: Do you get errors or no results when there should be some or results that shouldn't be there?
Comment: There's no errors at the moment. The display of the pointers in the map are as is when I hit submit. There is no change in the results.
Answer: It's a bit hard to say for sure but my guess is that you have missed a step when installing the location module.
For post code proximity searching the location module uses a database of postcodes and their coordinates to convert the postcode to the lat/lon coordinates that are then used to calculate whether other locations fall in the request distance.
See installation step 6 in the INSTALL.txt file of the location module.

(Optional) Import a postal codes database for the countries served by your    website, to support proximity searches and other useful
  features. Postal    code databases may be found in the "databases/"
  sub-directory of the    Location module directory. The files are in
  the format of zipcodes.CC.mysql,    where CC is a two-letter country
  code such as 'us' or 'de'.
Note: If your site is using table prefixes, you will need to adjust
  for this    manually, by opening the file in a text editor and
  replacing 'zipcodes' with    'prefix_zipcodes' throughout.
To import the files from the command line, enter the following:
cd sites/SITENAME/modules/location
   mysql -u username -p database-name < database/zipcodes.us.mysql

Note that this proximity functionality may not work for some countries if the data is not available.
Comment: Hi Rooby, it works perfectly! Thank you so much for your help :)


Probability of Limsup of a bunch of events

Question: In "Probability Theory" by Athreya, I encountered the following question:
Let $\{A_n\}_{n=1}^\infty$ be a sequence of events on a common probability space. Suppose
$$\sum_{n=1}^\infty P(A_n\setminus A_{n+1}) < \infty \quad(1)$$
and $\lim_{n \to \infty} P(A_n) = 0$, show that
$$P[\limsup A_n] = 0$$
Moreover show that one can replace $\lim_{n \to \infty} P(A_n) = 0$ with $$P(\liminf_{n \to \infty} A_n)=\lim_{n \to \infty} P(\bigcap_{j\geq n} A_j) = 0$$
My attempt:
I was able to show the first part. But the second part i.e. to show the replacement was kind of tricky. I tried various things including trying to show
$$\bigcup_{n=1}^\infty A_n = \bigcup_{n=1}^\infty \left\{(A_n\setminus A_{n+1})\cup \bigcap_{j \geq n}A_j\right\}$$
but I am not really sure if this is correct (For the result, a $\leq$ would suffice). This was inspired from the following identity (which I have proved for $m \geq 1$)
$$ \bigcup_{n=1}^m A_n = \bigcup_{n=1}^m \left\{(A_n\setminus A_{n+1})\cup \bigcap_{j = n}^{m+1}A_j\right\}$$
In trying to prove it for the $\infty$ case mentioned above, I ran into a technical difficulty, namely the switching of limits and infinite sums. Hence I am stuck here. Perhaps there is another way.
Kindly request clarifications if necessary and provide suitable hints (as opposed to whole answers). If I get it, I will provide the complete solution.
Update: Athreya gives a hint: He asks us to show that
$$A \cap B^c \subset \liminf A_n$$
where $A = \limsup A_n$ and $B = \limsup B_n$. The result would then follow from Borel Cantelli Lemma as $(1) \Rightarrow P(B)=0 \Rightarrow P(A \cap B) = 0$ which would imply
$$P(A) = P(A \cap B) + P(A \cap B^c) \leq 0 + P(\liminf A_n) =0$$
Answer: Ok, according to this, courtesy Daniel Fischer,
$$\bigcup_{n=k}^\infty A_n = \bigcup_{n=k}^\infty \left\{(A_n\setminus A_{n+1})\cup \bigcap_{j \geq n}A_j\right\}$$
is correct (although it does not necessarily follow from the arguments I gave earlier). Proof is by logical induction:
Suppose $x \in A_{k_0}$ for some $k_0 \geq n$, then if $x \in A_{k}\setminus A_{k+1}$ for some $k\geq n$, then done. Suppose not, then note that $x \not\in A_{k_0}\setminus A_{k_0+1}$. But since $x \in A_{k_0}$, this means $x \in A_{k_0+1}$. Continuing in this fashion, we get $x \in A_{j}, \forall j \geq k_0$. Or to put it in another way,
$$x \in \bigcap_{j \geq k_0}A_j$$
Since $\bigcap_{j \geq k_0}A_j \subset \bigcup_{n=k}^\infty \bigcap_{j \geq n}A_j $, we thus have
$$\bigcup_{n=k}^\infty A_n \subset \bigcup_{n=k}^\infty \left\{(A_n\setminus A_{n+1})\cup \bigcap_{j \geq n}A_j\right\}$$
We can prove the other way also although that is not required for the main proof. Hence we have
$$ P\left[\bigcup_{n=k}^\infty A_n\right]\leq P\left[\bigcup_{n=k}^\infty \left\{(A_n\setminus A_{n+1})\cup \bigcap_{j \geq n}A_j\right\}\right] \\
\leq \sum_{n=k}^\infty P\left[A_n \setminus A_{n+1}\right] + P\left[\bigcup_{n=k}^\infty \bigcap_{j \geq n}A_j\right] \\
= \sum_{n=k}^\infty P\left[A_n \setminus A_{n+1}\right] + P[\liminf A_n]$$
Take limits to get the result. $\blacksquare$


How can i filter NSMutableArray by firstName with non-alphabetical characters

Question: I want to filter the Array, where name starts with non-alphabetical characters. I want to display the contacts where firstName starts with non-alphabetical characters under different section in table view. I tried below code, but it crashing , please find reason below:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"NOT(firstName BEGINSWITH[c] %@)",arrIndex]; //where arrIndex is the array of alphabetical characeters.
  NSArray  *arrContacts = [arrayTotalContacts filteredArrayUsingPredicate:predicate];

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Can't do a substring operation with something that isn't a string (lhs = iPhone rhs = (
    A,
    B,
    C,
    D,
    E,
    F,
    G,
    H,
    I,
    J,
    K,
    L,
    M,
    N,
    O,
    P,
    Q,
    R,
    S,
    T,
    U,
    V,
    W,
    X,
    Y,
    Z
))'
arrayTotalContacts has the below data:
(
{
    firstName = iPhone;
    lastName = "";
},
{
    firstName = Madhu;
    lastName = "";
},
{
    firstName = "Swa";
    lastName = "";
},
{
    firstName = TechV;
    lastName = "";
},
{
    firstName = Vedika;
    lastName = Vt;
}
)

Comment: Edit you question with datasource.
Comment: @Reformer: I edited the question with the data.
Answer: You can use regular expression with a Core Data predicate:
[NSPredicate predicateWithFormat:@"NOT (firstName MATCHES %@)", @"^[A-Za-z].*"]

where ^[A-Za-z].* is a regex for all strings that do start with A-Z or a-z.
To make it work with letters from foreign languages as well (e.g. "Ä"), use
the Unicode property name:
[NSPredicate predicateWithFormat:@"NOT(firstName MATCHES %@)", @"^\\p{Letter}.*"]

Here ^\\p{Letter}.* is a regex for all strings that start with a letter.
But if this is for a table view, you might better use a fetched results controller
and its sectionNameKeyPath parameter. See for example here:

NSFetchedResultsController with sections created by first letter of a string

for some examples how to group a table view according to the initial letter. It should be
possible to modify the code to group all names that do not start with a letter into
a separate group.
Comment: This works fine for me, but if the name is empty i am not getting that object in the result, i want that object in the result, how can i fix it?
Comment: @PalchuriSudheerKumar: I have updated the answer, it should now work with an empty string as well.
Answer: Try this out,
NSArray * arrContacts = [arrayTotalContacts  valueForKeyPath:@"firstName"];

Hope it helps :)


Gibbs Sampler transition kernel

Question: Let $\pi$ be the target distribution on $(\mathbb{R}^d,\mathcal{B}(\mathbb{R^d}))$ which is absolutely continuously wrt to the $d$-dimensional Lebesgue measure, i.e :
$\pi$ admits a density $\pi(x_1,...,x_d)$ wrt to $\lambda^d$ with
$$\lambda^d(dx_1,...,dx_d) = \lambda(dx_1) \cdot \cdot \cdot \lambda (dx_d)$$
Let us assume that the full conditionals $\pi_i(x_i|x_{-i})$ from $\pi$ are known.
So the transition kernel of the Gibbs-Sampler is clearly the product of the full conditionals from $\pi$.
Is the transition kernel absolutely continuously wrt to the $d$-dimensional Lebesgue measure too ?
Comment: You're fortunate to have one of the authors answering your question.
Comment: i am so confused about the chapter of convergence properties of the gibbs sampler written by casella and Robert. sry for this question it is rather obvious but i need to be sure because it is for my master thesis
Comment: sorry about our chapter confusing you...!
Answer: If you write down the transition of the systematic Gibbs sampler kernel, you get
$$\mathbb{P}(X'\in A_1\times\cdots\times A_d|X=x)=\int_{A_1} \pi_1(x'_1|x_{-1})\Big\{\int_{A_2} \pi_2(x'_2|x'_1,x_{-1:2})\cdots \left\{\int_{A_d} \pi_d(x'_1|x_{-d}')\lambda(\text{d}x_d')\right\} \cdots\lambda(\text{d}x_2')\Big\}\lambda(\text{d}x_1')$$
for any product set $A_1\times\cdots\times A_d\in\mathcal{B}(\mathbb{R^d})$ and therefore
$$K(x,x')=\pi_1(x'_1|x_{-1})\times\pi_2(x'_2|x'_1,x_{-1:2})\times\cdots\times\pi_d(x'_d|x_{-d}')$$
is the density of a probability measure that is absolutely continuous against the Lebesgue measure on $(\mathbb{R}^d,\mathcal{B}(\mathbb{R^d}))$.
Comment: that is really funny :). thank you again now i feel very comfortable about my chapter for the convergence properties of the gibbs sampler. i really want to thank you for the chapter of convergence properties for the metropolis-hastings ! the minimal necessary conditions are brilliant and i really write down a beautiful proof for the irreducibility of the corresponding markov chain of the MH-Algo.

Gibbs Sampler transition kernel


max number of text lines + ellipsis

Question: I have multiple titles with different lenghts and i would like them to always take 1 line and leave suspension points/ellipsis (...) if they can't fit. I can't just change the text inside the divs because the h2s inside them will automatically change everyday.
Heres my code: http://jsfiddle.net/FranLegon/k9LsLuuk/
You can see what I want to achieve at Medium : https://i.stack.imgur.com/q2Jc3.png
PS: If my english isn't good enough feel free to edit my question
EDIT: I got an asnswer that works perfectly for 1 line, but now I want the text to take 2 lines instead. Any ideas?
Comment: I have used this module: https://www.npmjs.com/package/ellipsize for this kind of situation. Check if it can help you.
Answer: Since luckily you want one line,
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;

should work for you. MDN docs., fiddle
Comment: @FranLegon: Then you're currently out of luck with pure CSS, but http://stackoverflow.com/a/7680712/505649 has some good pointers.

max number of text lines + ellipsis