text:
Q: Java - Testing Two TCP Clients With One Computer For class I am required to build a program using a TCP connection.
We are given the sample code below to work with and understand how to build a connection.  The server and client communicate properly when I have only one client running.  When I attempt to start a new instance of the client to simulate two people using the client with one server, the second client can not send or receive and never displays the message "Got I/O Connection".  Why is this?
Here is the sample code.
// Fig. 27.5: Server.java
// Server portion of a client/server stream-socket connection.
import java.io.EOFException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

public class Server extends JFrame
{
   private JTextField enterField; // inputs message from user
   private JTextArea displayArea; // display information to user
   private ObjectOutputStream output; // output stream to client
   private ObjectInputStream input; // input stream from client
   private ServerSocket server; // server socket
   private Socket connection; // connection to client
   private int counter = 1; // counter of number of connections

   // set up GUI
   public Server()
   {
      super( "Server" );

      enterField = new JTextField(); // create enterField
      enterField.setEditable( false );
      enterField.addActionListener(
         new ActionListener()
         {
            // send message to client
            public void actionPerformed( ActionEvent event )
            {
               sendData( event.getActionCommand() );
               enterField.setText( "" );
            } // end method actionPerformed
         } // end anonymous inner class
      ); // end call to addActionListener

      add( enterField, BorderLayout.NORTH );

      displayArea = new JTextArea(); // create displayArea
      add( new JScrollPane( displayArea ), BorderLayout.CENTER );

      setSize( 300, 150 ); // set size of window
      setVisible( true ); // show window
   } // end Server constructor

   // set up and run server
   public void runServer()
   {
      try // set up server to receive connections; process connections
      {
         server = new ServerSocket( 12345, 100 ); // create ServerSocket

         while ( true )
         {
            try
            {
               waitForConnection(); // wait for a connection
               getStreams(); // get input & output streams
               processConnection(); // process connection
            } // end try
            catch ( EOFException eofException )
            {
               displayMessage( "\nServer terminated connection" );
            } // end catch
            finally
            {
               closeConnection(); //  close connection
               ++counter;
            } // end finally
         } // end while
      } // end try
      catch ( IOException ioException )
      {
         ioException.printStackTrace();
      } // end catch
   } // end method runServer

   // wait for connection to arrive, then display connection info
   private void waitForConnection() throws IOException
   {
      displayMessage( "Waiting for connection\n" );
      connection = server.accept(); // allow server to accept connection
      displayMessage( "Connection " + counter + " received from: " +
         connection.getInetAddress().getHostName() );
   } // end method waitForConnection

   // get streams to send and receive data
   private void getStreams() throws IOException
   {
      // set up output stream for objects
      output = new ObjectOutputStream( connection.getOutputStream() );
      output.flush(); // flush output buffer to send header information

      // set up input stream for objects
      input = new ObjectInputStream( connection.getInputStream() );

      displayMessage( "\nGot I/O streams\n" );
   } // end method getStreams

   // process connection with client
   private void processConnection() throws IOException
   {
      String message = "Connection successful";
      sendData( message ); // send connection successful message

      // enable enterField so server user can send messages
      setTextFieldEditable( true );

      do // process messages sent from client
      {
         try // read message and display it
         {
            message = ( String ) input.readObject(); // read new message
            displayMessage( "\n" + message ); // display message
         } // end try
         catch ( ClassNotFoundException classNotFoundException )
         {
            displayMessage( "\nUnknown object type received" );
         } // end catch

      } while ( !message.equals( "CLIENT>>> TERMINATE" ) );
   } // end method processConnection

   // close streams and socket
   private void closeConnection()
   {
      displayMessage( "\nTerminating connection\n" );
      setTextFieldEditable( false ); // disable enterField

      try
      {
         output.close(); // close output stream
         input.close(); // close input stream
         connection.close(); // close socket
      } // end try
      catch ( IOException ioException )
      {
         ioException.printStackTrace();
      } // end catch
   } // end method closeConnection

   // send message to client
   private void sendData( String message )
   {
      try // send object to client
      {
         output.writeObject( "SERVER>>> " + message );
         output.flush(); // flush output to client
         displayMessage( "\nSERVER>>> " + message );
      } // end try
      catch ( IOException ioException )
      {
         displayArea.append( "\nError writing object" );
      } // end catch
   } // end method sendData

   // manipulates displayArea in the event-dispatch thread
   private void displayMessage( final String messageToDisplay )
   {
      SwingUtilities.invokeLater(
         new Runnable()
         {
            public void run() // updates displayArea
            {
               displayArea.append( messageToDisplay ); // append message
            } // end method run
         } // end anonymous inner class
      ); // end call to SwingUtilities.invokeLater
   } // end method displayMessage

   // manipulates enterField in the event-dispatch thread
   private void setTextFieldEditable( final boolean editable )
   {
      SwingUtilities.invokeLater(
         new Runnable()
         {
            public void run() // sets enterField's editability
            {
               enterField.setEditable( editable );
            } // end method run
         }  // end inner class
      ); // end call to SwingUtilities.invokeLater
   } // end method setTextFieldEditable
} // end class Server

// Fig. 27.7: Client.java
// Client portion of a stream-socket connection between client and server.
import java.io.EOFException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

--
public class Client extends JFrame
{
   private JTextField enterField; // enters information from user
   private JTextArea displayArea; // display information to user
   private ObjectOutputStream output; // output stream to server
   private ObjectInputStream input; // input stream from server
   private String message = ""; // message from server
   private String chatServer; // host server for this application
   private Socket client; // socket to communicate with server

   // initialize chatServer and set up GUI
   public Client( String host )
   {
      super( "Client" );

      chatServer = host; // set server to which this client connects

      enterField = new JTextField(); // create enterField
      enterField.setEditable( false );
      enterField.addActionListener(
         new ActionListener()
         {
            // send message to server
            public void actionPerformed( ActionEvent event )
            {
               sendData( event.getActionCommand() );
               enterField.setText( "" );
            } // end method actionPerformed
         } // end anonymous inner class
      ); // end call to addActionListener

      add( enterField, BorderLayout.NORTH );

      displayArea = new JTextArea(); // create displayArea
      add( new JScrollPane( displayArea ), BorderLayout.CENTER );

      setSize( 300, 150 ); // set size of window
      setVisible( true ); // show window
   } // end Client constructor

   // connect to server and process messages from server
   public void runClient()
   {
      try // connect to server, get streams, process connection
      {
         connectToServer(); // create a Socket to make connection
         getStreams(); // get the input and output streams
         processConnection(); // process connection
      } // end try
      catch ( EOFException eofException )
      {
         displayMessage( "\nClient terminated connection" );
      } // end catch
      catch ( IOException ioException )
      {
         ioException.printStackTrace();
      } // end catch
      finally
      {
         closeConnection(); // close connection
      } // end finally
   } // end method runClient

   // connect to server
   private void connectToServer() throws IOException
   {
      displayMessage( "Attempting connection\n" );

      // create Socket to make connection to server
      client = new Socket( InetAddress.getByName( chatServer ), 12345 );

      // display connection information
      displayMessage( "Connected to: " +
         client.getInetAddress().getHostName() );
   } // end method connectToServer

   // get streams to send and receive data
   private void getStreams() throws IOException
   {
      // set up output stream for objects
      output = new ObjectOutputStream( client.getOutputStream() );
      output.flush(); // flush output buffer to send header information

      // set up input stream for objects
      input = new ObjectInputStream( client.getInputStream() );

      displayMessage( "\nGot I/O streams\n" );
   } // end method getStreams

   // process connection with server
   private void processConnection() throws IOException
   {
      // enable enterField so client user can send messages
      setTextFieldEditable( true );

      do // process messages sent from server
      {
         try // read message and display it
         {
            message = ( String ) input.readObject(); // read new message
            displayMessage( "\n" + message ); // display message
         } // end try
         catch ( ClassNotFoundException classNotFoundException )
         {
            displayMessage( "\nUnknown object type received" );
         } // end catch

      } while ( !message.equals( "SERVER>>> TERMINATE" ) );
   } // end method processConnection

   // close streams and socket
   private void closeConnection()
   {
      displayMessage( "\nClosing connection" );
      setTextFieldEditable( false ); // disable enterField

      try
      {
         output.close(); // close output stream
         input.close(); // close input stream
         client.close(); // close socket
      } // end try
      catch ( IOException ioException )
      {
         ioException.printStackTrace();
      } // end catch
   } // end method closeConnection

   // send message to server
   private void sendData( String message )
   {
      try // send object to server
      {
         output.writeObject( "CLIENT>>> " + message );
         output.flush(); // flush data to output
         displayMessage( "\nCLIENT>>> " + message );
      } // end try
      catch ( IOException ioException )
      {
         displayArea.append( "\nError writing object" );
      } // end catch
   } // end method sendData

   // manipulates displayArea in the event-dispatch thread
   private void displayMessage( final String messageToDisplay )
   {
      SwingUtilities.invokeLater(
         new Runnable()
         {
            public void run() // updates displayArea
            {
               displayArea.append( messageToDisplay );
            } // end method run
         }  // end anonymous inner class
      ); // end call to SwingUtilities.invokeLater
   } // end method displayMessage

   // manipulates enterField in the event-dispatch thread
   private void setTextFieldEditable( final boolean editable )
   {
      SwingUtilities.invokeLater(
         new Runnable()
         {
            public void run() // sets enterField's editability
            {
               enterField.setEditable( editable );
            } // end method run
         } // end anonymous inner class
      ); // end call to SwingUtilities.invokeLater
   } // end method setTextFieldEditable
} // end class Client

A: Issue is in Server class. This class is single threaded (main thread). Main thread is being used for both accepting new connection and reading from socket. Main thread after accepting connection goes to processConnection method and blocks on following call.
message = ( String ) input.readObject(); // read new message
This call is made in a loop which terminates only if you receive 'TERMINATE' from client
   } while ( !message.equals( "CLIENT>>> TERMINATE" ) );

until above loop is running code can't return to 'runServer' method, which can accept connection using 'waitForConnection'.
You need to separate threads to accept connection and read from connected sockets.


text:
Q: How does a plugin resize it's window When I load a pdf with the following html the pdf plugin seems to resize it's windows to accommodate the complete length of the pdf file. I'm wondering how the plugin does that?

<!DOCTYPE html>
<html>
<head>
<title>Test html object tag</title>
<style type = "text/css">
    html
    {
        height: 100%;
    }

    body
    {
        margin: 0;
        padding: 0;
        height: 100%;
    }

    .my_style
    {
        width: 100%;
        min-height: 100%;
    }
</style>
</head>

<body>
    <div class="my_style">
        <object class = "my_style" data="data/test.pdf" type="application/pdf"></object>
    </div>

</body>
</html>

As far as I understand it the size of a window that is provided to a plugin is defined in the html object tag.
Thanks,
Christian

A: This is pure speculation, since I don't have the source to said plugin, but if I were trying to solve this issue I would simply get a reference to the object tag of my plugin and set the width and height.
Haven't tested this code, but something along these lines should probably work:
FB::DOM::ElementPtr elem(m_host->getDOMElement());
elem->setWidth(640);
elem->setHeight(480);

Obviously wherever you do that you need access to the BrowerHostPtr (m_host).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Getting parenthood of tree structure I am trying to retrieve a tree structure i want specific levels of 'parenthood'. my table has level of depth, pathIndex and mapping. my first approach was to make some kinds of substrings to be able to look for the value via the mapping, but I am getting multiple errors on conversion of strings. one thing that might be possible is that if i try and query an item that is not at the lowest level it should return null for the levels it is missing.
In the table if i where to query for the line while asterisks
Id                                     depth    pathindex   ItemNumber
4CF91F7F-832E-468D-B44A-E14DC66E710A     0          0        0.0
D34784A3-2134-4D09-828E-0EDA0C275C43     1          1        1
38158804-3EBC-4841-B1AF-1B86AD153010     2          1        1.1
8E25D494-322F-45F9-8A91-2A385F561C71     3          1        1.1.1
**64EB6C43-FF9C-0FF9-133F-01F4F21DA14F**     4          1        1.1.1.1
13AFA35C-80F8-405A-8980-33C3F7733EE2     2          2        1.2
3F1332E9-4D42-4BD8-9423-598430E94CB5     3          1        1.2.1
B3CC1306-A122-46F6-8F67-30FBABA3B590     4          1        1.2.1.1
C3F27C8E-F96B-4498-A85F-E4FC8EA90ED7     4          2        1.2.1.2

This is how it should be looking for the information, the static string are the ones i don't know how to generate in order to get nulls when asking for a level that is not that deep.
Select top 1 VehicleGroupId as Region
      from GroupHierarchy where GroupHierarchy.numericalmapping = '1'
Select top 1 VehicleGroupId as gz
      from GroupHierarchy where GroupHierarchy.numericalmapping = '1.1'
Select top 1 VehicleGroupId as cedis
      from GroupHierarchy where GroupHierarchy.numericalmapping = '1.1.1'

A: Instead of putting decimals between your hierarchy members rather use forwardslashes (1/2/3) and then you can use Microsoft SQL hiearchy data type and functions to easily join and retain the structure:
https://www.sqlshack.com/use-hierarchyid-sql-server/


text:
Q: RDP VirtualBox Ubuntu 12.04LTS Windows 7 There are many RDP questions out there, none of the ones I've read up to now have the exact same problem.
I have:
A Dedicated server running Ubuntu 12.04LTS
 An installation of VirtualBox with two instances of Windows 7
In order to RDP to the virtualised OS's I need to set the adapter to
bridged, I have read that on so many tutorials & supprt sites etc.
When i do this, according to tutorials, the IP address should be assigned
within the same range as the server and then I can RDP to the VM...
.. this doesnt work for me.
Do i need to forward the SERVER-IP:PORT to the VM-IP:PORT to be able to
access RDP ?
Do i need to alter the /etc/network/interfaces ?
or could it be due to DHCP ?
Update:
I've not configured anything on the Ubuntu Dedicated Server as of yet, but I have tried all
types of 'Attached To' adapters in VirtualBox.
I don't know if this is relevant at all, but when i edit the VM only NAT ( adapter type ) seems to have the ability to access internet. All other ( including Bridged ) fail to connect to internet ( but cannot be pinged from the Ubuntu Server ).
I have to be honest here, this is the FIRST time i've tried to set this up, and in all the guides and tutorials, when selecting 'Bridged Adapter', it should just work. This is a head scratcher for me !
UPDATE :
It appears that RDP gets only as far as the Ubuntu xrdp service.
I stopped it
Now need to route the RDP traffic to the VM
( i think ) ....
TO CLOSE:
The server IP Tables were not being updated by ufw, a 'fasthosts feature' is that they use a different location for the firewall, once i had opened the ports and forwarded them the connection was allowed. Also for anyone else in this perdicament, I hope this helps !
Regards ;)

A: When you access a VM with RDP, its IP adress can be anything. I suspect you tried to connect to the VM instead of host.
In your RDP client, you must enter:
dedicated_host_name_or_IP:RDP_port_number_of_the_VM
for instance:
localhost:5001 # if I connect a VM running on my Virtual Box server.
192.168.1.25:5000 # IP adress of my dedicated server not of the VM.
Edit
There are two ways to use RDP on your VMs:

*

*Using the host machine as the RDP server. It works only if you activate the "Remote Display" server in your VMs setting (chapter Display). Using this will work even if your VM network configuration is incorrect.

*Using the VM itself as RDP server (I suspect it's what your trying to do). Then, you have to configure the TCP/IP options in the VM, not only the Virtual Box settings. Maybe you use the default DHCP option there. If this don't work with the bridged adapter setting (and works with the NAT), try this:

In the VB settings, make sure your bridged adapter is linked to your main interface (the one giving access to Internet to the VB host). Open the "Advanced options" and enable "Cable connected".
In the TCP/IP settings of the VM, choose DHCP. Restart the connection if needed.
If this don't work, open a terminal in the VM and type ipconfig to know if your VM got a working IP address.


text:
Q: Is it possible to generate true random numbers using software only? Looking around a bit I have found that most solutions for generating a true random number involves inspecting natural phenomenon.
But is it really necessary?
I mean, assuming that Pi has random infinite sequence of digits as far any system could tell, couldn't we just build an algorithm which will look something like this (assuming 64 bits architecture):

*

*Take the first 64 bits.

*Cast the bits into double

*Take next 64 bits

*Cast the bits into double

*etc...

Of course this could be enhanced (involving seeds, casting to Integers and so on...)
Does this sounds right or am I missing something?
Note:
About the assumption about pi, according to Wikipedia it is widely believed that Pi is a Normal number.
Shouldn't this be enough? If it can't be disproved, Shouldn't it be enough for any practical system?

A: No, it's absolutely not possible!
On a deterministic machine, you can compute deterministic sequences. There is no randomness to be
found. Even chaotic systems are just deterministic sequences.
You can indeed generate a deterministic sequence which appears to have the same distribution of
digits as one would expect from a randomly generated one. But it's still deterministic.
Pi is completely deterministic: If you and I both generate the sequence of digits in Pi, we both
get the same numbers.
I believe you are right in saying the distribution of digits seems to be uniform: but this raises the obvious question: where do we start? We need to choose a random place to start in the sequence to make it 'truly random': thus we are back to square one.
In practice we use sources of what seems to be randomness: Linux will look at times between disc accesses, and keystrokes, and the exact time. But with a little work we can predict all of these more and more accurately, or alter them by fixing our environment.
Hardware random number generators use quantum processes which are believed to be truly random. For example, performing a quantum measurement is believed to be a perfectly random process: no 'better' knowledge of the initial state can help predict the output state (as with chaotic systems).
A paper absolutely worth reading on this subject is "On random and hard to describe numbers" by Bennett, it's quite easy to find with a quick Google.
And here's a nice related XKCD :)

A: Sure. But why go to all that trouble? Computing π is a complicated task, and it is hard to reason about the results. Also, as far as I know there is no algorithm which will produce digits of π in constant time.
On the other hand, pseudo random generators like the Mersenne twister are designed to be fast to compute, are easily seeded, and allow some amount of analysis (in the case of the twister, the cycle length, for example).
However you compute pseudo-random number sequences, you leave yourself open to prediction attacks if the algorithm is known. (That would be particularly easy in the case of mathematical constants like π.) If you're using the random number as part of a security system, the suspicion that the bad guys could predict the sequence would be an obvious vulnerability.
So for such purposes, "natural" phenomena can have their uses.

A: Isn't Pi a natural phenomenon as well?


text:
Q: QCA blowfish decryption fails I'm trying to use QCA to encrypt/decrypt files.
When i use this code to encrypt, everything works fine (or seems to, at least).
But when i try to decrypt, the process() method returns an empty SecureArray.
Does anyone have an idea why and/or how to fix it?
void FileCrypto::crypt(QByteArray key, bool crypt){
    QCA::Initializer init;
    open();
    Cipher cipher = initializeCipher(key, crypt);
    QTextStream in(source);                                            //lecture ligne par ligne
    while (!in.atEnd()) {
        QString line = in.readLine();
        SecureArray secureData = line.toAscii().data();                        //securise les donnees
        if(!crypt)
            QString temp = QString::fromAscii(secureData.toByteArray().toHex());
        qDebug() << "Données lues : " << secureData.data();
        SecureArray cryptedData = cipher.process(secureData);                  //(de)crypte les donnees
        qDebug() << "Données cryptées :" << cryptedData.data();
        destination->write(cryptedData.data());                    //ecris dans le nouveau fichier

    }
    close();
}

void FileCrypto::open() throw (QString){
    if(!source->open(QIODevice::ReadOnly | QIODevice::Text)
        || !destination->open(QIODevice::WriteOnly | QIODevice::Text)){
        throw QString("Impossible d'ouvrir les fichiers cibles.");
    }
}

void FileCrypto::close(){
    source->close();
    destination->close();
}

Cipher FileCrypto::initializeCipher(QByteArray akey, bool crypt){
    QCA::InitializationVector iv;
    Direction direction;
    SymmetricKey key = SymmetricKey(akey);
    iv = InitializationVector(akey);

    if(crypt){
        direction = Encode;
    }else{
        direction = Decode;
    }

    return Cipher(QString("blowfish"),Cipher::CBC,
                  Cipher::DefaultPadding, direction, key, iv);
}


text:
Q: How can I lower the CPU usage on MySQL queries? We are running a Wowonder-based social site for a little community and as soon as we hit 100 users online, our site becomes extremely slow due to high CPU usage. The script itself should be fine because none of the other customers have issues with this so I believe something on our side is doomed. This is our glances report with a hundred users online:
glances report.
As you can see, our CPU usage is way too high, even after setting cache policies. We tried running without query_cache but the result was the same.
[mysqld]
innodb_buffer_pool_instances = 26
innodb_file_per_table = 1
innodb_read_io_threads = 16
innodb_write_io_threads = 16
innodb_buffer_pool_size = 26G
innodb_io_capacity=300
innodb_log_file_size=3G
performance_schema=ON
table_definition_cache=10000
join_buffer_size=256M
skip-name-resolve
key_buffer_size     = 512M
max_allowed_packet  = 512M
thread_stack        = 192K
thread_cache_size       = 10
myisam_recover_options  = BACKUP
max_connections        = 1000
query_cache_type = 1
query_cache_limit = 256K
query_cache_min_res_unit = 2k
query_cache_size = 50M
As said before, the code itself should be fine because it runs well on other instances but not on this one. Any ideas would be highly appreciated. Let me know if I can assist somehow, I'm out of ideas.

A: As a general rule, high CPU usage means slow (poorly indexed or poorly designed) queries. Configuration generally has a much smaller impact, and bad configuration will typically make your CPU usage lower and queries slower.
Having said that, some parts of your configuration are egregiously poor:
join_buffer_size=256M

This is quite likely increasing your CPU usage and crippling your performance. Comment it out, leave it on default value.
You almost certainly don't need to touch these away from defaults, so consider commenting them out:
thread_stack        = 192K
thread_cache_size       = 10

These usually do more harm than good:
query_cache_type = 1
query_cache_limit = 256K
query_cache_min_res_unit = 2k
query_cache_size = 50M

Consider replacing with:
query_cache_type = 0
query_cache_size = 0

A: My answer is to complement @Gordan Bobic
Check which queries are slow:
mysql -e "SELECT * FROM INFORMATION_SCHEMA.PROCESSLIST WHERE COMMAND<>'Sleep' and TIME > 5"

For each query that is slow run an EXPLAIN on the query. You can install Percona Tools and run pt-visual-explain to have a better representation of the EXPLAIN statement.
If you are using InnoDB engine, you can see what it is doing with:
mysql -e "show engine innodb status \G"

Other details can be found in MySQL Performance Schema which includes a profiler too. Here is a Percona article about the profiler.
If you want to have a better picture of the CPU utilization, you can use perf + FlameGraphs.


text:
Q: Problema incomum no Eclipse Galera estou iniciando na linguagem de programação Java, mas está dando um erro incomum, as linhas de código estão certas mas não consigo resolver, já configurei as variáveis de ambiente(nem sei o que é isso) pelo youtube, e parece que teve um progresso mas ainda da o mesmo erro, veja o código a seguir:

A: Tente colocar no arquivo eclipse.ini (provavelmente vai estar no diretório de instalação do Eclipse) a seguinte linha imediatamente antes da sentença -vmargs:
-vm %JAVA_HOME%\bin\javaw.exe
Se não der certo, ao invés de javaw.exe tente java.exe.
Outro erro pode ser as variáveis de ambientes. Veja minha resposta nessa pergunta: Para que serve as variáveis do SO relacionadas ao Java?.
Nota: Abra o arquivo eclipse.ini com o bloco de notas (notepad), e caso ele esteja separado em linhas, coloque em uma nova linha -vm e na outra linha o resto.
Se o comando javac não funciona então o erro está em algum lugar relacionado ao Java, e não ao Eclipse. Muito provavelmente as variáveis de ambiente. Se possível favor editar a pergunta mostrando o que acontece ao digitar java --version e javac --version.


text:
Q: ActionBarSherlock with Action Bar Style Generator for the last few days I'm trying to implement custom theme, which is created by Action Bar Style Generator to my application. I'm able to use theme with some generic samples from SDK, but I'm not able to use it with my application which uses ActionBarSherlock.
My application with ActionBarSherlock is a modified sample of Tabs and Pager.
Steps which I do:

*

*Create theme with Android Action Bar Style Generator.

*Copy theme to res folder inside my application.

*Change theme in Manifest file.

After those steps only 'Action bar color' changes to correct one. All other styles are not used in application. I have tried many different approaches which I found online, but without success.
Thank you very much for your help.

A: Did you add the proper items to your App's theme in styles.xml? You need to use attributes that are NOT prefixed with android:, for example:
<item name="actionBarStyle">@style/Widget.Styled.ActionBar</item>
<item name="background">@drawable/bg_striped</item>
<item name="backgroundSplit">@drawable/bg_striped_split</item>

You would also keep the properly prefixed ones for Android versions that have native actionbar.
<item name="android:actionBarStyle">@style/Widget.Styled.ActionBar</item>
<item name="android:background">@drawable/bg_striped</item>
<item name="android:backgroundSplit">@drawable/bg_striped_split</item>

The best place to understand this is to look at the demo provided with the ActionBarSherlock library project.

A: I managed to fix the problem.

*

*I missed android:background attribute in TabWidget. This partially
solves the problem.

*I had to set setLeftStripDrawable and setRightStripDrawable programatically.


text:
Q: Customizing Adaptive Card appearance using RenderedAdaptiveCards inside bot framework SDK I am developing a Bot using Microsoft Bot Framework. I am using Adaptive Cards for displaying flights to users but they have a lot of limitations on their appearance. I am trying to render the adaptive card from one of the dialogs within my bot framework by creating a adaptive card renderer using my own hostconfig.json and then attaching the Html of my adaptive card back to the chat window. But its not working :(
    public static Attachment CreateFlight(Flight flight)
    {
        var renderedAdaptiveCard = AdaptiveCardRenderer
            .RenderCard(new AdaptiveCard
            {
                Body = new List<AdaptiveElement>
                {
                    new AdaptiveContainer {Items = CreateFlightAdaptiveElements(flight)}
                },
                Actions = new List<AdaptiveAction>
                {
                    new AdaptiveShowCardAction
                    {
                        Card = new AdaptiveCard
                        {
                            Body = new List<AdaptiveElement>
                            {

                            },
                            Actions = new List<AdaptiveAction>
                            {
                                new AdaptiveSubmitAction
                                {
                                    Title = "Select",
                                    Data = flight.Segments.Select(x => $"{x.Airline} {x.FlightNo}")
                                        .Aggregate((i, j) => i + "/" + j),

                                }
                            },
                            BackgroundImage = new Uri($"{DomainUrl}/Images/ac_background.jpg")
                        },
                        Title = "Select"
                    },

                },
                BackgroundImage = new Uri($"{DomainUrl}/Images/ECEFF1.png")
            });

        var attachment = new Attachment
        {
            ContentType = "application/html",
            Content = renderedAdaptiveCard.Html
        };

        return attachment;
    }

Am I trying something that is impossible here ? How to change the default grey looks of my bot ? My primary channels would be Skype, Slack etc so I don't have plans to integrate this to a Web Chat. Kindly help me with this regard.

A: The idea behind Adaptive Cards is to allow each channel to render the cards in a way that's specific to that channel. A card "adapts" to any environment that might support it. While Adaptive Cards offer a lot of flexibility, the bot can only do so much because it's ultimately the channel that's in charge of rendering the card.

Card Authors describe their content as a simple JSON object. That
  content can then be rendered natively inside a Host Application,
  automatically adapting to the look and feel of the Host.
For example, Contoso Bot can author an Adaptive Card through the Bot
  Framework, and when delivered to Skype, it will look and feel like a
  Skype card. When that same payload is sent to Microsoft Teams, it will
  look and feel like Microsoft Teams. As more host apps start to support
  Adaptive Cards, that same payload will automatically light up inside
  these applications, yet still feel entirely native to the app.
Users win because everything feels familiar. Host apps win because
  they control the user experience. And Card Authors win because their
  content gets broader reach without any additional work.

As you probably know, the RenderedAdaptiveCard type is meant to be used in client-side code. That means it can help you if you want to make your own channel for example, but it's not really meant to be used in a bot. Your code isn't working because there is no HTML attachment type and most channels don't support HTML at all. You can find more information in this question and this GitHub issue.
Hopefully you can achieve the appearance you're looking for using the tools available to you, such as images and links.


text:
Q: Jquery Shorthand if else code return undefined variable 50% of the time WHY does this work
var hash = "find.asp?find=something"
var findParam = hash.indexOf('=') ? hash.split('=')[1] : hash;

$('#test').html(findParam);

RESULT: "something"
But THIS doesn't ?
var hash = "something"
var findParam = hash.indexOf('=') ? hash.split('=')[1] : hash;

$('#test').html(findParam);

RESULT: Uncaught TypeError: Cannot read property 'split' of undefined
The only difference is the variable.
If the variable contain '=' it should be treated one way, and if not...
https://jsfiddle.net/3eLan1hv/9/

A: So I solved it:
like this:
var findParam = (hash.indexOf('=') != -1) ? hash.split('=')[1] : hash;

I added != -1 to the control and voilá


text:
Q: Angular2 - Using POST with angular-in-memory-web-api I am playing around with angular-in-memory-web-api for Angular 2. So far I have only been using GET calls and it's working well.
The API I'm going to call is only using POST calls so I began rewriting my GET calls to POST calls, but then they stopped returning the mock data. In my test function bellow, I want to get the data as a TestResponse object by an id:
postTest(id: string): Promise<TestResponse> {
    return this.http
        .post(this.testUrl, JSON.stringify({ testId: id }), { headers: this.headers })
        .toPromise()
        .then(response => response.json().data as TestResponse)
        .catch(this.handleError);
}

And the mock data:
    let test = [
        { testId: 'e0d05d2b-3ec3-42ae-93bc-9937a665c4d6', missingData: 'qwerty', moreMissingData: 'asdfgh' },
        { testId: 'dccef969-b9cf-410a-9973-77549ec47777', missingData: 'qwerty', moreMissingData: 'asdfgh' },
        { testId: '20716fd7-1f50-4a12-af16-52c009bc42ab', missingData: 'qwerty', moreMissingData: 'asdfgh' }
    ];

If I understand this right, this code will assume that I want to create something and is therefor bouncing my testId back together with id: 1 (which doesn't even follow my data structure).
So, my question is, how can I get my mock data with POST calls?

A: It is possible to override HTTP methods in your in memory data service implementation.
In the overridden method (e.g POST), it is possible to react to the collection name (via the RequestInfo parameter) to provide specific functionality on a per-endpoint/collection basis.
A provided example deals with GET calls only: https://github.com/angular/in-memory-web-api/blob/master/src/app/hero-in-mem-data-override.service.ts
From that, overriding the POST functionality could look like this:
import { InMemoryDbService, RequestInfo, STATUS, ResponseOptions } from 'angular-in-memory-web-api';

export class Your InMemoryDataService implements InMemoryDbService {

  // ...

  post(requestInfo: RequestInfo) {
    const collectionName = requestInfo.collectionName;
    if (collectionName === 'somedatatype') {
      // Intercept POST calls to the 'somedatatype' collection:
      // E.g. add some fields to our entity that would be set in the backend,
      const data = requestInfo.utils.getJsonBody(requestInfo.req);
      const collection = requestInfo.collection;
      data.extraField = 'hello';

      // set id to next highest number
      data.id = collection.map(item => item.id).reduce((cur, next) => cur > next ? cur : next) + 1;

      // ... add the item to the collection
      collection.push(data);

      // forge the response
      const options: ResponseOptions = {
        body: { data  },
        status: STATUS.OK,
        headers: requestInfo.headers,
        url: requestInfo.url
      };

      // use createResponse$ to return proper response
      return requestInfo.utils.createResponse$(() => options);
    }

    // let the default POST handle all other collections by returning undefined
    return undefined;
  }
}


text:
Q: Select/Highlight column range (A-L) for every specific cell values ('Apple') in every row I'm trying to find an easy way to get rid of 'bad' rows in my worksheet, which has 3780 rows. Instead of scanning through and deleting each rows every time, which is time consuming, I was wondering if there was an easier way?
Perhaps by making a macro that highlights cells in a column range (A-L) every time it finds the bad value (e.g. 'Apple') in a cell located in every row.
Something along the lines of:
If =ISTEXT() then delete row

I hope this makes sense, let me know if not.

A: This small macro will search for the presence of apple in any cell in columns A through L and delete that row:
Sub KillBadApple()
    Dim rng As Range
    Set rng = Intersect(ActiveSheet.UsedRange, Range("A:L"))

    nLastRow = rng.Rows.Count + rng.Row - 1
    nFirstRow = rng.Row

    For i = nLastRow To nFirstRow Step -1
        exam = ""
        For j = 1 To 12
            exam = exam & Chr(1) & Cells(i, j).Text
        Next j

        exam = LCase(exam)
        If InStr(exam, "apple") > 0 Then
            Cells(i, j).EntireRow.Delete
        End If
    Next i
End Sub


text:
Q: Limiting use of filesharing services I live in an apartment with 3 other roommates, and we share the internet connection though a wireless router (Level One WBR-3406TX). One of the roommates is always running utorrent, and it is slowing down everybody's connection way too much. Unfortunately, he feels like he shouldn't have to give up on downloading stuff, and is refusing to stop hogging the bandwidth. I was wondering if there's something I can do to the router configuration that would disrupt his use of utorrent just enough to to make the internet usable for the rest of us, and still have it work well enough for him so that he doesn't start poking around looking for answers.

A: You're looking for QoS or Quality of Service controls. These allow you to regulate the priority based on IP/port or type of traffic (HTTP, bittorrent, ssh, VoIP, etc.)
I don't know if that router supports it, but if you have a spare computer lying around, or if you pick up a Linksys WRT54GL ($70), you can install an alternate firmware such as Tomato or DD-WRT which will allow you to set bittorrent traffic, or all traffic coming from his computer to low priority. This will allow him to use full bandwidth if it's available, but if someone else starts to use the web or watch a youtube video, the router will automatically throttle/limit the bittorrent to make bandwidth available for other things.
This would only be a last resort - See if he'll settle for setting uTorrent to cap at half or 3/4ths of your available bandwidth, as this allows him to continue downloading without 'hogging' all the available bandwidth. Ultimately it's up to whoever is paying for the connection.

A: Looking at the spec sheet for that router, it supports QoS (Quality of Service) for traffic to either a specific port or IP. You can set his traffic to the lowest priority, which wouldn't effect him while you are idle, but would throttle his traffic if there is contention.


text:
Q: I'm trying to know the country that pays the highest salary from select last_name, country_name, SUM(salary)
from employees e JOIN departments d ON (e.department_id= d.department_id)
JOIN locations L ON (d.location_id = L.location_id)
JOIN Countries Cc ON (L.country_id = Cc.country_id)
JOIN regions Rr ON (Cc.region_id = Rr.region_id)
GROUP BY country_name;

A: You want to only show the best rows of your intermediate result. As of Oracle 12c you could use the FETCH FIRST n ROWS clause for this. Until Oracle 11g, you should use a window function instead:
SELECT country_name, sum_salary
FROM
(
  select
    c.country_name,
    SUM(e.salary) AS sum_salary,
    MAX(SUM(e.salary)) OVER () AS max_sum_salary
  from employees e
  JOIN departments d ON e.department_id = d.department_id
  JOIN locations l ON d.location_id = l.location_id
  JOIN countries c ON l.country_id = c.country_id
  GROUP BY c.country_name
)
WHERE sum_salary = max_sum_salary
ORDER BY country_name;

A: Code you posted wouldn't compile; it lacks LAST_NAME in the GROUP BY (which is, basically, wrong as it would make what you're doing impossible) or - a better idea - remove it from the SELECT statement's column list.
Using RANK analytic function, you'd then have
WITH data
     AS (  SELECT country_name,
                  SUM (salary) sumsal,
                  RANK () OVER (ORDER BY SUM (salary) DESC) rn
             FROM employees e
                  JOIN departments d ON (e.department_id = d.department_id)
                  JOIN locations L ON (d.location_id = L.location_id)
                  JOIN Countries Cc ON (L.country_id = Cc.country_id)
                  JOIN regions Rr ON (Cc.region_id = Rr.region_id)
         GROUP BY country_name)
SELECT country_name, sumsal
  FROM data
 WHERE rn = 1;

I don't have your tables nor data so - for illustration - I'll use Scott's sample schema. Simplified, it would be like this:
SQL> select deptno, sum(sal)
  2  from emp
  3  group by deptno
  4  order by 2 desc;

    DEPTNO   SUM(SAL)
---------- ----------
        10      13750        --> this is a department you need
        20      10995
        30       9400

So:
SQL> WITH data
  2       AS (  SELECT deptno,
  3                    SUM (sal) sumsal,
  4                    RANK () OVER (ORDER BY SUM (sal) DESC) rn
  5               FROM emp
  6           GROUP BY deptno)
  7  SELECT deptno, sumsal
  8    FROM data
  9   WHERE rn = 1;

    DEPTNO     SUMSAL
---------- ----------
        10      13750

SQL>


text:
Q: outbound messages limit I would like to mass update leads which have workflow rules that update records in another sytem.
Is there outbound messsages limit in SFDC? As I'm using the Unlimited Edition, I understand I have unlimited API requrests but wondering if SOAP API migh impact the number of outbound messages sent.

A: The best source for this is the Salesforce Limits cheat sheet
From what I am aware there isn't a limit on the number of outbound messages sent.
Also note that despite being on "Unlimited Edition" you are limited in the number of API calls that you can make, this limit is 5,000 per user licence within any 24 hour period. (Unless you have had this amended by arrangment with Salesforce)


text:
Q: Mono For Android Hello World code throws AndroidManifest.xml error I recently downloaded the trial version of Mono For Android. I tried running the Hello World tutorial. I receive the following error:
Tried to launch activity 'HelloMonoDroid.HelloMonoDroid/hellomonodroid.Activity1', but the device could not find it.
A common cause of this is manually adding an  to your AndroidManifest.xml whose name does not match your Activity class.
Consider using the [Activity] attribute instead:
http://monodroid.net/Tutorials/Working_with_AndroidManifest.xml
I triple checked my code and didn't see any differences between it and the posted code in the tutorial. So I tried to create a new Mono For Android Project and ran it without modification. I named the Project Driver. Here is the error I received:
Tried to launch activity 'Driver.Driver/driver.Activity1', but the device could not find it.
A common cause of this is manually adding an  to your AndroidManifest.xml whose name does not match your Activity class.
Consider using the [Activity] attribute instead:
http://monodroid.net/Tutorials/Working_with_AndroidManifest.xml
Notice it is the same as the original error with only the activity name changed. This is a simple solution. I am not creating a AndroidManifest.xml file manually. Is this a bug with the Mono For Android product?

A: Go to Tools->Options->Mono for Android and turn on adb logging.
This should write a log to your desktop that might give more details.

A: Aha, thanks I've found the issue. There is a place in that dialog (Tools->Options->Mono For Android) that sets the Android SDK path. After doing this the solution deploys and works with no trouble. I thought I told the installer where the SDK was, but apparently not. Its possible I got myself confused as I'm evaluating the Eclipse/Android SDK development environment in parrallel.


text:
Q: How to iterate maps in insertion order? I have a navbar as a map:
var navbar = map[string]navbarTab{
}

Where navbarTab has various properties, child items and so on. When I try to render the navbar (with for tabKey := range navbar) it shows up in a random order. I'm aware range randomly sorts when it runs but there appears to be no way to get an ordered list of keys or iterate in the insertion order.
The playground link is here: http://play.golang.org/p/nSL1zhadg5 although it seems to not exhibit the same behavior.
How can I iterate over this map without breaking the insertion order?

A: The general concept of the map data structure is that it is a collection of key-value pairs. "Ordered" or "sorted" is nowhere mentioned.
Wikipedia definition:

In computer science, an associative array, map, symbol table, or dictionary is an abstract data type composed of a collection of (key, value) pairs, such that each possible key appears just once in the collection.

The map is one of the most useful data structures in computer science, so Go provides it as a built-in type. However, the language specification only specifies a general map (Map types):

A map is an unordered group of elements of one type, called the element type, indexed by a set of unique keys of another type, called the key type. The value of an uninitialized map is nil.

Note that the language specification not only leaves out the "ordered" or "sorted" words, it explicitly states the opposite: "unordered". But why? Because this gives greater freedom to the runtime to implement the map type. The language specification allows to use any map implementation like hash map, tree map etc. Note that the current (and previous) versions of Go use a hash map implementation, but you don't need to know that to use it.
The blog post Go maps in action is a must read regarding to this question.
Before Go 1, when a map was not changed, the runtime returned the keys in the same order when you iterated over its keys/entries multiple times. Note that this order could have changed if the map was modified as the implementation might needed to do a rehash to accommodate more entries. People started to rely on the same iteration order (when map was not changed), so starting with Go 1 the runtime randomizies map iteration order on purpose to get the attention of the developers that the order is not defined and can't be relied on.
What to do then?
If you need a sorted dataset (be it a collection of key-value pairs or anything else) either by insertion order or natural order defined by the key type or an arbitrary order, map is not the right choice. If you need a predefined order, slices (and arrays) are your friend. And if you need to be able to look up the elements by a predefined key, you may additionally build a map from the slice to allow fast look up of the elements by a key.
Either you build the map first and then a slice in proper order, or the slice first and then build a map from it is entirely up to you.
The aforementioned Go maps in action blog post has a section dedicated to Iteration order:

When iterating over a map with a range loop, the iteration order is not specified and is not guaranteed to be the same from one iteration to the next. Since Go 1 the runtime randomizes map iteration order, as programmers relied on the stable iteration order of the previous implementation. If you require a stable iteration order you must maintain a separate data structure that specifies that order. This example uses a separate sorted slice of keys to print a map[int]string in key order:

import "sort"

var m map[int]string
var keys []int
for k := range m {
    keys = append(keys, k)
}
sort.Ints(keys)
for _, k := range keys {
    fmt.Println("Key:", k, "Value:", m[k])
}

P.S.:

...although it seems to not exhibit the same behavior.

Seemingly you see the "same iteration order" on the Go Playground because the outputs of the applications/codes on the Go Playground are cached. Once a new, yet-unique code is executed, its output is saved as new. Once the same code is executed, the saved output is presented without running the code again. So basically it's not the same iteration order what you see, it's the exactly same output without executing any of the code again.
P.S. #2
Although using for range the iteration order is "random", there are notable exceptions in the standard lib that do process maps in sorted order, namely the encoding/json, text/template, html/template and fmt packages. For more details, see In Golang, why are iterations over maps random?

A: Go maps do not maintain the insertion order; you will have to implement this behavior yourself.
Example:
type NavigationMap struct {
    m map[string]navbarTab
    keys []string
}

func NewNavigationMap() *NavigationMap { ... }

func (n *NavigationMap) Set(k string, v navbarTab) {
    n.m[k] = v
    n.keys = append(n.keys, k)
}

This example is not complete and does not cover all use-cases (eg. updating insertion order on duplicate keys).
If your use-case includes re-inserting the same key multiple times (this will not update insertion order for key k if it was already in the map):
func (n *NavigationMap) Set(k string, v navbarTab) {
    _, present := n.m[k]
    n.m[k] = v
    if !present {
        n.keys = append(n.keys, k)
    }
}

Choose the simplest thing that satisfies your requirements.


text:
Q: "Fontconfig error: Cannot load default config file" on Ubuntu 16.04 I'm using python 2.7 on Anaconda, on Ubuntu 16.04, installed in a virtual machine with VMware Player on Windows 10.
When running the following code, I get the following error:
>>> import networkx as nx
>>> G = nx.complete_graph(4)
>>> pos = nx.nx_pydot.graphviz_layout(G)
Fontconfig error: Cannot load default config file

I have tried setting the path as suggested here, both in the root and on the conda environment, I have tried to reinstall fontconfig both in the root and on the conda environment, and I have also tried the answer suggested here, and I have exited the console, and restart the machine several times, and I still get the same error.
I will very much appreciate any help to solve this problem.

A: The following fixed it for me:
export FONTCONFIG_FILE=$CONDA_PREFIX/etc/fonts/fonts.conf
export FONTCONFIG_PATH=$CONDA_PREFIX/etc/fonts/

EDIT:
Can you try it again? There were two '\' too much.


text:
Q: Unresolved requirement: Import-Package: com.liferay.docs.guestbook.model; version="[1.0.0,1.1.0)"_ The version of this project is 7.2ga1 and I use Liferay Tomcat 7.3.5.
I've just tried use the target platform but with no results.
Here there are the logs of tomcat, when I deploy the project .
2020-11-23 11:03:21.019 ERROR [fileinstall-C:/java/bundles/liferay-ce-portal-tomcat-7.3.4-ga5-20200811154319029/liferay-ce-portal-7.3.4-ga5/osgi/modules][DirectoryWatcher:1112] Unable to start bundle: file:/C:/java/bundles/liferay-ce-portal-tomcat-7.3.4-ga5-20200811154319029/liferay-ce-portal-7.3.4-ga5/osgi/modules/com.liferay.docs.guestbook.service.jar
    org.osgi.framework.BundleException: **Could not resolve module: com.liferay.docs.guestbook.service [2425]_  Unresolved requirement: Import-Package: com.liferay.docs.guestbook.exception; version="[1.0.0,2.0.0)"_**    -> Export-Package: com.liferay.docs.guestbook.exception; bundle-symbolic-name="com.liferay.docs.guestbook.api"; bundle-version="1.0.0"; version="1.0.0"; uses:="com.liferay.portal.kernel.exception"_       com.liferay.docs.guestbook.api [2423]_         Unresolved requirement: Import-Package: com.liferay.portal.kernel.dao.orm; version="[9.6.0,10.0.0)"_  Unresolved requirement: Import-Package: com.liferay.docs.guestbook.model; version="[1.0.0,1.1.0)"_    -> Export-Package: com.liferay.docs.guestbook.model; bundle-symbolic-name="com.liferay.docs.guestbook.api"; bundle-version="1.0.0"; version="1.0.0"; uses:="com.liferay.exportimport.kernel.lar,com.liferay.portal.kernel.annotation,com.liferay.portal.kernel.bean,com.liferay.portal.kernel.model,com.liferay.portal.kernel.model.wrapper,com.liferay.portal.kernel.util"_ [Sanitized]
  at org.eclipse.osgi.container.Module.start(Module.java:444)
  at org.eclipse.osgi.internal.framework.EquinoxBundle.start(EquinoxBundle.java:428)
  at com.liferay.portal.file.install.internal.DirectoryWatcher._startBundle(DirectoryWatcher.java:1095)
  at com.liferay.portal.file.install.internal.DirectoryWatcher._startBundles(DirectoryWatcher.java:1128)
  at com.liferay.portal.file.install.internal.DirectoryWatcher._startAllBundles(DirectoryWatcher.java:1073)
  at com.liferay.portal.file.install.internal.DirectoryWatcher._process(DirectoryWatcher.java:985)

2020-11-23 11:03:21.022 ERROR [fileinstall-C:/java/bundles/liferay-ce-portal-tomcat-7.3.4-ga5-20200811154319029/liferay-ce-portal-7.3.4-ga5/osgi/modules][DirectoryWatcher:1112] Unable to start bundle: file:/C:/java/bundles/liferay-ce-portal-tomcat-7.3.4-ga5-20200811154319029/liferay-ce-portal-7.3.4-ga5/osgi/modules/com.liferay.docs.guestbook.api.jar
org.osgi.framework.BundleException: Could not resolve module: com.liferay.docs.guestbook.api [2423]_  Unresolved requirement: Import-Package: com.liferay.portal.kernel.dao.orm; version="[9.6.0,10.0.0)"_ [Sanitized]
  at org.eclipse.osgi.container.Module.start(Module.java:444)
  at org.eclipse.osgi.internal.framework.EquinoxBundle.start(EquinoxBundle.java:428)
  at com.liferay.portal.file.install.internal.DirectoryWatcher._startBundle(DirectoryWatcher.java:1095)
  at com.liferay.portal.file.install.internal.DirectoryWatcher._startBundles(DirectoryWatcher.java:1128)
  at com.liferay.portal.file.install.internal.DirectoryWatcher._startAllBundles(DirectoryWatcher.java:1073)
  at com.liferay.portal.file.install.internal.DirectoryWatcher._process(DirectoryWatcher.java:985)
  at com.liferay.portal.file.install.internal.DirectoryWatcher.run(DirectoryWatcher.java:302)
2020-11-23 11:03:21.025 ERROR [fileinstall-C:/java/bundles/liferay-ce-portal-tomcat-7.3.4-ga5-20200811154319029/liferay-ce-portal-7.3.4-ga5/osgi/modules][DirectoryWatcher:1112] Unable to start bundle: file:/C:/java/bundles/liferay-ce-portal-tomcat-7.3.4-ga5-20200811154319029/liferay-ce-portal-7.3.4-ga5/osgi/modules/com.liferay.docs.guestbook.api.jar
org.osgi.framework.BundleException: Could not resolve module: com.liferay.docs.guestbook.api [2423]_  Unresolved requirement: Import-Package: com.liferay.portal.kernel.dao.orm; version="[9.6.0,10.0.0)"_ [Sanitized]
  at org.eclipse.osgi.container.Module.start(Module.java:444)
  at org.eclipse.osgi.internal.framework.EquinoxBundle.start(EquinoxBundle.java:428)
  at com.liferay.portal.file.install.internal.DirectoryWatcher._startBundle(DirectoryWatcher.java:1095)
  at com.liferay.portal.file.install.internal.DirectoryWatcher._startBundles(DirectoryWatcher.java:1128)
  at com.liferay.portal.file.install.internal.DirectoryWatcher._process(DirectoryWatcher.java:990)
  at com.liferay.portal.file.install.internal.DirectoryWatcher.run(DirectoryWatcher.java:302)

This is the code autogenerated when I do the Gradle task buildService
CODE OF Service build.gradle
dependencies {
    compileOnly project(":modules:guestbook:guestbook-api")

    compileOnly group: "com.liferay", name: "com.liferay.petra.io"
    compileOnly group: "com.liferay", name: "com.liferay.petra.lang"
    compileOnly group: "com.liferay", name: "com.liferay.petra.string"
    compileOnly group: "com.liferay", name: "com.liferay.portal.aop.api"
    compileOnly group: "com.liferay.portal", name: "com.liferay.portal.kernel"
    compileOnly group: "org.osgi", name: "org.osgi.annotation.versioning"
    compileOnly group: "org.osgi", name: "org.osgi.core"
    compileOnly group: "org.osgi", name: "org.osgi.service.component.annotations"
    compileOnly group: "com.liferay", name: "com.liferay.petra.sql.dsl.api"
}

buildService {
    apiDir = "../guestbook-api/src/main/java"
}

group = "com.liferay.docs.guestbook"

tasks.withType(JavaCompile) {

    // Generated classes using Jodd library are unable to be read when compiled against JDK 11

    sourceCompatibility = JavaVersion.VERSION_1_8
    targetCompatibility = JavaVersion.VERSION_1_8
}

This is the code autogenerated when I do the Gradle task buildService
CODE OF api build.gradle
dependencies {
    compileOnly group: "com.liferay", name: "com.liferay.petra.lang"
    compileOnly group: "com.liferay", name: "com.liferay.petra.string"
    compileOnly group: "com.liferay.portal", name: "com.liferay.portal.kernel"
    compileOnly group: "org.osgi", name: "org.osgi.annotation.versioning"
    compileOnly group: "org.osgi", name: "org.osgi.core"
    compileOnly group: "org.osgi", name: "org.osgi.service.component.annotations"
    compileOnly group: "com.liferay", name: "com.liferay.petra.sql.dsl.api"

CODE OF Service bnd.bnd
Bundle-Name: guestbook-service
Bundle-SymbolicName: com.liferay.docs.guestbook.service
Bundle-Version: 1.0.0
Liferay-Require-SchemaVersion: 1.0.0
Liferay-Service: true
-dsannotations-options: inherit`

This is the code autogenerate when I do the Gradle task buildService
    **CODE OF Api bdn.bdn**

Bundle-Name: guestbook-api
Bundle-SymbolicName: com.liferay.docs.guestbook.api
Bundle-Version: 1.0.0
Export-Package:\
  com.liferay.docs.guestbook.exception,\
  com.liferay.docs.guestbook.model,\
  com.liferay.docs.guestbook.service,\
  com.liferay.docs.guestbook.service.persistence
-check: EXPORTS
-includeresource: META-INF/service.xml=../guestbook-service/service.xml

So I don t understand why Service can t import package of API.
However see the link below.
This is the project that Liferay makes you do if you are a principiant, and Im following this

A: You start with

The version of this project is 7.2ga1 and I use Liferay Tomcat 7.3.5

and you state that you've tried target platform. In fact, the build dependencies show that you are still using target platform, and most likely your target platform is set to a different version than the runtime you're using: Target Platform should at least match the major/minor part (e.g. 7.3.x), there are different opinions about the depth of it. Simplest: Make your target platform match the version you use at runtime.
Your service can't import the API bundle, because the API bundle doesn't deploy: It has a dependency on a Liferay kernel that is not there at runtime due to the version mismatch introduced at compile time (through the target platform).
Set the target platform to 7.3.5, do a clean rebuild and your dependencies should match your runtime version
Answering your comment: This way you'll have the correct dependency declared in your plugin, and it will be matched at runtime. Your build.gradle doesn't contain any version numbers, because those versions come from the target platform declaration. If you override any dependency's version in bnd.bnd (to 0), the version will be ignored, but there's no guarantee that you have compatible code that indeed can deal with what they find at runtime. Just switching off the correct dependency might work now, but can fail any time that the API you're dependent on is updated with a binary incompatible change.


text:
Q: Z-index on a absolute container in a fixed containter enter image description here
enter image description here
header{
        position:fixed;
        top:0;
        left:0;
        background-color: $color;
        width: $width;
        height: 56px;
    }

.utility{
        @include lockPosition(10px);
        right:10px;
        width:700px;
        height:20px;
        padding-top:10px;
        z-index:1000;
        position:absolute;
    }

I find that only absolute position fixes the z-index issue I am having but I want the header to be fixed so it does scroll. Is there a way to have a absolute position in a fixed element and not effect the z-index?

A: I think the easiest way is to push down the box with absolute position, i guess on .utility,
.utility{top: npx}

As for your question, the importances of the z-index is depending on how you lays the HTML DOM, so for example if your
Your fixed position

 Your absolute position

 with your fixed position z-index will be much more important than your
Hope that helps,


text:
Q: Whether to prove Plane, and Line are Perpendicular, or Parallel or Neither I have the equation a given plane in the format:
$$ax+by+cz+d=0$$
And I have a line in the following format:
$$<a,b,c>+t<d,e,f>$$
I have the normal vector that identifies the plane:
$$\vec{n}=<a,b,c>$$
I have the vector parallel to the line:
$$\vec{v}=<d,e,f>$$
I then take the dot product of the two vectors and get the a non-zero number:
$$\vec{n} \ \cdot \ \vec{v} \ne0$$
From here i can deduce that the plane, and the line are not parallel; however, how do I know if they are not perpendicular?
One observation I have the make is that:
$$\vec{n} = k\vec{v}$$
So since they are scalar multiples of each other are they perpendicular?


text:
Q: Do all symmetries of a Kähler quotient come from the original space? For a Kähler manifold $M$, let $\operatorname{Iso}_{\mathbb{C}}(M)$ denote the group of holomorphic isometries.
Suppose that $K$ is a compact subgroup of $\operatorname{Iso}_{\mathbb{C}}(M)$ and there is a moment map $\mu:M\to\mathfrak{k}^*$ for the $K$-action such that the Kähler quotient $M_0:=\mu^{-1}(0)/K$ is smooth. Then, if $N_{\operatorname{Iso}_{\mathbb{C}}(M)}(K)$ denotes the normalizer of $K$ in $\operatorname{Iso}_{\mathbb{C}}(M)$, there is a natural group homomorphism
$$N_{\operatorname{Iso}_{\mathbb{C}}(M)}(K)/K\to\operatorname{Iso}_{\mathbb{C}}(M_0).$$
Are there instances where this map is not surjective? I.e. $M_0$ posseses more symmetries than those comming from $M$?

A: Let $f : M \to E$ be a line bundle over an elliptic curve such that $\deg(M)<0$
 and let $G = \mathbf{C}^*$ act on $M$ (on the left) by scalar multiplications. The maximal compact subgroup $K$ of $G$ is  $U(1)$ and let $M$ be endowed with the $K$-invariant Kähler metric $h$ constructed as follows.
There exists a unitary representation of $\pi_1(E)$ of a hermitian vector space $L$ of dimension 1 such that $M = (L \times \tilde{E})/\pi_1(E)$ where $\tilde{E} = \mathbf{C}$ is the universal cover of $E$. This identification is compatible with the $G$-actions where on the right hand side, $G$ acts on $L$ on the left by scalar multiplications. Let $L \times \tilde{E}$ be endowed with the product metric $\tilde{h}= (h_L,h_{\mathrm{std}})$ where $h_L$ is the constant hermitian metric coming from the hermitian structure of $L$ and $h_{\mathrm{std}}$ the standard hermitian metric on $\mathbf{C}$. The metric $\tilde{h}$ is Kähler and is at the same time $K$-invariant and $\pi_1(E)$-invariant. So $\tilde{h}$ descends to a $K$-invariant Kähler metric $h$ on $M$.
The Kähler quotient $M_0 = M // G$ is isomorphic to the elliptic curve $E$ and the induced Kähler metric on $M_0$ is invariant under translations. So the group of translations of $E$ (still denoted by $E$) is contained in $\mathrm{Iso}_\mathbf{C}(M_0)$. We shall show that not every element of $E$ can be lifted to $N_{\operatorname{Iso}_{\mathbf{C}}(M)}$.
The $N_{\operatorname{Iso}_{\mathbf{C}}(M)}$-action on $M$ preserves fibers of $f$. As $H^0(E,M)= 0$, the action also preserves the $0$-section. Thus for each $g \in N_{\operatorname{Iso}_{\mathbf{C}}(M)}$, there exist a biholomorphic map $\phi : E \to E$ and an isomorphism  $i:\phi^*M \simeq M$ such that $g = i\circ \phi^*$, and the image of $g$ under the map $N_{\operatorname{Iso}_{\mathbf{C}}(M)} \to \operatorname{Iso}_{\mathbf{C}}(M_0)$ is $\phi$. Finally since $\deg(M) \ne 0$, the line bundle $M$ is not invariant under translations, which shows that $N_{\operatorname{Iso}_{\mathbf{C}}(M)} \to \operatorname{Iso}_{\mathbf{C}}(M_0)$ is not surjective.


text:
Q: How do I side-load a font in vscode? Without admin privileges to install a font, how do I use a non-installed font in vscode?  Visual Studio Code is built on Electron, so it should be able to load css, right?

A: Since Visual Studio Code is built on Electron, it is able to load css, yes.  Modifying vscode-internal files will cause your title bar to display [Unsupported], however.
The avenue for side-loading fonts through css is as follows:

*

*Download and extract a font.  For this example, I'm using Iosevka since it comes with a ready-to-use stylesheet already.

*Modify your install's workbench.js script found at resources/app/out/vs/code/electron-browser/workbench/ by appending the following snippet (the path separator used is unimportant; node.js will deal with / just fine on windows)

const el = document.createElement('style');
el.type = 'text/css';
const content = document.createTextNode(`
@import url('C:/path/to/iosevka.css');
`);
el.appendChild(content);
document.head.appendChild(el);

*

*Configure your settings.json to use the font
  "fontFamily": "'Iosevka Web', monospace",

*Reload your editor

If your font does not have a stylesheet for you to load, you can specify your own fontFamily in the above content variable:

@font-face {
    font-family: 'Iosevka Web';
    font-display: swap;
    font-weight: 100;
    font-stretch: normal;
    font-style: normal;
    src: url('woff2/iosevka-thin.woff2') format('woff2'),
        url('woff/iosevka-thin.woff') format('woff'),
        url('ttf/iosevka-thin.ttf') format('truetype');
}

One last note, it is possible to load a stylesheet from the Internet, but I kept this answer to local files for simplicity.  It is also possible to run the snippet per-session to avoid persistence, but I didn't see the purpose of doing so and leave it as an exercise to the reader.


text:
Q: How to convert time string field into "hh:mm" format? I have pandas DataFrame like this:
import pandas as pd
d = {
         'time': [0, 100, 200, 1400, 1500],
         'value': [9, 8, 7, 6, 5],
         'three': ['a', 'b', 'a', 'a', 'b']
    }
df = pd.DataFrame(d)

How want to convert time into hh:mm format to get: 00:00, 01:00, 02:00, etc.
How can I do it without  if-then?

A: You need to convert it to string and perform a zfill() and concatenate using':'
d['time'] = [str(a).zfill(4)[:2]+':'+str(a).zfill(4)[2:4] for a in d['time']]


text:
Q: Is it possible for the user to change a model instance through the ajax request in Livewire? For security reasons, is it possible for the enduser to change the model in the livewire request?
For example, if I mount my component like this:
public $order;

public function mount(Order $order){
    $this->order = $order;
}

Can I be sure that this order instance won't be changed if the user tries to manipulate the request?


text:
Q: jQuery slice random amount of divs I'm a beginner at best with scripting so I'm hoping someone can help me if this is possible.
I'm using this script pieced together from research to randomize the divs displayed on a page, but I would like to make it display a random amount of them as well, instead of set slice amounts (0,6).
$(document).ready(function(){
    var divs = $("div.picture").get().sort(function(){
        return Math.round(Math.random())-0.5;
    })

   $(divs).appendTo(divs[0].parentNode).show();
   $('.gallery').find('.picture').slice(0,6).remove();
});

Thanks!

A: Use parseInt(Math.random() * (max - min) + min, 10) to get the random number. It will give you and interval of [min, max] slices.


text:
Q: How does lazy initialization happen in Singleton? Can anyone explain how does lazy initialization happen in the following singleton pattern code?
public class Singleton
{
  private static Singleton INSTANCE = null;
  private Singleton() {}
  public static Singleton getInstance()
  {
    if (INSTANCE == null)
       INSTANCE = new Singleton();
    return INSTANCE;
  }
}

A: The first time getInstance() is called, INSTANCE is null, and it is initialized with INSTANCE = new Singleton();.  This has the advantage of not initializing the instance if it is never used.
This code should be improved to be thread safe if it can be accessed by multiple threads.

A: Lazy means the instance is initialized when is used for the first time.
Here is an example of eager, its initialized before its used.
public class Singleton
{
  private static Singleton INSTANCE = new Singleton();
  private Singleton() {}
  public static Singleton getInstance()
  {
    return INSTANCE;
  }
}

A: The instance is created only when the class is initialized, and the class is initialized only when you call getInstance.
You might want to visit the JLS - 12.4.1. When Initialization Occurs:

A class or interface type T will be initialized immediately before the
  first occurrence of any one of the following:

T is a class and an instance of T is created.
T is a class and a static method declared by T is invoked.
A static field declared by T is assigned.
A static field declared by T is used and the field is not a constant
    variable (§4.12.4).
T is a top level class (§7.6), and an assert statement (§14.10)
    lexically nested within T (§8.1.3) is executed.


text:
Q: Using my computer as MySQL database and access with Xamarin.forms app I have developed an app from Xamarin. forms (C#) and I want to use my own computer to host a MySQL database. I have forwarded my port on my router as well but the database can only be accessed when my phone(Xamarin. forms app) and my computer (MySQL database and server) are connected on the same WIFI.
So far I have;

*

*create a user in the MySQL database and have given to connect with any address(%) privilege

*Forwarded port 3306 from my router

*Check port 3306 on my windows firewall(it is there). The database can be accessed with the local network.

*Add bind-address = 0.0.0.0 under [mysqlId] in my.ini file.The my.ini file

*Bang my head on the wall after trying everything above several times.
Router Menu
Connection string


text:
Q: Timestamps on deleted and then undeleted answers When an answer is deleted, then totally re-edited before being undeleted, please change the timestamp to reflect the time of the undeletion rather than the time of the original answer.
This sequence of events made one of my Meta answers look incorrect even though it was correct at the moment I posted it.
This is the edit sequence in question. Don't get me wrong - juergen did a good job by creating the tag, but by changing and undeleting his answer it makes mine (10K+ only) look incorrect - which it wasn't at the time I posted it. Note that I'm not concerned about down votes, I'm concerned about context and accuracy.

A: I feel that the "edited X hours" ago is enough. What you say applies equally well to a post which was just edited substantially, with no deletion magic. If he had just edited and created the tag, your answer would still look wrong. The second timestamp takes care of this. The "answered X hours ago" timestamp would be downright confusing if it was reset on deletion.
Stuff changes. The Internet doesn't (or shouldn't) expect you to be up-to-date, no more than you can expect a reporter to fix their published material after getting more information.


text:
Q: unable to check out source code from gerrit.hyperledger.org https://hyperledger-fabric.readthedocs.io/en/latest/Gerrit/lf-account/
I've been using this for my setup and finished Configuring Gerrit to Use SSH. When I try to clone/check out the Source Code i get this error:
Permission denied (publickey).
fatal: The remote end hung up unexpectedly
I'm not able to clone it, any fixes or ideas on what's going wrong?

A: There's something wrong with your SSH key. Check the id_rsa and id_rsa.pub in your $HOME/.ssh directory and the id_rsa.pub configured in the Gerrit server. Execute the following command to help to find out what's going on:
ssh -vvv -p 29418 <user>@<gerrit-server>


text:
Q: Drupal theme() problem I am trying to display a custom page the same as my search results page by re-using the theme functions and pre-processors built into the search module.
With an empty Drupal cache this works beautifully. I simple call
theme('search_results', $results, 'node' );

with a correctly popuated results array, and I get back formatted markup.
Great.
However, when the cache is not clear, the search module is not available and so the theme() call goes nowhere and returns an empty string.
I've tried drupal_load('module','search') which makes the module file available, but does not intialize its hook_theme.

A: Fixed it with the following:
function_exists('search_theme') or drupal_load('module','search');
function_exists('template_preprocess_search_results') or module_load_include('inc','search','search.pages');

I don't like it though.

A: For theming standard search results use these:

*

*http://api.drupal.org/api/drupal/modules--search--search-result.tpl.php/6

*http://api.drupal.org/api/drupal/modules--search--search-results.tpl.php/6


text:
Q: Prevent CompletionItem list from inserting first value I have a snippet:
'color: ${1|initial,inherit|};'

Which is registered like so (minus unnecessery code):
const cssPropertyProvider = languages.registerCompletionItemProvider('mjml', {
  provideCompletionItems(document, position) {
    const snippetCompletion = new CompletionItem(attr.prefix)

    snippetCompletion.documentation = new MarkdownString(attr.description)
    snippetCompletion.insertText = new SnippetString(attr.body)

    return snippetCompletion
  }
})

subscriptions.push(cssPropertyProvider)

This automatically inserts the first list item (initial) when selecting the CompletionItem:

Is there a way to prevent this?

Essentially, I want the same functionality as a placeholder, but with a list:
'color: ${1:initial};'

VSCode docs on lists and placeholders
VSCode docs on registerCompletionItemProvider

A: I had to abandon the list/placeholder way and store the suggestions separately:
body: 'color: $1;',
values: ['initial', 'inherit'],

Then, assign this command to the original suggestion (cssPropertyProvider):
snippetCompletion.command = {
    command: 'editor.action.triggerSuggest',
    title: '',
}

And add a separate completion provider to cover this:
const cssValueProvider = languages.registerCompletionItemProvider('mjml', {
    provideCompletionItems(document, position) {
        const snippetCompletions: ProviderResult<CompletionItem[] | CompletionList> = []

        cssProperties.forEach((prop) => {
            const formattedBody = prop.body.split('$1').join('')

            // Ensure the line includes the relevant CSS property
            if (!document.lineAt(position).text.includes(formattedBody)) return

            prop.values.forEach((val) => {
                const snippetCompletion = new CompletionItem(val)

                // Sets the suggestion icon to the little orange thing
                snippetCompletion.kind = 11 // 11 = Value
                // Ensure tab-stops ($1) are handled
                snippetCompletion.insertText = new SnippetString(val)

                snippetCompletions.push(snippetCompletion)
            })
        })

        return snippetCompletions
    },
})

Also, just for my specific use case, I had to add a check in cssPropertyProvider that prevents the property suggestions displaying above the value suggestions:
const cssPropertyProvider = languages.registerCompletionItemProvider('mjml', {
    provideCompletionItems(document, position) {
        const { text: lineText } = document.lineAt(position)
        const lastLineChar = lineText[position.character]

        if (lastLineChar === ';') return
...

Result:


text:
Q: Unnest json file with coordinates into dataframe in R I'm having trouble parsing a json file into a dataframe in R. I've been able to turn the json file into a data frame, but I can't seem to unnest the "geometry" column. Below is a sample of the json file
[
{
    "point_id": 4,
    "geometry": {
        "type": "Point",
        "coordinates": [
            -101.5961904,
            31.7070736
        ]
    },
    "NumericID": "4543842",
}
]

When I try to unnest using the code below, I get an error.
ex_data<-lapply(ex_data, function(x) ifelse (x == "NULL", NA, x))
ex_data<-as.data.frame(do.call(rbind, ex_data))
ex_data<-ex_data%>% bind_rows(ex_data) %>%    # make larger sample data
mutate_if(is.list, simplify_all)   # flatten each list element internally
ex_data%>%unnest(geometry)->ex_data_unnest
Error: Each column must either be a list of vectors or a list of data frames
[geometry]

Thanks

A: Use jsonlite::stream_in() to read the JSON-file (I copied your example in a JSON-file several times):
df <- stream_in(file("test.json"))

Edit:
Unnesting the geometry columns:
df <- as.data.frame(cbind(df[,-2],
    do.call(rbind,df$geometry$coordinates),
    df$geometry$type),
    stringsAsFactors = F)
names(df)[3:5] <- c("geometry.coordinates1","geometry.coordinates2","geometry.type")

df
   point_id NumericID geometry.coordinates1 geometry.coordinates2 geometry.type
1         4   4543842             -101.5962              31.70707         Point
2         4   4543842             -101.5962              31.70707         Point

Now you can access the values from the data.frame


text:
Q: Conditionally Switching a UIViewController For my app I need the user to input a number, so in order to prevent them from not entering a number I've created an if/else statement that presents the user with an error message if they don't fill out the field, and moves onto the main view of the app if they fill in a number. The only issue is that I'm getting a crash whenever it tries to run the code to bring up the next screen.
- (IBAction)budgetButton:(id)sender
{
    myBudget = [self.budgetTextField.text floatValue];
    NSLog(@"myBudget = %.2f", myBudget);
    if (myBudget == 0)
    {
        self.whatsYourBudgetLabel.text = [NSString stringWithFormat:(@"You must enter a budget!")];
    }
    else
    {
        ViewController * nextView = [self.storyboard instantiateViewControllerWithIdentifier:@"ViewController"];
        self.view.window.rootViewController = nextView;
    }
}

A: Your code to move to the next view is messed up.
Have a look at the performSegueWithIdentifier:sender: method.
You should not change the root of your window. Place a UINavigationController into you window, place your entire view hierarchy in there, and use the default segue mechanisms to navigate.


text:
Q: Filling missing levels I have the following type of dataframe:
Country <- rep(c("USA", "AUS", "GRC"),2)
Year    <- 2001:2006
Level   <- c("rich","middle","poor",rep(NA,3))
df <- data.frame(Country, Year,Level)

df
Country Year  Level
1     USA 2001   rich
2     AUS 2002 middle
3     GRC 2003   poor
4     USA 2004   <NA>
5     AUS 2005   <NA>
6     GRC 2006   <NA>

I want to fill the missing values with the correct level label in the last from the right column.
So the expected outcome should be like this:
Country Year  Level
1     USA 2001   rich
2     AUS 2002 middle
3     GRC 2003   poor
4     USA 2004   rich
5     AUS 2005 middle
6     GRC 2006   poor

A: We can group by 'Country' and get the non-NA unique value
library(dplyr)
df %>%
    group_by(Country) %>%
    dplyr::mutate(Level = Level[!is.na(Level)][1])
# A tibble: 6 x 3
# Groups:   Country [3]
#  Country  Year  Level
#   <fctr> <int> <fctr>
#1     USA  2001   rich
#2     AUS  2002 middle
#3     GRC  2003   poor
#4     USA  2004   rich
#5     AUS  2005 middle
#6     GRC  2006   poor

If we have loaded dplyr along with plyr, it is better to specify explicitly dplyr::mutate or dplyr::summarise so that it uses the function from dplyr.  There are same functions in plyr and it could potentially mask the functions from dplyr when both are loaded creating different behavior.

A: You can do it using data.table and zoo:-
library(data.table)
library(zoo)
setDT(df)
df[, Level := na.locf(Level), by = Country]

This will give you:-
   Country Year  Level
1:     USA 2001   rich
2:     AUS 2002 middle
3:     GRC 2003   poor
4:     USA 2004   rich
5:     AUS 2005 middle
6:     GRC 2006   poor

A: library(dplyr)

df %>%
  group_by(Country) %>%
  mutate(Level = replace(Level, is.na(Level), unique(na.omit(Level))))

  Country  Year  Level
   <fctr> <int> <fctr>
1     USA  2001   rich
2     AUS  2002 middle
3     GRC  2003   poor
4     USA  2004   rich
5     AUS  2005 middle
6     GRC  2006   poor

Or, more succinctly, applying @suchait's idea to use na.locf:
df %>%
  group_by(Country) %>%
  mutate(Level = zoo::na.locf(Level))

A: In base R, you could use ave():
transform(df, Level = ave(Level, Country, FUN = na.omit))

#   Country Year  Level
# 1     USA 2001   rich
# 2     AUS 2002 middle
# 3     GRC 2003   poor
# 4     USA 2004   rich
# 5     AUS 2005 middle
# 6     GRC 2006   poor

Another, more accurate possibility is to use a join.  Here we merge the Country column with the NA-omitted data.  The outcome is the same, just in a different row order.
merge(df["Country"], na.omit(df))

#   Country Year  Level
# 1     AUS 2002 middle
# 2     AUS 2002 middle
# 3     GRC 2003   poor
# 4     GRC 2003   poor
# 5     USA 2001   rich
# 6     USA 2001   rich

A: A solution using dplyr and tidyr.
library(dplyr)
library(tidyr)

df %>%
  arrange(Country) %>%
  fill(Level) %>%
  arrange(Year)
#   Country Year  Level
# 1     USA 2001   rich
# 2     AUS 2002 middle
# 3     GRC 2003   poor
# 4     USA 2004   rich
# 5     AUS 2005 middle
# 6     GRC 2006   poor

A: Here is another data.table solution which updates on join using a lookup table which is created from the given dataset itself:
library(data.table)
setDT(df)[df[!is.na(Level)], on = .(Country), Level := Level][]

   Country Year  Level
1:     USA 2001   rich
2:     AUS 2002 middle
3:     GRC 2003   poor
4:     USA 2004   rich
5:     AUS 2005 middle
6:     GRC 2006   poor


text:
Q: How come I can define generic exception types in Scala? In Java, it's illegal to define a generic exception class. The compiler will refuse to compile the following:
public class Foo<T> extends Throwable {
    // whatever...
}

However, this Scala code compiles just fine:
class Foo[T](val foo: T) extends Throwable

Even weirder, I can use this Scala class in Java code as long as I catch the raw Foo type:
public class Main {
    public static void main(String[] args) {
        try {
            throw new Foo<String>("test");
        }
        catch(Foo e) {
            System.out.println(e.foo());
        }
    }
}

This compiles, runs, and prints "test".
Is this well defined according to the JLS and JVM spec or does it just happen to work accidentally?
Is the Java restriction on generic exceptions purely a language restriction or does it also apply to the bytecode (in which case the bytecode generated by the Scala compiler would be invalid)?
Edit: This is what the Scala class looks after decompilation:
public class Foo<T> extends java.lang.Throwable {
  public T value();
    Code:
       0: aload_0
       1: getfield      #15                 // Field value:Ljava/lang/Object;
       4: areturn

  public Foo(T);
    Code:
       0: aload_0
       1: aload_1
       2: putfield      #15                 // Field value:Ljava/lang/Object;
       5: aload_0
       6: invokespecial #22                 // Method java/lang/Throwable."<init>":()V
       9: return
}

A: Short answer:

*

*the JVM spec forbids throwing and catching parametrized exceptions, but does not care about declaration. It does not even forbid that, there just is no way to represent the type parameter in bytecode, so the question is moot.

*the JLS forbids declaring them because there is no way you could use them anyway.

Long answer:
The Java Language Specification says (§8.1.2) about declaring such a class:

It is a compile-time error if a generic class is a direct or indirect subclass of Throwable (§11.1.1).
This restriction is needed since the catch mechanism of the Java Virtual Machine works only with non-generic classes.

And it says about throwing an exception (§14.18):

The Expression in a throw statement must denote either
1) a variable or value of a reference type which is assignable (§5.2) to the type Throwable, or
2) the null reference, or a compile-time error occurs.
The reference type of the Expression will always be a class type (since no interface types are assignable to Throwable) which is not parameterized (since a subclass of Throwable cannot be generic (§8.1.2)).

This restriction was added when generics were added to the Java language because they were not added to the JVM itself: only raw types exist on the JVM.
There is still information about that type parameter where the class is defined, but not where is is used! Independently of the declaration of a parametrized exception, this is impossible on the JVM level:
try {
    throw new Foo<String>("test");
} catch(Foo<Int> e) {
  // int
} catch(Foo<String> e) {
  // string
}

The way exception catching is implemented is that there is an exception table that specify ranges of bytecode to watch and an associated class to catch. That class cannot have a type parameter since there is no way to describe them in bytecode (JVM specification, §2.10 and §3.12).
Because of type erasure, the throw clause only refers to Foo, and those two catch methods would become two entries in the exception table that both refer to the class Foo, which is both useless and impossible anyway. As a consequence that syntax is not possible in the Java language and one can only catch Foo.
And as a consequence to that, it becomes pretty useless and potentially dangerous to be able to declare parametrized exceptions. So they were forbidden altogether in the language, even though the JVM itself does not care.

A: Here is the answer we carved out so far in the discussion.

Is this well defined according to the JLS and JVM spec or does it just
  happen to work accidentally?

It does not have to be well defined according to the Java Language Specification, as it is a different Language.
The JVM, OTOH, has no problems throwing and catching such exceptions, because due to type erasure, it makes no difference in the bytecode.
Nevertheless, the interesting question remains, why Java forbids extension of Throwable with generic classes in the first place.


text:
Q: Is this function decreased with $x$? Given three positive integers $a,b,c\ge 1$, I am wondering if the following $f(x)$ is decreased with $x$ ?
$$f(x)=\frac{c+2x}{(a+x)(b+x)}, \quad x \in Z^+ \cup \{0\}$$
where $1\le c \le ab$.

A: Let $a=b=2$ and $c=1$.  Then $f(0)=1/4$ but $f(1)=1/3$.

A: Let
$$c=t+(1-t)ab,\text{  } 0\le t\le 1,\text{   } \tag{A}$$,
then
$$f(x,a,b,t)=\frac{t+(1-t)ab+2x}{(a+x)(b+x)}$$
Now consider $g(x)=f(x,a,a,t)$.
$$g'(x)=\frac{dg}{dx}=\frac{2(a + a^2(-1 + t) - t - x)}{(a + x)^3}$$
Thus $g'(x)$ has a zero at $x_0=(a-1)(a(1-t)-t)$.
(1) If $a>t=1$, then this zero is positive. In this case g(x) increase when $x$ varies from 0 to $x_0>0$ and decreases afterwards.
(2) If $t=0$, then $x_0<0$. So $g(x)$ is a decreasing function.
(3) If $a\gt=\frac{t}{1-t}$ and $0<t<1$, then $x_0>0$. So this case is similar to (1).
We have not considered that the restriction on $t$ because $c$ in (A) is a positive integer.

A: since my calculations are error-prone, i will merely show some working which someone might check. if this result is correct then at present i cannot see see how it can be non-trivially related to the given condition $1 \le c \le ab$. might one expect a condition involving $c^2$ rather than $c$? apologies in advance
$$
\frac{df}{dx} = \frac{2(a+x)(b+x) - (c+2x)(a+b+2x)}{(a+x)^2(b+x)^2}
$$
the numerator is
$$
2(ab+(a+b)x+x^2) - c(a+b) - 2cx -2x(a+b)-4x^2 \\
= 2ab - 2x^2 -2cx - c(a+b)\\
= - ( 2x^2+2cx + [c(a+b)-2ab])
$$
the critical values of $x$ are thus the solutions, if any, of:
$$
x = \frac{-2c \pm \sqrt{(4c^2-8c(a+b)+16ab)}}{4}\\
= -\frac12 \left(c \pm \sqrt{(c-2a)(c-2b)} \right)
$$

A: Check $\frac{1}{f}$ !
$$\frac{1}{f(x)}=(c+2x)q(x)+r$$
$r$ is a constant and does not contribute to the growth of the function.
$(c+2x)$ is increasing and positive. So analyze the linear function $q(x)$.
Some Maxima output:

(%i2) f(x):=(c+2*x)/((x+a)*(x+b));
(%o2) f(x):=(c+2*x)/((x+a)*(x+b))
(%i3) makelist(f(i),i,[1,2,3]),a=10,b=10,c=100,numer;
(%o3) [0.84297520661157,0.72222222222222,0.62721893491124]
(%i4) makelist(f(i),i,[1,2,3]),a=10,b=10,c=1,numer;
(%o4) [0.024793388429752,0.034722222222222,0.041420118343195]


text:
Q: How to remove index.php in url ? (laravel 5.3, php 7) My url is like this : http://31.220.56.75/mysystem/public/index.php/login
I want remove index.php, to be like this : http://31.220.56.75/mysystem/public/login
My .htaccess :
<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews
    </IfModule>

    RewriteEngine On

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)/$ /$1 [L,R=301]

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
</IfModule>

I try some tutorial di google. but I don't find the solution
Update :
I try update .htaccess like this :
<IfModule mod_rewrite.c>
   RewriteEngine On
   RewriteRule ^(.*)$ public/$1 [L]
</IfModule>

It's not working

A: Try this
<IfModule mod_rewrite.c>
 RewriteEngine On
  RewriteRule ^(.*)$ public/$1 [L]
</IfModule>

A: default .htaccess in public folder should be working very fine. check: original .htaccess

A: Follow the below .htaccess file, hopefully this will work.
If your are facing the issue of $_GET variable also i.e If your both URL index.php and without index.php is working but $_GET variables found not working, then the below of .htaccess code will work for you.
DirectoryIndex index.php
<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews
    </IfModule>

    RewriteEngine On
    RewriteCond %{REQUEST_URI}::$1 ^(/.+)/(.*)::\2$
    RewriteRule ^(.*) - [E=BASE:%1]
    RewriteCond %{ENV:REDIRECT_STATUS} ^$
    RewriteRule ^index\.php(/(.*)|$) %{ENV:BASE}/$2 [R=301,L]
    RewriteCond %{REQUEST_FILENAME} -f
    RewriteRule .? - [L]
    RewriteRule .? %{ENV:BASE}/index.php [L]

</IfModule>


text:
Q: auto select the parent after deleting a selected node I would like to auto select the parent after deleting a selected node.
The following is code that I use to delete a node and any children if there is any
           var selectedNode = treeview.select();
            $(selectedNode).children('.k-group').remove();
            treeview.remove(selectedNode);

How would I auto select the parent node after the delete?

A: Try the folllowing:
var selectedNode = treeview.select();
var parentNode = treeview.parent(selectedNode);
$(selectedNode).children('.k-group').remove(); // you don't actually need this line of code
treeview.remove(selectedNode);
treeview.select(parentNode);

Take a look through the documentation too:

*

*http://docs.telerik.com/kendo-ui/api/web/treeview#methods-parent

*http://docs.telerik.com/kendo-ui/api/web/treeview#methods-select


text:
Q: Grabbing param value from #id=3333 I have this,
var stateObj = { foo: "foo" };
function change_my_url()
{
    if (window.history && window.history.pushState){
        history.pushState(stateObj, "page 2", "foo.html?id=3333");
    }else{
        location.hash = '#id=3333'
    }
}

In case window.history isnt supported, it will be #id=3333. Now if you load the page and it has a location.hash, it $.post request to file.php with it:
$.post('do_something.php', { hash: hash }, function(result) { $('#photos').html(result); });

in do_something im grabbing it with $_POST['hash'];. Now $_POST['hash'] will contain #id=3333. How can i divide in params and grab the value, '3333' ?

A: There are many ways to turn the string #id=3333 into the string 3333.
Split on '=':
$parts = explode('#', $inputString);
$value = $parts[1];

Remove the first four chars:
$value = substr($inputString, 3);


text:
Q: Lua - I have created a frame in Lua but am stumped on how to insert text into it? local MyAddon = CreateFrame("frame","MyAddonFrame")
MyAddon:SetBackdrop({
      bgFile="Interface\\DialogFrame\\UI-DialogBox-Background",
      edgeFile="Interface\\DialogFrame\\UI-DialogBox-Border",
      tile=1, tileSize=32, edgeSize=32,
      insets={left=11, right=12, top=12, bottom=11}
})
MyAddon:SetWidth(220)
MyAddon:SetHeight(400)
MyAddon:SetPoint("CENTER",UIParent)
MyAddon:EnableMouse(true)
MyAddon:SetMovable(true)
MyAddon:RegisterForDrag("LeftButton")
MyAddon:SetScript("OnDragStart", function(self) self:StartMoving() end)
MyAddon:SetScript("OnDragStart", function(self) self:StartMoving() end)
MyAddon:SetScript("OnDragStop", function(self) self:StopMovingOrSizing() end)
MyAddon:SetFrameStrata("FULLSCREEN_DIALOG")

MyAddon:RegisterEvent("PLAYER_ENTERING_WORLD");
local function eventHandler(self, event, ...)
 print("Hello World! Hello " .. event);
end
MyAddon:SetScript("OnEvent", eventHandler);

I have coded a frame to be created in Lua, and just want to simply put in "Hello World" so that the text is a part of the frame.
Any advice?

A: I believe you want the CreateFontString function:
local helloFS = MyAddon:CreateFontString(nil, "OVERLAY", "GameFontNormal")
helloFS:SetPoint("CENTER")
helloFS:SetText("Hello World!")