text:
Q: calling Restful Service from Java Here I am not creating a RESTful service indeed I have to call an external Restful service from my java code. Currently I am implementing this using Apache HttpClient.
The response that I get from the web service is in XML format.
I need to extract the data from XML and put them on Java objects.
Rather than using SAX parser, I heard that we can use JAX-RS and JERSEY which automatically maps the xml tags to corresponding java objects.
I have being looking through but unable to find a source to get started.
I did look at existing links
Consuming RESTful APIs using Java
RESTful call in Java
Any help is appreciated in moving forward.
Thanks!!

A: JAX-RS is the Java api for restful webservice. Jersey is an implementation from sun/oracle.
You need jaxb to convert your xml to a POJO. But it is not the always case that, converted object can be used without any transformation. If this is the scenario SAXParser is a nice solution.
Here is a nice tutorial on JAXB.

A: You could consider using jaxb to bind your java objects to an xml document (marshalling).
http://www.oracle.com/technetwork/articles/javase/index-140168.html#xmp1

A: I use Apache CXF to build my RESTful services, which is another JAX-RS implementation (it also provides a JAX-WS implementation).  I also use its "org.apache.cxf.jaxrs.client.WebClient" class in unit tests, which will completely manage all the marshalling and unmarshalling under the covers.  You give it a URL and ask for an object of a particular type, and it does all the work.  I don't know if Jersey has similar facilities.

A: UPDATE

as follow up with this: Can I do this way?? if the xml being returned
  as  4
     .....
  If I am constructing a Person object, I believe this will choke up.
  Can I just bind only the xml elements that I want? if Yes how can I do
  that.

You could map this XML as follows:
input.xml
<?xml version="1.0" encoding="UTF-8"?>
<Persons>
    <NumberOfPersons>2</NumberOfPersons>
        <Person>
            <Name>Jane</Name>
            <Age>40</Age>
        </Person>
        <Person>
            <Name>John</Name>
            <Age>50</Age>
        </Person>
</Persons>

Persons
package forum7177628;

import java.util.List;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name="Persons")
@XmlAccessorType(XmlAccessType.FIELD)
public class Persons {

    @XmlElement(name="Person")
    private List<Person> people;

}

Person
package forum7177628;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;

@XmlAccessorType(XmlAccessType.FIELD)
public class Person {

    @XmlElement(name="Name")
    private String name;

    @XmlElement(name="Age")
    private int age;

}

Demo
package forum7177628;

import java.io.File;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(Persons.class);

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        Persons persons = (Persons) unmarshaller.unmarshal(new File("src/forum7177628/input.xml"));

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(persons, System.out);
    }

}

Output
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Persons>
    <Person>
        <Name>Jane</Name>
        <Age>40</Age>
    </Person>
    <Person>
        <Name>John</Name>
        <Age>50</Age>
    </Person>
</Persons>

ORIGINAL ANSWER
Below is an example of calling a RESTful service using the Java SE APIs including JAXB:
String uri =
    "http://localhost:8080/CustomerService/rest/customers/1";
URL url = new URL(uri);
HttpURLConnection connection =
    (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept", "application/xml");

JAXBContext jc = JAXBContext.newInstance(Customer.class);
InputStream xml = connection.getInputStream();
Customer customer =
    (Customer) jc.createUnmarshaller().unmarshal(xml);

connection.disconnect();

For More Information:

*

*http://blog.bdoughan.com/2010/08/creating-restful-web-service-part-55.html

A: If you also need to convert that xml string that comes as a response to the service call, an x object you need can do it as follows:
 import java.io.BufferedReader;
 import java.io.IOException;
 import java.io.InputStreamReader;
 import java.io.StringReader;
 import java.net.HttpURLConnection;
 import java.net.MalformedURLException;
 import java.net.URL;
 import java.util.ArrayList;
 import java.util.List;

 import javax.xml.bind.JAXB;
 import javax.xml.bind.JAXBException;
 import javax.xml.parsers.DocumentBuilder;
 import javax.xml.parsers.DocumentBuilderFactory;
 import javax.xml.parsers.ParserConfigurationException;

 import org.w3c.dom.CharacterData;
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 import org.w3c.dom.Node;
 import org.w3c.dom.NodeList;
 import org.xml.sax.InputSource;
 import org.xml.sax.SAXException;

 public class RestServiceClient {

// http://localhost:8080/RESTfulExample/json/product/get
public static void main(String[] args) throws ParserConfigurationException,
    SAXException {

try {

    URL url = new URL(
        "http://localhost:8080/CustomerDB/webresources/co.com.mazf.ciudad");
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("GET");
    conn.setRequestProperty("Accept", "application/xml");

    if (conn.getResponseCode() != 200) {
    throw new RuntimeException("Failed : HTTP error code : "
        + conn.getResponseCode());
    }

    BufferedReader br = new BufferedReader(new InputStreamReader(
        (conn.getInputStream())));

    String output;

    Ciudades ciudades = new Ciudades();
    System.out.println("Output from Server .... \n");
    while ((output = br.readLine()) != null) {
    System.out.println("12132312");
    System.err.println(output);

    DocumentBuilder db = DocumentBuilderFactory.newInstance()
        .newDocumentBuilder();
    InputSource is = new InputSource();
    is.setCharacterStream(new StringReader(output));

    Document doc = db.parse(is);
    NodeList nodes = ((org.w3c.dom.Document) doc)
        .getElementsByTagName("ciudad");

    for (int i = 0; i < nodes.getLength(); i++) {
        Ciudad ciudad = new Ciudad();
        Element element = (Element) nodes.item(i);

        NodeList name = element.getElementsByTagName("idCiudad");
        Element element2 = (Element) name.item(0);

        ciudad.setIdCiudad(Integer
            .valueOf(getCharacterDataFromElement(element2)));

        NodeList title = element.getElementsByTagName("nomCiudad");
        element2 = (Element) title.item(0);

        ciudad.setNombre(getCharacterDataFromElement(element2));

        ciudades.getPartnerAccount().add(ciudad);
    }
    }

    for (Ciudad ciudad1 : ciudades.getPartnerAccount()) {
    System.out.println(ciudad1.getIdCiudad());
    System.out.println(ciudad1.getNombre());
    }

    conn.disconnect();

} catch (MalformedURLException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}
}

public static String getCharacterDataFromElement(Element e) {
Node child = e.getFirstChild();
if (child instanceof CharacterData) {
    CharacterData cd = (CharacterData) child;
    return cd.getData();
}
return "";
}

}
Note that the xml structure that I expected in the example was as follows:
 <ciudad><idCiudad>1</idCiudad><nomCiudad>BOGOTA</nomCiudad></ciudad>


text:
Q: How...if any number x which ends in three is coprime to 10, then is 9x is also coprime to 10? why 9x? where did 9x come from?
It is probably some modulus arithmetic or Fermat-Euler theorem .... I just can't grasp it!!! Shame

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why timeit.timeit is giving error when using with variable? I have been trying to execute one code snippet to get to know how much time it takes to execute.
I had tried two alternatives to do that. One is using variable inside timeit.timeit function and check. And the other one is directly using the value and check.
The second approach is working fine but I am facing some scoping issue while using first one. Attached are the images for both scenarios.

Can anyone help me in this regard? Any suggestions to the questions are highly appreciated.

A: Others already addressed the main issue (the code you pass to timeit() is invalid), I just wanted to mention that with the commonly posted solution (adding a semi-colon between the two statements) you will end up benchmarking the total cost of both statements combined (creating the literal string "Hello world", assigning it to a variable and calling endswith('d') on this variable). Assuming what you're actually interested in is the cost of the second statement only, you may want to use timeit() second's (optional) "setup" argument with is a piece of code to be executed before the execution of the tested code, ie:
import timeit
timeit.timeit("s.endwith('d')", "s = 'Hello World'", number=10000)

which will execute both statements but only benchmark the first one.
This is also useful if you want to benchmark a function imported from a module:
timeit.timeit("re.search(r'42', 'hello world')", "import re")

or from your current script or interactive shell session:
$ python
Python 3.6.5 (default, Apr  1 2018, 05:46:30)
[GCC 7.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> def foo():
>>>    return 42
>>> import timeit
>>> timeit.timeit("foo()", "from __main__ import foo")

A: I'm going to guess you do not have that much experience programming in python, otherwise the SyntaxError would have been clear enough. The exception given states that the syntax (ie. lines of code) is invalid.
Valid (Compound statement) code. But harder to read so not advised:
s='Hello world'; s.endswith('d')

Invalid code:
s='Hello world'  s.endswith('d')

The latter would raise an exception, which will try to highlight the exact location of where the exception is caused with an '^'.
s='Hello world'  s.endswith('d')
  File "<stdin>", line 1
    s='Hello world'  s.endswith('d')
                     ^
SyntaxError: invalid syntax

For testing small bits of code with timeit, you could put the code into a function and call that. For example:
import timeit

def test():
    s = 'Hello world'
    s.endswith('d')

if __name__ == '__main__':
    t = timeit.Timer('test()', setup='from __main__ import test')
    num_of_repeat = 1000
    runs = t.repeat(repeat=num_of_repeat, number=1)
    print('Fastest run of {3} repeats: {0}ms  Slowest: {1}ms  Average: {2}ms'.format(
        min(runs) * 1000, max(runs) * 1000, (sum(runs) / float(len(runs))) * 1000, num_of_repeat))

Put this into a file called mytest.py, and run it from commandline:
python mytest.py

A: If you want to run several statements you can simply use the triple quotes for your code. Example:
import timeit
code = """
s = 'Hello world'
s.endswith('d')
"""
timeit.timeit(code, number=10000)

A: The issue is that s = 'Hello World' and s.endswith('d')
are two separate statements so either they have to be in different lines or they must me separated using a semi-colon
So change it to
timeit.timein("s = 'Hello World'; s.endswith('d')",number=10000)


text:
Q: Android : Is there way to Play sequential mp3 files from urls without interrupt? I am creating application that load sequential mp3 files from URLs. As i try it with initialize next mp3 files on completion of first mp3 files, but the problem is that, when first files complete, player take time to prepare or initialize the next mp3 files, yes I know that is part of the media player,it will take time to Prepare(For prepare() it may be long And for prepareAsync() comparatively sort time).
But , What i need that, when first mp3 files complete there playing, next mp3 files (From url) should not take time to prepare,as it should play without interrupt. I want to know , Is there way to attach next mp3 files for buffering while playing current mp3?, so we can playing it without interrupt.
As i tried also it with downloading next mp3 file in cache while playing first one. But the problem is that when complete first one, the second mp3 file may be not fully download(which is too poor for 2g connection). and player will initialize the part of the mp3 file which is downloaded. and player will play only that part of the downloaded files which is initialized(please correct if i wrong).it cause files corrupt. and it is not good performance at all.
I tried to cache next mp3 files while current mp3 played about 75% percentage, but in that case the mp3 files doesn't cached fully and it cause also files corrupt.
So please give me suggestion, how can i playing sequential mp3 files without inrerupt ? And batter approch to do that. Thanks in advance

A: Just save all Urls in an ArrayList and note the current index of songUrl. And add SekkCompleteListener to it.When a song finishes change the index and play it .And full detail tutorial is AndroidHive
if(currentSongIndex < (songsList.size() - 1)){
                    playSong(currentSongIndex + 1);
                    currentSongIndex = currentSongIndex + 1;
                }else{
                    // play first song
                    playSong(0);
                    currentSongIndex = 0;
                }

Where playSong is
public void  playSong(int songIndex){
        // Play song
        try {
            mp.reset();
            mp.setDataSource(songsList.get(songIndex).get("songPath"));
            mp.prepare();
            mp.start();
            // Displaying Song title
            String songTitle = songsList.get(songIndex).get("songTitle");
            songTitleLabel.setText(songTitle);

            // Changing Button Image to pause image
            btnPlay.setImageResource(R.drawable.btn_pause);

            // set Progress bar values
            songProgressBar.setProgress(0);
            songProgressBar.setMax(100);

            // Updating progress bar
            updateProgressBar();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

MediaPlayer.OnSeekCompleteListener

A: Use setNextMediaPlayer(mp) API which is specially designed for your case. You have to prepare another instance of MediaPlayer during playback and set it as next. Then you will have no time waste between tracks. Basicly you have to use 2 instances and swap them back and forth.


text:
Q: Download a file from a Server with double ssh I connect to a Server with ssh
Step 1:
$ ssh userid@something.com

and then it asks for password and everything is ok
Then I connect to a DB
Step2:
$ssh user1@smthing_else

and then it asks for password and everything is ok
Now when I type ls I can see the file that I want to download...
How can I download this file on my Desktop..??

A: I guess you can't directly reach the "inner" host from the outside? In that case you have to ssh into the outer host, then you can use scp to copy the file from the inner host to the outer one. Accordingly, you can then copy the file to your local pc from the outer host with scp (or whatever you can use in that case).
scp works like this (to copy a local file to a remote host):
scp myfile.txt user@somehost.com:/home/user/whatever

resp. like this (remote to local):
scp user@somehost.com:/home/user/whatever/myfile.txt .

A: You need to scp the file twice in order to bring it to local m/c if you don't have direct access. First ssh to the server 1 and run the command to download it. Then run this command again from your local m/c.
scp -r -i path-to-secret-key ubuntu@ec2-address:/home/ubuntu/app-folder-location /home/user/local-mc-location

As you don't have the key, use the below command
scp -r ubuntu@ec2-address:/home/ubuntu/app-folder-location /home/user/local-mc-location

Update:
path-to-secret-key is the private key address which is used in ec2 instances to ssh. They are used for authentication and are present in home/.ssh/private-key. They have a permission of 400 and are either .pem extension for unix m/c's or ppk extension for windows m/c's


text:
Q: Having more than one Get in Restful webservice I am working on a project to connect test instruments and get request and response from it using webservice.
I have to request more than one service from the instrument, but when I use more than two @Gets in the server, I get an error in my browser saying

Cannot access WADL, please restart your restful webservice

This is my code,
GET
@Produces("text/html")
public String getHtml(){
   String ins_name=null;

   try {
      String [] env=null;
      //setting the environment variable.
      String[]callAndArgs= {"python","instrument_name.py"};//Python and file name

      Process p = Runtime.getRuntime().exec(callAndArgs,env,
         new java.io.File("C:\\fakepath\\NetBeansProjects\\DemoApp1\\build\\web"));//executing Python file

      BufferedReader stdInput = new BufferedReader(new
      InputStreamReader(p.getInputStream()));//getting the value from Python file
      BufferedReader stdError = new BufferedReader(new
      InputStreamReader(p.getErrorStream()));// reading the error
      ins_name = stdInput.readLine();//reading the output from the Pythonfile
      System.out.println(ins_name);
   }
   catch (IOException e) {//catching the exception

      System.out.println("exception occured");
      e.printStackTrace();
      System.exit(-1);
   }

   return ins_name;//returning the instrument name
}

@GET
@Produces("text/html")
public String getHtml1() {
   String check=null;
   String c1="hjhj";
   String [] env=null;
   //setting the environment variable.
   try{
      String[] callAndArgs= {"python","check_connection.py",c1};//Python and file name

      Process p = Runtime.getRuntime().exec(callAndArgs,env,
      new java.io.File("C:\\Users\\Balkishore\\Documents\\NetBeansProjects\\DemoApp1\\build\\web"));//executing Python file

      BufferedReader stdInput = new BufferedReader(new
      InputStreamReader(p.getInputStream()));//getting the value from Python file

      BufferedReader stdError = new BufferedReader(new
         InputStreamReader(p.getErrorStream()));// reading the error

      check= stdInput.readLine();//reading the output from the Python file
      System.out.println();
   }
   catch (IOException e) {//catching the exception

      System.out.println("exception occured");
      e.printStackTrace();
      System.exit(-1);
   }
   return check;
}

/**
* Web service operation

}

/**
* PUT method for updating or creating an instance of GenericResource
* @param content representation for the resource
* @return an HTTP response with content of the updated or created resource.
*/
@PUT
@Consumes("text/html")
public String putHtml(String interface_name) {

   try {
      String [] env=null;
      String [] callAndArgs= {"python","connection.py",this.interface_name=interface_name};//Python file with arguments

      Process p = Runtime.getRuntime().exec(callAndArgs,env,
         new java.io.File("C:\\fakepath\\NetBeansProjects\\DemoApp1\\build\\web"));//executing the Python file

      BufferedReader stdInput = new BufferedReader(new
         InputStreamReader(p.getInputStream()));//getting the input

      BufferedReader stdError = new BufferedReader(new
         InputStreamReader(p.getErrorStream()));//getting the error

      interface_name = stdInput.readLine();//reading the output
      System.out.println(interface_name);
   }
   catch (IOException e) {//catching the exception
      System.out.println("exception occured");
      e.printStackTrace();
      System.exit(-1);

   }
   return interface_name;
}
}

I have also attached the image of the error message.

A: You can't define distinct "GET" for a resource unless you specify distinct Path for your methods  @Path("/mypath") in addition to your resource path
@Path("/myRes")
public class myResource{

   @GET @Path("/myAttr")
   public void getAttr(...)
}


text:
Q: Show/Hide (via Bootstrap's collapse function) divs based on radio button I'm trying to use Bootstrap's collapse functionality to show/hide divs based on which radio button is checked.  I was able to get things to work fine when I don't use Bootstrap's collapse function, however, in order to give a more consistent feel I'd like to take advantage of this function.
Here's a snippet of the HTML in question:

    <input type="radio" id="send-now-radio" name="when" value="send-now" checked> Send Now

    <input type="radio" id="pickup-radio" name="when" value="pickup"> Hold for pickup

    <input type="radio" id="fax-radio" name="when" value="fax"> Fax

    <input type="radio" id="email-radio" name="when" value="email"> Email

Send

Pickup

Fax

Email

And here's my javascript code:
$(document).ready(function()
{
  // Hide all but one method div (since all are shown in case the user has JS disabled)
  $('#send').show();
  $('#pickup').hide();
  $('#fax').hide();
  $('#email').hide();

  // Attach to the radio buttons when they change
  $('#send-now-radio, #pickup-radio, #fax-radio, #email-radio').on('change', function () {
    // Make sure that this change is because a radio button has been checked
    if (!this.checked) return

    // Check which radio button has changed
    if (this.id == 'send-now-radio') {
      $('#send').collapse('show');
      $('#pickup').collapse('hide');
      $('#fax').collapse('hide');
      $('#email').collapse('hide');
    } else if (this.id == 'pickup-radio') {
      $('#send').collapse('hide');
      $('#pickup').collapse('show');
      $('#fax').collapse('hide');
      $('#email').collapse('hide');
    } else if (this.id == 'fax-radio') {
      $('#send').collapse('hide');
      $('#pickup').collapse('hide');
      $('#fax').collapse('show');
      $('#email').collapse('hide');
    } else // if (this.id == 'email-radio') {
      $('#send').collapse('hide');
      $('#pickup').collapse('hide');
      $('#fax').collapse('hide');
      $('#email').collapse('show');
    }
  });
};

Here's a link to a JS fiddle with all of this: http://jsfiddle.net/DTcHh/156/
Unfortunately I'm missing something, cause the behavior is weird and not what I would expect.

A: First of all, excellent question. You provided code, made it clear what you tried, etc. Love it.
I forked your JSFiddle, and came up with this:
http://jsfiddle.net/emptywalls/EgVF9/
Here's the Javascript:
$('input[type=radio]').on('change', function () {
    if (!this.checked) return
    $('.collapse').not($('div.' + $(this).attr('class'))).slideUp();
    $('.collapse.' + $(this).attr('class')).slideDown();
});

I wouldn't recommend using the collapse functionality from Bootstrap, it relies on a very different DOM structure from what you need. My fiddle uses just jQuery to accomplish what you need. My approach was to pair the radio buttons and divs with classes, so you can DRY up your code.

A: As @emptywalls mentioned, the Bootstrap collapse function won't work. I tried it and it almost does, except that it is based on clicking the source element, not it's state. A radio button needs to pay attention to it's state.
But I wanted something that allowed me to mark up the element with data tags and have it inherit the functionality, as the bootstrap collapse does. So I came up with this:
<input data-target="#send" data-toggle="radio-collapse" id="send_now_radio" name="when" type="radio" value="send-now">

Send

And then have this included once in your site and it will apply to all such buttons.
$('input[type=radio][data-toggle=radio-collapse]').each(function(index, item) {
  var $item = $(item);
  var $target = $($item.data('target'));

  $('input[type=radio][name="' + item.name + '"]').on('change', function() {
    if($item.is(':checked')) {
      $target.collapse('show');
    } else {
      $target.collapse('hide');
    }
  });
});

This uses the collapse function of Bootstrap for the animation. You could just as easily use jQuery hide() and show().

A: Unless I'm mistaken, @jwadsack code won't work if you have another group of radio buttons with a different name attribute.
That's because the $item and $target variables are declared globally. The $item variable will be overidded by the last group and only this one will hide/show the collaspe.
Adding var before the variable definition seems to fix the problem.
The code is then
$('input[type=radio][data-toggle=radio-collapse]').each(function(index, item) {
  var $item = $(item);
  var $target = $($item.data('target'));

 $('input[type=radio][name="' + item.name + '"]').on('change', function() {
   if($item.is(':checked')) {
     $target.collapse('show');
    } else {
     $target.collapse('hide');
   }
 });
});


text:
Q: OpenVPN via proxy not sure what's happening, Clarification about theory? I'm currently running OpenVPN and a squid proxy on a small VPS.
In the config file of the VPN I'm using OpenVPN proxy options to connect to the proxy before the VPN.
The interesting part of the configuration is like this:
*Note: the redacted IP in the config file is the same as both squid and OpenVPN server are on the same VPS.
[...]
remote xxx.xxx.xxx.xxx 15855 tcp-client
http-proxy xxx.xxx.xxx.xxx 3128
[...]
http-proxy-option CUSTOM-HEADER Host [redacted]
[...]

I understand that the proxy is located before the VP connection, but squid being an HTTP proxy how can it handle the TCP connection to the VPN?
When the custom header is passed? It's passed when the client connects to the proxy or when from the proxy the packets go to the VPN?
Can anybody explain it or point me to some reference to better understand what's happening?

A: Proxies like Squid supports a bunch of different HTTP request methods. You have probably heard of GET, POST etc, but there are others like the one OpenVPN is utilising above; CONNECT.
CONNECT creates a "tunnel" over HTTP, and you can read more on this wikipedia page.

A: The "proxy" in OpenVPN only means that the OpenVPN client is connected to the server through a proxy, like socks5 proxy you can open on a ssh client. Unless you set squid to be the http proxy on a given port, it will automatically hijack any outbound traffic to port 80 or port 443 with its own cached files. Under this settings, you can view squid as reverse-proxy like nginx who does not provide a real http proxy.


text:
Q: Wordpress plug-in to instantly reply to a form? Does anyone know if there is a wordpress plug-in which lets you set up a form which has an email field, among others.
The form, after filled in, would:

*

*send the content of the form fields to an email address (name:joe, phone number: 555 etc)

*send an instance response to the email provided ('thanks for your contribution')

*add email address to an internal database (which is exportable) within the wprdpress admin

Thanks.

A: This will accomplish your task and more - http://wordpress.org/extend/plugins/formstack/

A: cformsII from Delicious Day is what you're looking for.  Customizable, easy to set up, and can be set up to track all form submissions.  Find it at http://www.deliciousdays.com/cforms-plugin/


text:
Q: Google Maps is not woking I am trying to show google map in my application, but it displays small squares boxes screen instead of google maps
Here is my Mainactivity
public class MainActivity extends FragmentActivity {

    private static final int GPS_ERRORDIALOG_REQUEST = 9001;
    GoogleMap mMap;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (servicesOK()) {
            //Toast.makeText(this, "Google play services successfully connected.", Toast.LENGTH_SHORT).show();
            setContentView(R.layout.activity_map);
        }else{
            setContentView(R.layout.activity_main);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    public boolean servicesOK(){
        int isAvailable = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
        if (isAvailable == ConnectionResult.SUCCESS) {
            return true;
        }else if (GooglePlayServicesUtil.isUserRecoverableError(isAvailable)) {
            Dialog dialog = GooglePlayServicesUtil.getErrorDialog(isAvailable, this, GPS_ERRORDIALOG_REQUEST);
            dialog.show();
        }else{
            Toast.makeText(this, "Can't connect to google play services.", Toast.LENGTH_SHORT).show();
        }
        return false;
    }

My activiy_map.xml
<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:map="http://schemas.android.com/apk/res-auto"
    android:id="@+id/map"
    android:name="com.google.android.gms.maps.SupportMapFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

My mainfest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.gmapapp"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />

    <permission
        android:name="com.example.gmapapp.permission.MAPS_RECEIVE"
        android:protectionLevel="signature"/>

    <uses-permission android:name="com.example.gmapapp.permission.MAPS_RECEIVE"/>
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission
        android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true"/>
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.gmapapp.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <meta-data android:name="com.google.android.gms.version"
           android:value="@integer/google_play_services_version" />

        <meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="API_KEY"/>

    </application>

</manifest>

My logcat
11-30 15:23:13.430: E/dalvikvm(6948): GC_CONCURRENT freed 1785K, 24% free 7739K/10147K, paused 3ms+12ms
11-30 15:27:45.260: E/dalvikvm(6948): GC_CONCURRENT freed 1673K, 24% free 7781K/10147K, paused 3ms+4ms
11-30 15:30:40.500: E/dalvikvm(7048): GC_CONCURRENT freed 1007K, 18% free 7301K/8803K, paused 2ms+3ms
11-30 15:30:40.840: E/dalvikvm(7048): GC_FOR_ALLOC freed 856K, 23% free 7424K/9571K, paused 2ms+5ms
11-30 15:30:41.040: E/dalvikvm(7048): GC_FOR_ALLOC freed 842K, 23% free 7460K/9571K, paused 2ms+4ms

A: You must get api key for this application
https://developers.google.com/maps/documentation/android/start#obtain_a_google_maps_api_key
In manifest
   <meta-data
        android:name="com.google.android.maps.v2.API_KEY"
        android:value="08DEBUGKEYABCDEFBLAHBLAHBLAH"/>

A: I think your problem is simply that you have not turned on google maps api in your google console online go there: https://cloud.google.com/console/project
click on your project then on APIs and Auth and then select google maps andorid api v2
this should help :)


text:
Q: Kivy how can I customize video's size and position So I'm able to use the video library to play video on my GUI, but I realized the video was always placed at the middle with the default size, as there are no attribute like pos or size in video class. I would like to know if there are any way I can size and place the video like other widgets/buttons/labels.

A: The following example illustrates sizing and placing a video.
Example
In the following demo, we are using AnchorLayout. You can replace it with any Layouts (BoxLyout, FloatLayout, etc.), Widget, etc. and use pos or pos_hint.
main.py
from kivy.base import runTouchApp
from kivy.lang import Builder

runTouchApp(Builder.load_string("""
AnchorLayout:
    anchor_x: 'center'
    anchor_y: 'top'
    Video:
        source: 'rtsp://184.72.239.149/vod/mp4:BigBuckBunny_175k.mov'
        state: 'play'
        keep_ratio: True
        allow_stretch: True
        size_hint: 0.8, 0.8
"""))


text:
Q: Type-proofing primitive .NET value types via custom structs: Is it worth the effort? I'm toying with the idea of making primitive .NET value types more type-safe and more "self-documenting" by wrapping them in custom structs. However, I'm wondering if it's actually ever worth the effort in real-world software.

(That "effort" can be seen below: Having to apply the same code pattern again and again. We're declaring structs and so cannot use inheritance to remove code repetition; and since the overloaded operators must be declared static, they have to be defined for each type separately.)

Take this (admittedly trivial) example:
struct Area
{
    public static implicit operator Area(double x) { return new Area(x); }
    public static implicit operator double(Area area) { return area.x; }

    private Area(double x) { this.x = x; }
    private readonly double x;
}

struct Length
{
    public static implicit operator Length(double x) { return new Length(x); }
    public static implicit operator double(Length length) { return length.x; }

    private Length(double x) { this.x = x; }
    private readonly double x;
}

Both Area and Length are basically a double, but augment it with a specific meaning. If you defined a method such as…
    Area CalculateAreaOfRectangleWith(Length width, Length height)

…it would not be possible to directly pass in an Area by accident. So far so good.
BUT: You can easily sidestep this apparently improved type safety simply by casting a Area to double, or by temporarily storing an Area in a double variable, and then passing that into the method where a Length is expected:
    Area a = 10.0;

    double aWithEvilPowers = a;
    … = CalculateAreaOfRectangleWith( (double)a, aWithEvilPowers );

Question: Does anyone here have experience with extensive use of such custom struct types in real-world / production software? If so:

*

*Has the wrapping of primitive value types in custom structs ever directly resulted in less bugs, or in more maintainable code, or given any other major advantage(s)?

*Or are the benefits of custom structs too small for them to be used in practice?

P.S.: About 5 years have passed since I asked this question. I'm posting some of my experiences that I've made since then as a separate answer.

A: This is a logical next step to Hungarian Notation, see an excellent article from Joel here http://www.joelonsoftware.com/articles/Wrong.html
We did something similar in one project/API where esp. other developers needed to use some of our interfaces and it had siginificantly less "false alarm support cases" - because it made really obvious what was allowed/needed... I would suspect this means measurably less bugs though we never did the statistics because the resulting apps were not ours...

A: In the aprox. 5 years since I've asked this question, I have often toyed with defining struct value types, but rarely done it. Here's some reasons why:

*

*It's not so much that their benefit is too small, but that the cost of defining a struct value type is too high. There's lots of boilerplate code involved:

*

*Override Equals and implement IEquatable<T>, and override GetHashCode too;

*Implement operators == and !=;

*Possibly implement IComparable<T> and operators <, <=, > and >= if a type supports ordering;

*Override ToString and implement conversion methods and type-cast operators feom/to other related types.

This is simply a lot of repetitive work that is often not necessary when using the underlying primitive types directly.

*Often, there is no reasonable default value (e.g. for value types such as zip codes, dates, times, etc.). Since one can't prohibit the default constructor, defining such types as struct is a bad idea and defining them as class means some runtime overhead (more work for the GC, more memory dereferencing, etc.)

*I haven't actually found that wrapping a primitive type in a semantic struct really offers significant benefits with regard to type safety; IntelliSense / code completion and good choices of variable / parameter names can achieve much of the same benefits as specialized value types. On the other hand, as another answer suggests, custom value types can be unintuitive for some developers, so there's an additional cognitive overhead in using them.
There have been some instances where I ended up wrapping a primitive type in a struct, normally when there are certain operations defined on them (e.g. a DecimalDegrees and Radians type with methods to convert between these).
Defining equality and comparison methods, on the other hand, does not necessarily mean that I'd define a custom value type. I might instead use primitive .NET types and provide well-named implementations of IEqualityComparer<T> and IComparer<T> instead.

A: I did this in a project a couple of years ago, with some mixed results.  In my case, it helped a lot to keep track of different kinds of IDs, and to have compile-time errors when the wrong type of IDs were being used.  And I can recall a number of occasions where it prevented actual bugs-in-the-making.  So, that was the plus side.   On the negative side, it was not very intuitive for other developers -- this kind of approach is not very common, and I think other developers got confused with all these new types springing up.  Also, I seem to recall we had some problems with serialization, but I can't remember the details (sorry).
So if you are going to go this route, I would recommend a couple of things:
1)  Make sure you talk with the other folks on your team first, explain what you're trying to accomplish and see if you can get "buy-in" from everyone.  If people don't understand the value, you're going to be constantly fighting against the mentality of "what's the point of all this extra code"?
2)  Consider generate your boilerplate code using a tool like T4.  It will make the maintenance of the code much easier.  In my case, we had about a dozen of these types and going the code-generation route made changes much easier and much less error prone.
That's my experience.  Good luck!
John

A: I don't often use structs.
One thing you may consider is to make your type require a dimension. Consider this:
public enum length_dim { meters, inches }
public enum area_dim { square_meters, square_inches }
public class Area {
    public Area(double a,area_dim dim) { this.area=a; this.dim=dim; }
    public Area(Area a) { this.area = a.area; this.dim = a.dim; }
    public Area(Length l1, Length l2)
    {
        Debug.Assert(l1.Dim == l2.Dim);
        this.area = l1.Distance * l1.Distance;
        switch(l1.Dim) {
            case length_dim.meters: this.dim = square_meters;break;
            case length_dim.inches: this.dim = square_inches; break;
        }
    }
    private double area;
    public double Area { get { return this.area; } }
    private area_dim dim;
    public area_dim Dim { get { return this.dim; } }
}
public class Length {
    public Length(double dist,length_dim dim)
    { this.distance = dist; this.dim = dim; }
    private length_dim dim;
    public length_dim Dim { get { return this.dim; } }
    private double distance;
    public double Distance { get { return this.distance; } }
}

Notice that nothing can be created from a double alone. The dimension must be specified. My objects are immutable. Requiring dimension and verifying it would have prevented the Mars Express disaster.

A: I can't say, from my experience, if this is a good idea or not. It certainly has it's pros and cons. A pro is that you get an extra dose of type safety. Why accept a double for an angle when you can accept a type that has true angle semantics (degrees to/from radians, constrained to degree values of 0-360, etc). Con, not common so could be confusing to some developers.
See this link for a real example of a real commercial product that has several types like you describe:
http://geoframework.codeplex.com/
Types include Angle, Latitude, Longitude, Speed, Distance.


text:
Q: Qt - How to build a multi-tab window? I want to build a single-window application which has two tabs. How can I set two tabs on the window and click to switch, just like the browser's window and tabs ?
PS: The two tabs have different layout of buttons and text-widgets and functions differently.

A: http://doc.qt.io/qt-5/qtabwidget.html#details

The QTabWidget class provides a stack of tabbed widgets.
A tab widget provides a tab bar (see QTabBar) and a "page area" that
  is used to display pages related to each tab. By default, the tab bar
  is shown above the page area, but different configurations are
  available (see TabPosition). Each tab is associated with a different
  widget (called a page). Only the current page is shown in the page
  area; all the other pages are hidden. The user can show a different
  page by clicking on its tab or by pressing its Alt+letter shortcut if
  it has one.
The normal way to use QTabWidget is to do the following:

*

*Create a QTabWidget.

*Create a QWidget for each of the pages in the tab dialog, but do not specify parent widgets for them.

*Insert child widgets into the page widget, using layouts to position them as normal.

*Call addTab() or insertTab() to put the page widgets into the tab widget, giving each tab a suitable label with an optional keyboard
  shortcut.

  The position of the tabs is defined by tabPosition, their shape by
  tabShape.
...

And there is your answer.
EDIT: Link to an example, too.
http://doc.qt.io/qt-5/qtwidgets-dialogs-tabdialog-example.html
Update: In addition to all the advantages that come with using the QTabWidget, some additional functionality of tabs come with the QDockWidget, like tearing them off into a separate window.  I've used QDockWidgets recently to get nearly the same appearance of tabs, but the baked in tear-off, and the right click for a checked listing of tabs.
Hope that helps.


text:
Q: modified mongodb database and facing problems I am implementing authentication in my website using passport-local-mongoose but when registering new users I receive the following error:
MongoServerError: E11000 duplicate key error collection: myDatabase.users index: email_1 dup key: { email: null }

I previously had an email field for my user but I deleted it because it was not necessary for my application
here is my model
 var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var passportLocalMongoose = require('passport-local-mongoose');

var UserSchema = new Schema({
    username : {type: String, unique: true, required: true},
});

UserSchema.plugin(passportLocalMongoose);

 module.exports = mongoose.model("User", UserSchema);

I am also using mongodb atlas as my database
This error didn't show up the first time I registered a new user
How can I fix this problem?

A: It looks like the email field you used to have had a unique index set on it.
The first user got created fine with no email as there were no other users with "email": null set on them. Now that there is one, all new users without email will be duplicates, and a unique index does not allow duplicates.
Indexes, unlike schemas, are set on the database and not just in code. This means you will have to delete the index from your database. You can do this via any GUI mongodb browser. As you are using Atlas, you can do it directly via their web interface. Here are the instructions:

Drop an Index
To drop an index from a collection through the Data Explorer:
1 Go to the Indexes tab.
Select the collection whose index you wish to drop, and go to the
Indexes tab.
2 Click the Drop Index button for the index to drop.
3 Confirm action.
Confirm by typing the name of the index, and click Drop.


text:
Q: How scrap a div only when it contains a certain text- SELENIUM Python I'm trying to automate LinkedIn and want to scrap the profile URL only if they are already not in a pending state.

Status is offline

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 14 14" data-supported-dps="14x14" fill="currentColor" class="mercado-match" width="14" height="14" focusable="false">
<g>
<path class="background-mercado" d="M14 1v12a1 1 0 01-1 1H1a1 1 0 01-1-1V1a1 1 0 011-1h12a1 1 0 011 1zM4 5H2v7h2zm.25-2A1.27 1.27 0 003 1.8 1.27 1.27 0 001.75 3 1.27 1.27 0 003 4.2 1.27 1.27 0 004.25 3zM12 8.29c0-2.2-.73-3.49-2.86-3.49A2.71 2.71 0 006.89 6V5H5v7h2V8.73A1.74 1.74 0 018.66 6.8C9.82 6.8 10 7.94 10 8.73V12h2z"></path>
</g>
</svg>

• 2nd2nd degree connection

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 14 14" data-supported-dps="14x14" fill="currentColor" class="mercado-match" width="14" height="14" focusable="false">
<g>
<path class="background-mercado" d="M14 1v12a1 1 0 01-1 1H1a1 1 0 01-1-1V1a1 1 0 011-1h12a1 1 0 011 1zM4 5H2v7h2zm.25-2A1.27 1.27 0 003 1.8 1.27 1.27 0 001.75 3 1.27 1.27 0 003 4.2 1.27 1.27 0 004.25 3zM12 8.29c0-2.2-.73-3.49-2.86-3.49A2.71 2.71 0 006.89 6V5H5v7h2V8.73A1.74 1.74 0 018.66 6.8C9.82 6.8 10 7.94 10 8.73V12h2z"></path>
</g>
</svg>

• 2nd2nd degree connection

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" data-supported-dps="16x16" fill="currentColor" class="mercado-match" width="16" height="16" focusable="false">
<path d="M14 11.75V15H9v-3.25A1.75 1.75 0 0110.75 10h1.5A1.75 1.75 0 0114 11.75zM11.5 9A2.5 2.5 0 109 6.5 2.5 2.5 0 0011.5 9zM5 1a3 3 0 103 3 3 3 0 00-3-3zm.75 7h-1.5A2.25 2.25 0 002 10.25V15h6v-4.75A2.25 2.25 0 005.75 8z"></path>
</svg>

<button aria-label="Withdraw invitation sent to Grigorij Aronov" id="ember57" class="artdeco-button artdeco-button--muted artdeco-button--2 artdeco-button--full artdeco-button--secondary ember-view" type="button">

Pending
</button>

Status is offline

• 2nd2nd degree connection

• 2nd2nd degree connection

  #

    #

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" data-supported-dps="16x16" fill="currentColor" class="mercado-match" width="16" height="16" focusable="false">
<path d="M14 11.75V15H9v-3.25A1.75 1.75 0 0110.75 10h1.5A1.75 1.75 0 0114 11.75zM11.5 9A2.5 2.5 0 109 6.5 2.5 2.5 0 0011.5 9zM5 1a3 3 0 103 3 3 3 0 00-3-3zm.75 7h-1.5A2.25 2.25 0 002 10.25V15h6v-4.75A2.25 2.25 0 005.75 8z"></path>
</svg>

        <button aria-label="Invite Lucas Teuchner to connect" id="ember55" class="artdeco-button artdeco-button--2 artdeco-button--secondary ember-view">
Connect</button>

There are 2 blocks of HTML. One contains a button with "Pending" and the other with "Connect". I want to scrap the profile URL of the one inside "Connect" li.
If you find this question stupid, I'm sorry. I'm not advanced in Selenium.
Thanks in advance

A: You should be able to locate that element with the following (if element is not in an iframe, shadow root, or some other unforeseen elements in that page):
profile_link = WebDriverWait(browser,10).until(EC.element_to_be_clickable((By.XPATH, "//span[text() = 'Connect']/ancestor::li//a[@class = 'app-aware-link']")))

You will also need to import:
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC


text:
Q: Jquery method doesn't work on dynamically generated elements I'm trying to create a price list and validate its values.
This is my function:

(function($) {
        $.fn.inputFilter = function(inputFilter) {
            return this.on("input keydown keyup mousedown mouseup select contextmenu drop", function() {
                if (inputFilter(this.value)) {
                    this.oldValue = this.value;
                    this.oldSelectionStart = this.selectionStart;
                    this.oldSelectionEnd = this.selectionEnd;
                } else if (this.hasOwnProperty("oldValue")) {
                    this.value = this.oldValue;
                    this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd);
                } else {
                    this.value = "";
                }
            });
        };
    }(jQuery));

    // Para números enteros
    $(".intTextBox").inputFilter(function(value) {
        return /^-?\d*$/.test(value);
    });

<input class="intTextBox" id="intTextBox">

This works fine.
But when I insert elements dynamically the method doesn't work.

(function($) {
        $.fn.inputFilter = function(inputFilter) {
            return this.on("input keydown keyup mousedown mouseup select contextmenu drop", function() {
                if (inputFilter(this.value)) {
                    this.oldValue = this.value;
                    this.oldSelectionStart = this.selectionStart;
                    this.oldSelectionEnd = this.selectionEnd;
                } else if (this.hasOwnProperty("oldValue")) {
                    this.value = this.oldValue;
                    this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd);
                } else {
                    this.value = "";
                }
            });
        };
    }(jQuery));

    // Para números enteros
    $(".intTextBox").inputFilter(function(value) {
        return /^-?\d*$/.test(value);
    });

    $('#add').click(function(e){
      $('#generate').append('<input id="intTextBox" class="intTextBox">');
    }
    );

<button id="add">ADD</button>

  <input id="intTextBox" class="intTextBox">

how could i solve this? I've been looking all morning, thanks for reading.(I have more validation methods, this is a small summary).

A: append DOM elements with already connected validation methods
    $('#add').click(function(e){
      $('#generate').append('<input id="intTextBox"
        class="intTextBox">').inputFilter(function(value) {
         return /^-?\d*$/.test(value);
        });
      }
    );

A: When you reference an element, it does not keep looking for new elements that are added after the code runs. So it will not locate dynamically created inputs.
You need to create the element and use inputFilter on that element.
$(".intTextBox").inputFilter(function(value) {
    return /^-?\d*$/.test(value);
});

$('#add').click(function(e){
  var newInput = $('<input name="intTextBox" class="intTextBox">');
  newInput.inputFilter(function(value) {
    return /^-?\d*$/.test(value);
  });
  $('#generate').append(newInput);
}

to remove the code duplication
function addFilter (elems) {
  elems.inputFilter(function(value) {
    return /^-?\d*$/.test(value);
  });
}

addFilter($(".intTextBox"));

$('#add').click(function(e){
  var newInput = $('<input name="intTextBox" class="intTextBox">');
  addFilter(newInput);
  $('#generate').append(newInput);
}

A: The code below randomizes your ID for the new element to avoid conflict (not a perfect solution; just a hacky work-around for the example), and then applies the filter on the new element.

(function($) {
  $.fn.inputFilter = function(inputFilter) {
    return this.on("input keydown keyup mousedown mouseup select contextmenu drop", function() {
      if (inputFilter(this.value)) {
        this.oldValue = this.value;
        this.oldSelectionStart = this.selectionStart;
        this.oldSelectionEnd = this.selectionEnd;
      } else if (this.hasOwnProperty("oldValue")) {
        this.value = this.oldValue;
        this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd);
      } else {
        this.value = "";
      }
    });
  };
}(jQuery));

function getRandomInt(max) {
  return Math.floor(Math.random() * Math.floor(max));
}

// Para números enteros
$(".intTextBox").inputFilter(function(value) {
  return /^-?\d*$/.test(value);
});

$('#add').click(function(e) {
  let randomId = "intTextBox_" + getRandomInt(100000);
  $('#generate').append(`<input id="${randomId}" class="intTextBox">`);
  $(`#${randomId}`).inputFilter(function(value) {
    return /^-?\d*$/.test(value);
  });

});

<button id="add">ADD</button>

  <input id="intTextBox" class="intTextBox">


text:
Q: laravel how bind all classes which implemented specific interface? in laravel 5.4 we can bind a class which known and we use it anywhere after binded but if we wants bind some classes implemented specific interface how we bind dynamically ?
for example:
interface x {}

class a implements x {}
class b implements x {}
class c implements x {}
class d implements x {}
class e implements x {}

in service provider how can i bind all classes implemented x dynamicaly so in
 future i will add some class implemeted x. how can i do?


text:
Q: Generating FSK Modulated signals in GnuRadio I am trying to recreate the signal from the RC car toy and control it with HackRf and GNU-Radio.
I have identified following:

*

*Controller operates on 2.463 GHz

*The bandwidth is 1MHz

*

*Logical "1" 2.4635 GHz

*Logical "0" 2.4625 GHz

*Baud rate 1e6 samples

*I have demodulated the signals with Quadrature Demod block and I have extracted the sequence of 1s and 0s

*I created the binary file which stores the 0s and 1s pattern that I would like to transmit.

Now I want to recreate this signal based on the upper parametrs. Through some research I came up with the following setup for transmission:

But I have several questions that I am not sure how to resolve:

*

*Based on this paper I have found out that there is a relation between modulation index, sample rate and difference between frequencies (screenshot from there):

Based on that I have set sample rate to 2M, BT to 0.5, but I am not sure if thats right.

*Also I dont quite understand how to adjust other parameters and what they mean.

I would really appreciate if somebody can give intuitive explanation on how these things should be adjusted.
EDIT:
I also implemented new schematics based on the Tutorial from GNURadio about FSK:

Sniffing with other HackRf I couldn't find any signal transmitted, can you tell me what is wrong with this setup or what would be the best approach to recreate the required signal?

A: For starters, what is the objective of your project? If it is just to mimic what your RC controller is doing, you could store the received bits into packed bytes and write a file. But, I would start with a thorough analysis of the signal from your RC toy:
a) what are the audio frequencies, or at least what is the difference between the high and low tones? are there more than two tones? how do you know it's FSK?
b) what is the bit time, i.e. the shortest period you can find between transitions? that determines the baud rate.
With no documentation, you have a lot of experimenting to do on the receive side before you can attempt to transmit anything meaningful. Maybe you can find something in the RC literature about it.


text:
Q: myBatis offset position setting issue for infinite scroll I am building a Quora like application. The backend uses spring boot, mybatis to connect to a mysql database. When a user opens the website, the backend returns the first 10 questions. If the user clicks the "fetch more" button, the backend should return the next 10 questions.
The mybatis code is
<mapper namespace="com.quora.dao.QuestionDAO">
    <sql id="table">question</sql>
    <sql id="selectFields">id, title, content, comment_count,created_date,user_id
    </sql>
    <select id="selectLatestQuestions" resultType="com.quora.model.Question">
        SELECT
        <include refid="selectFields"/>
        FROM
        <include refid="table"/>

        <if test="userId != 0">
            WHERE user_id = #{userId}
        </if>
        ORDER BY id DESC
        LIMIT #{offset},#{limit}
    </select>
</mapper>

Currently, my logic is that the first time #{offset} is 0, the second time #{offset} is 10. But I find that this logic is not correct when the table updates frequently. The user may get duplicate data if the table has been inserted new rows. How can I set the #{offset} based on the last question id shown in the front end? For example, the last question id in the front end is 10, then the #{offset} should be the row number of question id 10.
Can anyone give me some suggestions?
Thanks,
Peter

A: The general idea is to not use OFFSET at all and do filtering instead. If you can define the order on the messages so that it does not change when new messages are inserted (for example you incrementally generate ids and sort message by id ASC) then it is easy:
SELECT id, some_other_field, yet_another_field
FROM question
<if test="last_seen_question_id != null">
    WHERE id > #{last_seen_question_id}
</if>
ORDER BY id ASC
LIMIT #{limit}

Then client should use the last seen question id and pass it when it wants to fetch the next page.
From your query (ORDER BY id DESC) it looks like you want to see the newest questions in the top. This is a bit of a problem as newly inserted questions will tend to get to the top.
If you are ok to get new questions on the next page first and then older questions you can do like this:
<!-- This condition is needed to avoid duplication when the first page is fetched
     and we haven't seen any question yet.
     In this case we just get up to limit of the last questions.
-->
<if test="newest_seen_question_id != null">
SELECT * FROM (
  -- select all questions that were created _after_
  -- the last seen max question id
  -- client should maintain this value as in get the
  -- largest question id for every page and compare it
  -- with the current known max id. And client should
  -- do it for the whole duration of the paging
  -- and pass it to the follow up queries
  SELECT id, some_other_field, yet_another_field
  FROM question
  WHERE id > #{newest_seen_question_id}
  -- note that here we do sorting in the reverse order
  -- basically expanding the set of records that was returned
  -- in the direction of the future
  ORDER BY id ASC
  LIMIT #{limit}
  UNION ALL
</if>
  -- select all questions that were created _before_
  -- the last seen min question id.
  -- client should maintain this value for the whole
  -- duration of the paging
  -- and pass it to the follow up queries
  SELECT id, some_other_field, yet_another_field
  FROM question
  <if test="oldest_seen_question_id != null">
    WHERE id < #{oldest_seen_question_id}
  </if>
  ORDER BY id DESC
  LIMIT #{limit}
<if test="newest_seen_question_id != null">
) AS q
ORDER BY id DESC
LIMIT #{limit}
</if>

Another benefit is that this approach to paging that does not use OFFSET is much better from performance standpoint.


text:
Q: Matching a value in one column to the name of another column I have a char column, where I need to match the value of that column to the name of other column in my data frame in order to extract the value from the other column. I have added a picture as I think it will be easier to understand.

A: We can use row/column indexing to extract the elements from the first dataset and create the 'result' column in 'd2'
d2$result <- d1[-1][cbind(1:nrow(d1), match(d2$mycol, names(d1)[-1]))]
d2
#  mycol result
#1     a     40
#2   bxb     88
#3   bxb     76
#4    ct     33

It could be also that there is a single dataset available i.e. 'd1' and want to get the 'd2'.  In that case, do a melt and subset
library(reshape2)
subset(melt(d1, id.var="mycol"), mycol==variable, select= c(1,3))

data
d1 <- data.frame(mycol = c("a", "bxb", "bxb", "ct"), a = c(40, 8, 43, 94),
 `bxb` =c(7, 88, 76, 12), ct = c(4,6, 8954, 33), stringsAsFactors=FALSE,
 check.names=FALSE)
d2 <- data.frame(mycol = c('a', 'bxb', 'bxb', 'c'), stringsAsFactors=FALSE)


text:
Q: Rails 3 Custom FormBuilder Parameters I create a custom FormBuilder for my application, but I dont understand why I need to pass tow parameters as follow:
f.text_field :my_model, :my_field

Here is my builder:
class AceBuilder < ActionView::Helpers::FormBuilder
  %w[text_field password_field text_area].each do |method_name|
    define_method(method_name) do |object_name, method, *args|
      options = args.extract_options!

      @template.content_tag(:div, :class => "control-group #{@object.errors[method].length > 0 ? 'error' : ''}") do
        @template.concat(
            @template.content_tag(:label,
                                  options[:label] || method.to_s.humanize,
                                  :class => 'control-label',
                                  :for => "#{object_name}_#{method}"))
        @template.concat(
            @template.content_tag(:div,
                                  :class => "controls") do
              @template.concat(super(method))

              @template.concat(
                  @template.content_tag(:span,
                                        @object.errors[method].join,
                                        :for => "#{object_name}_#{method}",
                                        :class => "help-inline"
                  )
              )
            end
        )
      end
    end
  end

I know that
define_method(method_name) do |object_name, method, *args|

has two parameters, so my question is:
How can I write this FormBuilder, such a way that I can call it like this:
f.text_field :my_field

Thanks.

A: That was easy, after I realize how: replace object_name by @object_name
class AceBuilder < ActionView::Helpers::FormBuilder
  %w[text_field password_field text_area].each do |method_name|
    define_method(method_name) do |method, *args|
      options = args.extract_options!

      @template.content_tag(:div, :class => "control-group #{@object.errors[method].length > 0 ? 'error' : ''}") do
        @template.concat(
            @template.content_tag(:label,
                                  options[:label] || method.to_s.humanize,
                                  :class => 'control-label',
                                  :for => "#{@object_name}_#{method}"))
        @template.concat(
            @template.content_tag(:div,
                                  :class => "controls") do
              @template.concat(super(method))

              @template.concat(
                  @template.content_tag(:span,
                                        @object.errors[method].join,
                                        :for => "#{@object_name}_#{method}",
                                        :class => "help-inline"
                  )
              )
            end
        )
      end
    end
  end


text:
Q: vs code not installing on Chromebook I was trying to install vs code on Chromebook with Linux but i get it off the website and go into the file and it says "apt is not install able" and things like it for about five rows of text I hope someone knows the answer.

A: Try beginning with sudo apt install as opposed to apt install.  Linux can be wishy washy when it comes to installs in the terminal.


text:
Q: what is the protocol be used in SSLContext.getInstance I'm tring JDK1.7 with the code below
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null,null,null);
SSLSocketFactory sf = sc.getSocketFactory();
SSLSocket ss = (SSLSocket)sf.createSocket();
System.out.println(Arrays.toString(ss.getSupportedProtocols()));

No matter what protocol I put as getInstance parameter, there is no change in the result. I have tried these protocols:

*

*SSLv2Hello

*SSLv3

*TLSv1

*TLSv1.1

*TLSv1.2

Where does this parameter take effect, as I can call sslsocket.setEnabledProtocols to set protocols I want later?

A: It affects the enabled protocols.
It would be more interesting if you had printed the result of getEnabledProtocols() rather than getSupportedProtocols().


text:
Q: N случайных элементов из std::set Есть std::set минимум из N элементов. Как выбрать N разных случайных?Порядок любой.

A: Если постановка задачи требует именно работы на структуре данных с последовательным доступом, то классический "алгоритм Кнута" подойдет прекрасно: проходим последовательно по элементам std::set и принимаем решение брать очередной элемент с вероятностью осталось набрать элементов / осталось пройти элементов
int main()
{
    std::set<int> s = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

    unsigned N = 3;
    std::vector<int> r;

    auto it = s.begin();
    for (unsigned S = s.size(); S > 0 && N > 0; --S, ++it)
      if (rand() % S < N)
      {
        r.push_back(*it);
        --N;
      }

    std::copy(r.begin(), r.end(), std::ostream_iterator<int>(std::cout, " "));
    std::cout << std::endl;
}

Такой алгоритм выполнит случайную выборку N элементов с сохранением их относительного порядка из исходного std::set. Если порядок тоже надо получить случайный, то можно просто дополнительно сделать случайную перетасовку полученной выборки.
Другим вариантом будет алгоритм "резервуарной выборки", согласно которому мы сначала сразу забираем N первых элементов из std::set в нашу выборку, а затем итерируем через оставшиеся элементы std::set (начиная с элемента с номером i = N). Каждый новый элемент мы забираем в выборку с вероятностью N / (i + 1) и сохраняем в случайную позицию в выборке
int main()
{
    std::set<int> s = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

    unsigned N = 3;
    std::vector<int> r;

    auto it = s.begin();
    unsigned i = 0;

    for (; i < N; ++i, ++it)
      r.push_back(*it);

    for (; it != s.end(); ++i, ++it)
      if (rand() % (i + 1) < N)
        r[rand() % N] = *it;

    std::copy(r.begin(), r.end(), std::ostream_iterator<int>(std::cout, " "));
    std::cout << std::endl;
}

Такой алгоритм уже не будет сохранять относительный порядок элементов в выборке. Однако из-за того, что первые N элементов выбраны по порядку, полной случайности порядка и тут нет.
Интересной особенностью варианта "резервуарной выборки" является то, что ему не нужно знать размера исходной последовательности заранее, т.е. его можно использовать для генерации случайной выборки из последовательности, генерируемой неким "оракулом", не зная заранее, когда эта последовательность закончится. (Например, для случайной выборки строк из текстового файла нет необходимости знать заранее, сколько в этом файле строк.)

Если бы исходный контейнер поддерживал эффективный прямой доступ по индексу элемента (т.е. если бы это был массив, а не std::set), то такие подходы были бы довольно неэффективными в ситуациях, когда N намного меньше, чем размер исходного контейнера. Но в случае std::set это соображение неприменимо.

A: Если воспользоваться дополнительным вектором - просто: выбираем в нем эти N элементов, а потом берем соответствующие из множества.
Вряд ли вы будете работать с ними прямо во множестве - скорее всего, вы будете использовать либо копии элементов, либо итераторы/указатели, на них указывающие. В таком случае можно просто загрузить их в вектор, перемешать и выбрать первые N, например.
Если вы уточните, как вы планируете их использовать - можно будет уточнить способ :)

A: используйте  альгоритм  std::random_shuffle или  std::next_permutation


text:
Q: In C# should my Common.Logging logger be an instance member or static? Looking a project that uses Common.Logging for .NET, I noticed that some classes declare the logger instance as a class static member. For instance:
public class HelloJob : IJob
{
    private static ILog _log = LogManager.GetLogger(typeof(HelloJob));

    public HelloJob()
    {
    }

    public virtual void  Execute(IJobExecutionContext context)
    {
        _log.Info(string.Format("Hello World! - {0}", System.DateTime.Now.ToString("r")));
    }
}

And in other classes the logger is declared as an instance member:
public class SimpleExample : IExample
{
    public virtual void Run()
    {
        ILog log = LogManager.GetLogger(typeof (SimpleExample));

        log.Info("------- Initializing ----------------------");

        // etc
    }
}

Is there a reason to prefer one approach or the other?
In which cases is each approach recommended? Is it related to thread safety?
Would it be a problem if I just declared a "Logger" class with a static "logger" member and the whole project used that (apart from the issue that I would in practice have a global variable)?

A: Most loggers are thread safe, and creating instances of them has very little overhead, both in terms of time and memory. So the real question needs to be what makes sense from a programming and maintainability standpoint.
On the one hand, since the logger is conceptually tied to your class, and not to the instance of the class, a lot of people prefer to keep it static. That's a perfectly valid argument. For example, if HelloWorldJob extends HelloJob, I think most people would expect the log message written by code in HelloJob to be tied to the HelloJob class, even though you have a more specific subclass instance. It's also nice to be able to access your logger from static methods, which wouldn't be possible if it's not on a static field.
On the other hand, there is no reason that your HelloJob should be responsible for getting its own logger instance. There's a lot to be said for using dependency injection instead (unit testability, additional configurability, and simpler code). So I personally suggest having your logger injected by a DI framework, in which case it would need to be referenced on a per-instance field.
public class HelloJob : IJob
{
    private readonly ILog _log;

    public HelloJob(ILog log)
    {
        _log = log;
    }
    ...
}

Your DI framework can set up the logger based on details it knows at run-time, or you can provide a fake or mocked logger in your unit tests to make sure the expected log messages are produced. Note that even though you are referring to a per-instance field, you're perfectly free to still use a per-class (or even a singleton) instance--those are just details that don't need to be part of this class's concern.
Update
Over time I've shifted my opinion more in the direction of using a static logger. More specifically, I really like using Fody Anotar libraries to generate the static logger (and other helpful code) for me, so all I have to write in my source code is logging statements like:
LogTo.Info("This is a message");


text:
Q: Get the ping from a remote target with Qt (Windows/Linux) Currently I use this code for retrieving the ping of a target system.
However it works so far only under linux and it is likely dependent on the locale settings.
To add support for windows will be likely even more complicated.
Is there an easy way or library to get the ping of a target system? I mainly work with Qt, so it would be ideal if I could work with QSockets.
#ifndef _WIN32
QProcess ping;
ping.start("ping", QStringList() << "-c 1" << m_sHostName);
if(ping.waitForFinished(250) ) {
    while(ping.canReadLine()) {
        QString line = ping.readLine();
        if(line.contains("time=")) {
            int iStart = line.indexOf("time=") + 5;
            int iStop = line.indexOf(" ms");
            QStringRef latency(&line, iStart, iStop-iStart);

            m_vNetwork_s.append(time_s);
            m_vLatency_ms.append(QString(latency.toLocal8Bit()).toDouble());
            break;
        }
    }
}
#endif

A: Nejat's code didn't work for me neither. Maybe it's Windows specific (tested on Windows 7 x64 + Qt 5.6).
Ping command seems to distinct parameters and values and needs them to be passed apart when creating QProcess.
So instead of passing "-n 1" in one go, you'll need to pass "-n" and "1" separately.
Basically, with Nejat's code it would be:
int exitCode = QProcess::execute("ping", QStringList()
                                     << "-n" << "1"
                                     << m_sHostName);
if (exitCode==0) {
    // it's alive
} else {
    // it's dead
}

Tested and working now.

A: You would need write your code for this without QAbstractSocket. In short, this base class was not designed for this use case.
The reason is that you would need to use raw sockets and run as root; that is also why you usually see the setuid flag set on the ping executable on Linux.
ICMP is "connectionless", and as such the Qt class is not feasible for it as it does not provide sending data to a specific host, etc.
You can read the more thorough explanation in here.

A: The ping method return a 0 exit code event if the target is unreachable in Windows.
You have to parse the command output.
The following example is working on Windows and linux :
class MyClass {
  private slots:
   void OnPing();
   void OnPingEnded();
  private:
   Process mPingProcess;
};

void MyClass::OnPing()
{
   connect(&mPingProcess, SIGNAL(finished(int,QProcess::ExitStatus)), this, SLOT(OnPingEnded()));
#ifdef __linux__
   mPingProcess.start("ping", QStringList() << "-c" << "1" << ui->ip->text());
#else
   mPingProcess.start("ping", QStringList() << "-n" << "1" << ui->ip->text());
#endif
}

void MyClass::OnPingEnded()
{
    QByteArray output = mPingProcess.readAllStandardOutput();
    if (!output.isEmpty())
    {
        qDebug() << output;
        if (-1 != QString(output).indexOf("ttl", 0, Qt::CaseInsensitive))
        {
           qDebug() << "PING OK";
        }
        else
        {
           qDebug() << "PING KO";
        }
    }
}

A: You can ping on both Windows and Linux using this:
   QStringList parameters;
#if defined(WIN32)
   parameters << "-n" << "1";
#else
   parameters << "-c 1";
#endif

   parameters << m_sHostName;

   int exitCode = QProcess::execute("ping", parameters);
   if (exitCode==0) {
       // it's alive
   } else {
       // it's dead
   }


text:
Q: How to implement a generic react native backdrop? I want to create a generic component that should detect required component View outside click (hide the View/dropdown, etc. when pressed outside).  Basically it's for the Autocomplete Search Dropdown but I guess such functionality could be used in the future for other things.

*

*The content should be dynamic and could be passed from any level of the app because such functionality is a common UX thing.

*It shouldn't be modal that always render content at the screen center because a dropdown should be opened below its trigger, etc. So it should respect the initial component position. (In think to use onLayout/measure API of the initial position when passing the content into the Backdrop)

I researched a lot of resources and found that the one possible way is:

*

*Create a TouchableWithoutFeedback layer (Backdrop) at the top level of the app.

*make it fullscreen with/height

*When dropdown is shown: render the Backdrop and onPress on it - close the dropdown & backdrop.

The main question is: How to pass a generic content into this Layer and save its relationship with the parent/props, re-render when needed, etc.?
Please, keep in mind, that the component which should pass content for this layer could be deep inside the app.
I guess it could be done via Context API, etc. but I'm not sure if it's the best possible way.
P.S. in the case of web it's a trivial task: create a fullscreen layer -> use a portal -> move content at the top level of the app -> render it at the required X\Y position and listen for the outside press.
I didn't expect that such functionality will be a problem in the case of RN.
Thanks for any help.


text:
Q: ignore touch events I´m making a game with cocos2d and need to ignore touch events in some cases, esp. when another touch is "in progress".
It is, the player touches the screen, moves the finger around and then ends the touch. During this period, I need to ignore all other touches that may occur. How can I do that?

A: self.userInteractionEnabled = YES;


text:
Q: iOS dev center certificates, identifiers & profiles gets stuck in loading screen I have this very frustrating issue with iOS dev center. Every time I want to add a new iOS-device by its UDID the site gets stuck in the loading screen. This same problem occurs when I want to change an existing distribution profile. The site just goes "Loading" forever.
Considering that this occurs on all my devices (computers, mobilephones etc.) I would be very grateful if someone had any idea how to deal with this problem..

A: I had the same issue for some time now. Actually even it is get stuck the device is added to  my list. So just refresh the page after a while to see if it is added.

A: I did a bit of research into what the underlying issue was with this on Chrome.  Seems there are multiple parts to this issue.
Firstly clearing cookies seem to help (partly) it got me past one hanging loading screen (first step of adding a new device), however I was still hanging on the next step.
Further investigation with Chrome developer tools indicated that Chrome was refusing to load some content due to XHR restrictions.  Seems that Apple mixes https and http content. I was able to get past that by click on the shield icon on the right on the address bar and telling Chrome to allow the mixed content.
Finally there was also an issue with X-FRAME-OPTIONS headers that are being sent in the response which generate the following errors
Multiple 'X-Frame-Options' headers with conflicting values ('SAMEORIGIN, SAMEORIGIN, DENY') encountered when loading 'https://developer.apple.com/account/ios/device/deviceComplete.action?returnURL='. Falling back to 'DENY'.

Refused to display 'https://developer.apple.com/account/ios/device/deviceComplete.action?returnURL=' in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN, SAMEORIGIN, DENY'.

There are a couple of extensions available to remove X-FRAME-OPTION headers, but I wasn't able to get those working and wouldn't really recommend it.
My guess is that this works ok on Safari as it's not as strict on the XHR and X-FRAME-OPTION rules.
Anyway hope that helps someone. I'm going to raise a support request with Apple to see if they can get it sorted.

A: Are you using Safari? For some reason the dev site doesn't always play nice with other browsers like Chrome and Firefox

A: I have same issue with Chrome and Safari on OS X but it works fine with Chrome on Ubuntu.

A: Try deleting the cookies in chrome settings.This has always helped me.


text:
Q: Binary Tree in Java - why do i have an "empty" node (with a blank String) in my Tree? Basically, my problem with my code is that somewhere in its implementation it creates a blank node which is then inserted into my binary tree. This node exists, as my sizeOfTree method counts it as such.
The code works just fine, the only problem is the node.
OK, so here I have defined the TreeNode based on which the Binary Tree is constructed:
    package hr.fer.oop.lab1.prob6;

    public class TreeNode {
    TreeNode left=null;
    TreeNode right=null;
    String data;
    public TreeNode(String data) {
    this.data=data;
    }
    }

And here is the rest of it:
package hr.fer.oop.lab1.prob6;
import hr.fer.oop.lab1.prob6.TreeNode;
public class BinaryTree {
TreeNode root;
public BinaryTree() {
TreeNode node = new TreeNode("");
root=node;
}
public void insert (String data) {
    if (this.root==null) {
        this.root=new TreeNode(data);
        return;
    }
    else {
    TreeNode node = this.root;
    TreeNode parent = new TreeNode("");
    while(node!=null) {
        parent = node;
        if (node.data.compareTo(data)<=0) {
            node=node.left;
        }
        else{
            node=node.right;
        }
    }
        if (parent.data.compareTo(data)<=0) {
            parent.left=new TreeNode(data);
        }
        else {
            parent.right=new TreeNode(data);
        }
    }
    return;
}

private boolean subTreeContainsData(TreeNode node, String data) {
    if ((node.data).compareTo(data)<1E-15) return true;
    TreeNode temp=new TreeNode("");
    temp=node;
    if((temp.left.data).equals("")&&(temp.right.data).equals("")) return false;
    return (subTreeContainsData(temp.left, data)||subTreeContainsData(temp.right, data));
}
private boolean containsData(String data) {
    return subTreeContainsData(root, data);
}
private int sizeOfSubTree(TreeNode node) {
    if (node==null) return 0;
    return 1 + sizeOfSubTree(node.left) + sizeOfSubTree(node.right);
}
public int sizeOfTree() {
    return sizeOfSubTree(root);
}
private void writeSubTree(TreeNode node) {
    if (node!=null) {
    writeSubTree(node.left);
    System.out.println(node.data);
    writeSubTree(node.right);
    }
    return;
}
public void writeTree() {
    writeSubTree(root);
}
private void reverseSubTreeOrder(TreeNode node) {
    if (node==null) return;
    TreeNode helpNode;
    helpNode=node.left;
    node.left=node.right;
    node.right=helpNode;
    reverseSubTreeOrder(node.left);
    reverseSubTreeOrder(node.right);
}
public void reverseTreeOrder() {
    reverseSubTreeOrder(root);
}
public static void main (String[] args) {
    BinaryTree tree = new BinaryTree();
    tree.insert("Jasna");
    tree.insert("Ana");
    tree.insert("Ivana");
    tree.insert("Anamarija");
    tree.insert("Vesna");
    tree.insert("Kristina");

    System.out.println("Writing tree inorder:");
    tree.writeTree();
    tree.reverseTreeOrder();
    System.out.println("Writing reversed tree inorder:");
    tree.writeTree();
    int size=tree.sizeOfTree();
    System.out.println("Number of nodes in tree is "+size+".");
    boolean found = tree.containsData("Ivana");
    System.out.println("Searched element is found: "+found);
}
}

Much appreciate any help provided.

A: You create an empty TreeNode in your constructor and make it the root of the tree:
public BinaryTree() {
    TreeNode node = new TreeNode("");
    root=node;
}

Later, in your insert method, your if (this.root==null) condition is always false, so you don't assign the first inserted node to the root.
Just remove it:
public BinaryTree() {
}


text:
Q: Java Netbeans MySql database Connection I want to insert row into MySql database with a normal Program for Mysql connection in Java Netbeans,but when i run this code my database remains unaffected.I had setup connection with Netbeans and Mysql and it is working fine.
Code:
    import java.sql.*;

    public class MySqlConnection {

       static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
       static final String DB_URL = "jdbc:mysql://localhost:3306/migration";
       static final String USER = "root";
       static final String PASS = "ngts12345";

       public static void main(String[] args) {

            Connection conn = null;

            try{
             Class.forName("com.mysql.jdbc.Driver");
             System.out.println("Connecting to a selected database...");
             conn = DriverManager.getConnection(DB_URL, USER, PASS);
             System.out.println("Connected database successfully...");
             System.out.println("Inserting records into the table...");

             String sql = "INSERT INTO document (document_id, document_name, format)" +
            "VALUES (?, ?, ?)";
             PreparedStatement preparedStatement = conn.prepareStatement(sql);
             preparedStatement.setInt(1, 1);
             preparedStatement.setString(2, "Test2");
             preparedStatement.setString(3, "Test3");
             preparedStatement.executeUpdate();
             preparedStatement.close();
             conn.close();
        }catch(SQLException se){
          //Handle errors for JDBC

       }catch(Exception e){
          //Handle errors for Class.forName

       }
     }
  }

A: there is not space after format) and values
Change this line to
String sql = "INSERT INTO document (document_id, document_name, format)" +
        "VALUES (?, ?, ?)";

to
String sql = "INSERT INTO document(document_id, document_name, format) " +
        "VALUES (?, ?, ?)";

A: Try doing this:
preparedStatement.executeUpdate(sql);

and you should also specify database
String sql = "INSERT INTO database_name.document (document_id, document_name, format)" +"VALUES (?, ?, ?)";

A: try{
  Class.forName("com.mysql.jdbc.Driver"); // MySQL database  connection
  conn = DriverManager.getConnection("jdbc:mysql://localhost:3306","root","");
  String sql = "select * from 'table_name'.database_name where user=? and pass=?";
  pst = conn.prepareStatement(sql);
  rs= pst.executeQuery();
}

A: Note preparedStatement.executeUpdate() returns true (record was successful in insert, update, or delete) or false (not successful). Therefore I suggest printing out the result to see if it worked.
As for not getting an error message, are you consuming exceptions and not printing out the error? In your catch block, put e.printStackTrace() to see what the error is.


text:
Q: Lifetime of rvalue bound to static const reference Consider this:
std::string foo();

void bar() {
         const std::string& r1 = foo();
  static const std::string& r2 = foo();
}

I know that the lifetime of the string resulting from the first call to foo() will be extended to the lifetime of r1.
What about the temporary bound to r2, though? Will it live until the end of the scope or will it still be there when bar() is re-entered?
Note: I am not interested whether a particular compiler does so. (I am interested in the one we use, and I can test easily with that.) I want to know what the standard has to say on this.

A: The temporary is extended to the lifetime of the reference.

[C++14: 12.2/5]: The temporary to which the reference is bound or the temporary that is the complete object of a subobject to which the reference is bound persists for the lifetime of the reference except:

*

*A temporary bound to a reference member in a constructor's ctor-initializer (12.6.2) persists until the constructor exits.

*A temporary bound to a reference parameter in a function call (5.2.2) persists until the completion of the full-expression containing the call.

*The lifetime of a temporary bound to the returned value in a function return statement (6.6.3) is not extended; the temporary is destroyed at the end of the full-expression in the return statement.

*A temporary bound to a reference in a new-initializer (5.3.4) persists until the completion of the full-expression containing the new-initializer. [ Example:
struct S { int mi; const std::pair<int,int>& mp; };
S a { 1, {2,3} };
S* p = new S{ 1, {2,3} }; // Creates dangling reference

—end example ] [ Note: This may introduce a dangling reference, and implementations are encouraged to issue a warning in such a case. —end note ]

(In particular, note that none of the bullet points match this scenario.)
So, in this case, it's essentially until the program ends.
We can, of course, test this pretty trivially:
#include <iostream>

struct Tracked
{
    Tracked() { std::cout << "ctor\n"; };
    Tracked(const Tracked&) { std::cout << "copy\n"; };
    ~Tracked() { std::cout << "dtor\n"; };
};

void foo()
{
    static const Tracked& ref = Tracked();
}

int main()
{
    std::cout << "main()\n";
    foo();
    std::cout << "bye\n";
}

Result:

main()
  ctor
  bye
  dtor

(live demo)


text:
Q: create new column that compares across rows in pandas dataframe I am looking to create a new column in a dataframe based on the values seen in the next 2 rows.  Specifically, if any values in the next 2 rows are below 4, then I want the new value in the current row to be 0 (and if all values in the next 2 rows are above 4 then I want the new value in the current row to be 1).
>>> df = pandas.DataFrame({"A": [5,6,7,3,2]})
>>> df
   A
0  5
1  6
2  7
3  8
4  2
>>> desired_result = pandas.DataFrame({"A": [5,6,7,8,2], "new": [1,1,0,0,0]})
>>> desired_result
   A  new
0  5    1
1  6    1
2  7    0
3  8    0
4  2    0

Where you can see that in the "desired_result" the first value is 1 because 6 and 7 are both > 4 (and hte same logic applies) until in the third row the new value becomes 0 because when we look ahead to the next two rows (8,2) then we see that 2 is < 4 so the value becomes 0.
I have been trying to use the apply function but I cannot figure out how to pass along the next 2 row values as inputs.
I have found lots of help on this site about comparing across columns, but cannot figure out how to "look ahead" like I described.
Thanks for the help!

A: You can set the new value to one and then use loc together with shift and lt (less than) to set the appropriate values to zero.
df = pd.DataFrame({"A": [5, 6, 7, 8, 2]})
df['new'] = 1

df.loc[(df.A.shift(-1).lt(4)) | (df.A.shift(-2).lt(4)), 'new'] = 0

# The last value does not have any future observations and should be set to zero.
df.new.iat[-1] = 0

>>> df
   A  new
0  5    1
1  6    1
2  7    0
3  8    0
4  2    0

To expand to the next 8 rows instead of 2:
nrows = 8
df.loc[eval(" | ".join("df.A.shift(-{0}).lt(4)".format(n)
                       for n in range(1, nrows + 1))), 'new'] = 0


text:
Q: Google map memory usage on VB.Net form I am using a Google map inside of vb.net application. The problem is that it keeps taking a memory space whenever I search a map on a web browser which is on a windows form . Even though I close the form, it is not disappeared from memory. The size of memory is just going up. That goes away when I close MDI form.
What is the solution for this? How do I manage the memory problem?
-->Edited : One of out team member found the solution. It worked out pretty well. Just call the function whenever you want to do it. I used it on Form Closing event.
<DllImport("psapi.dll")> _
    Public Function EmptyWorkingSet(ByVal hProcess As IntPtr) As Boolean
    End Function

    <DllImport("kernel32.dll", CharSet:=CharSet.Auto, SetLastError:=True)> _
    Public Function GetCurrentProcess() As IntPtr
    End Function

    Public Sub FreeMemory()
        EmptyWorkingSet(GetCurrentProcess())
    End Sub

A: Check out my answer to this question. I believe your best bet is to do some profiling.
I ran the trial version of ANTS memory profiler, against an app I was working on and the problem I discovered is outlined in this walthrough of how to use the tool (specifically the details around figures 10 - 15).
Basically, I was subscribing to some events on a form, but then not unsubscribing from them when the form was closed. This meant there was still a reference to the form and it (along with all it's controls and members) were never collected.
Maybe you have a similar situation, but your best bet is to look at the code in a profiler. It doesn't have to be this one (this is just the one I've used). It will certainly help you identify the root cause of your problem.

A: This is from the liberal garbage collection in .NET.  If you're really concerned about memory, try this.
First, ensure that the objects you wish to remove have been disposed.  If this is a Windows Form, this should be automatic.
Call System.GC.Collect().  You should see your memory usage decrease.

A: As a work around you could use an MDI parent and put your maps into MDI child forms opening up a new one each time (or periodically closing unused ones)?


text:
Q: java.lang.NullPointerException with a POST call in Karate I have a feature file like below:
*Feature: Create Quote in D365
  Background:
    * def myFeature = call read('D365_Authentication.feature')
    * header Authorization = 'Bearer ' + myFeature.BearerToken
    * def random_string =
      """
      function(s){
      var text = "";
      var pattern = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
      for(var i=0; i<s; i++)
        text += pattern.charAt(Math.floor(Math.random() * pattern.length()));
        return text;
      }
      """
    * url '<somehost>'
  Scenario: Create Opportunity
    Given path '<path>'
    And def requestPayload = read('CreateOpportunity.json')
    And set requestPayload.name = 'Temp Opportunity From Karate ' + random_string(10)
    And set requestPayload.hsl_closedate = '2022-03-23T00:00:00.000Z'
    And header Content-Type = 'application/json'
    And request requestPayload
    When method POST
    Then status 204*

When running this, getting NullPointerException. Can anybody help me identify why this exception is coming.

A: Firstly you need to download the jar file specific karate version from https://github.com/karatelabs/karate/releases.
Please unfold the Assets link.
You can run the feature file so:
java - jar jarfinename -m xxx.feature


text:
Q: How to convert a signed int to its hex representation on nbBits, in Ruby? For instance : -78_base10 on 8 bits is 0xB2
The pseudo-algorithm says : "-A =/A+1"
For instance :

*

*-78 => 78 => 01001110

*Then apply 'bar' : 01001110 => 10110001

*Then '+1' : 10110001 + 1 = 10110010

*convert in hexa : 0xB2

How to get the result nicely in Ruby (with or without this 'algorithm').

A: How about something like
def signed_int_to_hex(n)
  "0x%X" % (n % 2 ** 8)
end

signed_int_to_hex(-78) #=> "0xB2"

A: ((-78) % 2 ** 8).to_s(16)
# => "b2"


text:
Q: React setState returns function dispatch() I have met issues setting the state of the const displayClipName in the following function which is blocking despite the fact that I passed the props from the parent element to the child.
const audioClips = [
        {
        keyCode: 67,
        keyTrigger: "C",
        id: "Closed-HH",
        src: "https://s3.amazonaws.com/freecodecamp/drums/Cev_H2.mp3"
    }
]

function App() {

    const [displayClipName, setDisplayClipName] = React.useState('Click a key!')

    return (

FCC - Drum Machine

                {audioClips.map((clip) => (
                <Pad
                    key={clip.id}
                    clip={clip}
                    setDisplayClipName={setDisplayClipName}
                />
                ))}

{displayClipName}

    )
}

const Pad = ({clip, setDisplayClipName}) => {
    const [playing, setPlaying] = React.useState(false)

    React.useEffect(() => {
        document.addEventListener('keydown', handleKey);
        return () => {
            document.removeEventListener('keydown', handleKey)
        }
    }, [])

    const handleKey = (e) => {
        if(e.keyCode === clip.keyCode) {
            playSound()
            }
    }

    const playSound = () => {
        const audioPlay = document.getElementById(clip.keyTrigger);
        const clipName = document.getElementById(clip.id)
        setPlaying(true);
        setTimeout(() => setPlaying(false), 300);
        audioPlay.currentTime = 0;
        audioPlay.play();
        setDisplayClipName(clipName);
        console.log(setDisplayClipName)
    }

    return (
        <div onClick={playSound} id={`drum-pad-${clip.keyTrigger}`}>
            <audio src={clip.src} className="clip" id={clip.keyTrigger}/>
            {clip.keyTrigger}

    )
}

const container = document.getElementById('root');
const root = ReactDOM.createRoot(container);
root.render(<App />);

The console returns the following message:
function dispatchSetState()

length: 1

name: "bound dispatchSetState"

<prototype>: function ()

A: As some have pointed out in comments to your post it'd be better if you used refs. Also you were logging a function that's why the console displayed that. I have taken the liberty to do some modifications to your code so I could understand it better, I would suggest you keep the ones you find reasonable:

*

*The displayName variable has an undefined state when no song is playing. This could be set from any other part of the application but you wouldn't depend on rerendering the component for it to return to a default message ("Press a key!")

*The playSound function could be bound to the id of the song and you would avoid having to check the HTML element that received the input.

Here is a working snippet.

const { useState, useEffect } = React;

const audioClips = [
  {
    keyCode: 67,
    keyTrigger: "C",
    id: "Closed-HH",
    src: "https://s3.amazonaws.com/freecodecamp/drums/Cev_H2.mp3"
  }
]

const Pad = ({ clip, setDisplayClipName }) => {
  const [playing, setPlaying] = useState(false);

  useEffect(() => {
    document.addEventListener("keydown", handleKey);
    return () => {
      document.removeEventListener("keydown", handleKey);
    };
  }, []);

  const handleKey = (e) => {
    if (e.keyCode === clip.keyCode) {
      playSound(clip.id);
    }
  };

  const playSound = (clipId) => {
    const audioPlay = document.getElementById(clip.keyTrigger);
    setPlaying(true);
    setTimeout(() => setPlaying(false), 300);
    audioPlay.currentTime = 0;
    audioPlay.play();
    setDisplayClipName(clipId);
  };

  return (

 playSound(clip.id)} id={`drum-pad-${clip.keyTrigger}`}>
      <audio src={clip.src} className="clip" id={clip.keyTrigger} />
      {clip.keyTrigger}

  );
};

function App() {
  const [clipName, setClipName] = useState(undefined);

  return (

FCC - Drum Machine

        {audioClips.map((clip) => (
          <Pad key={clip.id} clip={clip} setDisplayClipName={setClipName} />
        ))}

{clipName ? clipName : "Press a key!"}

  );
}

ReactDOM.createRoot(
    document.getElementById("root")
).render(
    <App />
);

To further refine the Pad component and avoid the missing dependencies on the useEffect hook I would suggest you model it like this, using useMemo:
export const Pad = ({ clip, setDisplayClipName }) => {
  const [playing, setPlaying] = useState(false);
  const playSound = useMemo(
    () => () => {
      const audioPlay = document.getElementById(clip.keyTrigger);
      setPlaying(true);
      setTimeout(() => setPlaying(false), 300);
      if (audioPlay) {
        audioPlay.currentTime = 0;
        audioPlay.play();
      }
      setDisplayClipName(clip.id);
    },
    [setDisplayClipName, clip]
  );

  useEffect(() => {
    const handleKey = (e) => {
      if (e.keyCode === clip.keyCode) {
        playSound();
      }
    };

    document.addEventListener("keydown", handleKey);
    return () => {
      document.removeEventListener("keydown", handleKey);
    };
  }, [playSound, clip.keyCode]);

  return (
    <div onClick={playSound} id={`drum-pad-${clip.keyTrigger}`}>
      <audio src={clip.src} className="clip" id={clip.keyTrigger} />
      {clip.keyTrigger}

  );
};