text:
Q: Rgd: PHP-FPM Installation Rgd: PHP-FPM Installation
I used to install PHP-FPM by this ways..
rpm -Uvh http://rpms.famillecollet.com/enterprise/remi.repo
yum --enablerepo=remi install php-fpm

But now i try the same way, it give me php-fpm package not found.
I am running CentOS 6 with php 5.3.26(cli) installed.
I am trying install php-fpm and then do a service php-fpm start which I did for my other server but today I try install the same thing using the same steps it does not work..
Anyone can guide me on how to get php-fpm setup on my this new server

A: Since CentOS 6.4 is PHP-FPM included in their php builds.
You can try :
rpm --import http://rpms.famillecollet.com/RPM-GPG-KEY-remi
rpm -ivh http://rpms.famillecollet.com/enterprise/remi-release-6.rpm

yum install yum-priorities

and edit:
vi /etc/yum.repos.d/remi.repo

and set:
enabled=1
priority=10

Let me know if it worked out for you!


text:
Q: Почему Room меняет последовательность елементов при получении? Вполне стандартная ситуация
Я сохраняю 4 елемента в БД в последовательности 1, 2, 3, 4
Я использую Stetho для того, чтоб посмотреть как они сохранились в БД и действительно все правильно сохранено
Но когда мне нужно получить все элементы с БД я использую такой метод
@Query("SELECT * FROM mytable WHERE name = :i AND state = :iS")
List<MyObj> getAll(String i,  String iS);

То порядок возвращенных элементов которые я получаю вот такой 1, 2, 4, 3
Что делаю не так?

A: SQL не гарантирует постоянный порядок строк, тем более в том порядке, в котором данные были размещены в БД
Стоит попробовать добавить сортировку вроде такого:
@Query("SELECT * FROM mytable WHERE name = :i AND state = :iS ORDER BY id")
List<MyObj> getAll(String i,  String iS);

Только id заменить на то поле, которое хранит порядок добавления/следования элементов

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to authenticate as admin, query and mutate Hasura in python? I'm trying to find any documentation with examples to authenticate to hasura on heroku in python and query and mutate data, I couldn't find any info on this topic, can you guy please help me?

A: I think what you can do is send, just like in the other languages, a request to your hasura endpoint and add the header x-hasura-admin-secret and your secret key.
       {
            headers: {
                'content-type': 'application/json',
                'x-hasura-admin-secret': configuration.ACCESS_KEY,
            },
            url: 'https://myapp.herokuapp.com/v1/graphql',
            body: JSON.stringify({
                query: mutation,
                variables: { userId, name, email, avatar },
            }),
        }


text:
Q: Finding indexes of even numbers in a list I want to find the indexes of the even numbers in this list.
messy = [5, 2, 8, 1, 3]
y = [x for x in messy if x%2==0]
f = y[0]
g = y[1]
print(f, g)
>>> 2 8
z = messy.index(f)
zz = messy.index(g)
print(z)
>>> 1

print(y) outputs [2, 8] and that isn't in the list, and that's why I can't messy.index(y)
I'm a bit confused here. Any help?

A: The .index method will fail when there are 2 or more of the same value elements in your list. Instead, you can simplify by enumerating your list and using the indices as follows
even_indices = [i for i, elem in enumerate(messy)
                  if elem % 2 == 0]

A: Another way is to use a lambda:
>>> messy = [5, 2, 8, 1, 3]
>>> filter(lambda i: i%2==0, messy)
[2, 8]

The above will give you the even numbers. Now if you want to get the indexes of those even numbers, two ways to do this are the following:
Using a list comprehension like so:
>>> [k[0] for k in filter(lambda (i,j): j%2==0, enumerate(messy))]
[1, 2]

or using map combined with filter:
>>> from operator import itemgetter
>>> map(itemgetter(0), filter(lambda (i,j): j%2==0, enumerate(messy)))
[1, 2]

A: You can use functional approach using filter function and lambda expression:
For python 2.x:
filter(lambda a:a%2==0, messy)

For python 3.x:
list(filter(lambda a:a%2==0, messy))

A: You can use a list-comprehension with enumerate to get the indexes of the even elements:
>>> [i for i, e in enumerate(messy) if not e & 1]
[1, 2]

the & 1 here is masking the last bit of each number in the list which represents if it is odd (1) or even (0), we can then just use Python's not to flip this and get the desired result

A: If you use numpy, you can use np.where:
>>> import numpy as np
>>> messy = np.array([5, 2, 8, 1, 3])
>>> np.where(messy % 2 == 0)
(array([1, 2]),)


text:
Q: Why do shell script comparisons often use x$VAR = xyes? I see this often in the build scripts of projects that use autotools (autoconf, automake).  When somebody wants to check the value of a shell variable, they frequently use this idiom:
if test "x$SHELL_VAR" = "xyes"; then
...

What is the advantage to this over simply checking the value like this:
if test $SHELL_VAR = "yes"; then
...

I figure there must be some reason that I see this so often, but I can't figure out what it is.

A: I recommend instead:
if test "yes" = "$SHELL_VAR"; then

since it does away with the ugly x, and still solves the problem mentioned by https://stackoverflow.com/a/174288/895245 that $SHELL_VAR may start with - and be read as an option.

A: The other reason that no-one else has yet mentioned is in relation to option processing.  If you write:
if [ "$1" = "abc" ]; then ...

and $1 has the value '-n', the syntax of the test command is ambiguous; it is not clear what you were testing.  The 'x' at the front prevents a leading dash from causing trouble.
You have to be looking at really ancient shells to find one where the test command does not have support for -n or -z; the Version 7 (1978) test command included them.  It isn't quite irrelevant - some  Version 6 UNIX stuff escaped into BSD, but these days, you'd be extremely hard pressed to find anything that ancient in current use.
Not using double quotes around values is dangerous, as a number of other people pointed out.  Indeed, if there's a chance that file names might contain spaces (MacOS X and Windows both encourage that to some extent, and Unix has always supported it, though tools like xargs make it harder), then you should enclose file names in double quotes every time you use them too.  Unless you are in charge of the value (e.g. during option handling, and you set the variable to 'no' at startup and 'yes' when a flag is included in the command line) then it is not safe to use unquoted forms of variables until you've proved them safe -- and you may as well do it all the time for many purposes.  Or document that your scripts will fail horribly if users attempt to process files with blanks in the names.  (And there are other characters to worry about too -- backticks could be rather nasty too, for instance.)

A: I believe its due to
SHELLVAR=$(true)
if test $SHELLVAR  = "yes" ; then echo "yep" ; fi

# bash: test: =: unary operator expected

as well as
if test $UNDEFINEDED = "yes" ; then echo "yep" ; fi
# bash: test: =: unary operator expected

and
SHELLVAR=" hello"
if test $SHELLVAR = "hello" ; then echo "yep" ; fi
# yep

however, this should usually work
SHELLVAR=" hello"
if test "$SHELLVAR" = "hello" ; then echo "yep" ; fi
#<no output>

but when it complains in output somewhere else, its hard to tell what its complaining about I guess, so
SHELLVAR=" hello"
if test "x$SHELLVAR" = "xhello" ; then echo "yep" ; fi

works just as well, but would be easier to debug.

A: There's two reasons that I know of for this convention:
http://tldp.org/LDP/abs/html/comparison-ops.html

In a compound test, even quoting the string variable might not suffice.
  [ -n "$string" -o "$a" = "$b" ]  may cause an error with some versions of
  Bash if $string is empty. The safe way is to append an extra character to
  possibly empty variables, [ "x$string" != x -o "x$a" = "x$b" ] (the "x's" cancel out).

Second, in other shells than Bash, especially older ones, the test conditions like '-z' to test for an empty variable did not exist, so while this:
if [ -z "$SOME_VAR" ]; then
  echo "this variable is not defined"
fi

will work fine in BASH, if you're aiming for portability across various UNIX environments where you can't be sure that the default shell will be Bash and whether it supports the -z test condition, it's safer to use the form if [ "x$SOME_VAR" = "x" ]  since that will always have the intended effect. Essentially this is an old shell scripting trick for finding an empty variable, and it's still used today for backwards compatibility despite there being cleaner methods available.

A: If you're using a shell that does simple substitution and the SHELL_VAR variable does not exist (or is blank), then you need to watch out for the edge cases. The following translations will happen:
if test $SHELL_VAR = yes; then        -->  if test = yes; then
if test x$SHELL_VAR = xyes; then      -->  if test x = xyes; then

The first of these will generate an error since the fist argument to test has gone missing. The second does not have that problem.
Your case translates as follows:
if test "x$SHELL_VAR" = "xyes"; then  -->  if test "x" = "xyes"; then

The x, at least for POSIX-compliant shells, is actually redundant since the quotes ensue that both an empty argument and one containing spaces are interpreted as a single object.

A: I used to do that in DOS when the SHELL_VAR might be undefined.

A: If you don't do the "x$SHELL_VAR" thing, then if $SHELL_VAR is undefined, you get an error about "=" not being a monadic operator or something like that.


text:
Q: Unable to send english text using gsm modem with AT commands I tried to send a text "alert" but it became "5w", sent out other kind of messages and they all end up being some weird characters like =ìteèNñq¥tΔ6M#ΦReÅZ¡Δf¿£AfåP3TÅbVÉè /&pøo3Λ+XKw6
ΣPΨΓ8FwΘBΩ. I am not sure what i did wrongly can anybody help me with this problem?
Public Sub New(ByRef COMMPORT As String)
        'initialize all values
        SMSPort = New SerialPort
        With SMSPort
            .PortName = COMMPORT
            .BaudRate = 115200
            .Parity = Parity.None
            .DataBits = 8
            .StopBits = StopBits.One
            .Handshake = Handshake.RequestToSend
            .DtrEnable = True
            .RtsEnable = True
            .NewLine = vbCrLf
        End With
    End Sub
    Public Function SendSMS() As Boolean
        If SMSPort.IsOpen = True Then
            'sending AT commands
            SMSPort.WriteLine("AT")
            SMSPort.WriteLine("AT+CMGF=1" & vbCrLf) 'set command message format to text mode(1)
            SMSPort.WriteLine("AT+CMGS= " & Chr(34) + phonenumber + Chr(34) & vbCrLf)
            _ContSMS = False
            SMSPort.WriteLine("alert" & vbCrLf & Chr(26)) 'SMS sending

            SMSPort.Close()
        End If
    End Function

    Public Sub Open()
        If Not (SMSPort.IsOpen = True) Then
            SMSPort.Open()
        End If
    End Sub

    Public Sub Close()
        If SMSPort.IsOpen = True Then
            SMSPort.Close()
        End If
    End Sub


text:
Q: d3.js ticks function giving more elements than needed I have this simple linear scale:
var x = d3.scale.linear().domain([0, 250]);

x.ticks(6), as expected, returns:
[0, 50, 100, 150, 200, 250]

However, x.ticks(11) returns:
[0, 20, 40, 60, 80, 100, 120, 140, 160, 180, 200, 220, 240]

When what I want is:
[0, 25, 50, 75, 100, 125, 150, 175, 200, 225, 250]

How do I fix this?

A: I had a similar issue with ordinal scales, I simply wrote some code to pick evenly spaced intervals in my data.  Since I wanted it to always choose the first and last data element on the axis, I calculate the middle part only.  Since some things do not divide evenly, rather than having the residual in one or two bins, I spread it out across the bins as I go; until there is no more residual.
There is probably a simpler way to accomplish this but here's what I did:
function getTickValues(data, numValues, accessor)
{
  var interval, residual, tickIndices, last, i;

  if (numValues <= 0)
  {
    tickIndices = [];
  }
  else if (numValues == 1)
  {
    tickIndices = [ Math.floor(numValues/2) ];
  }
  else
  {
    // We have at least 2 ticks to display.
    // Calculate the rough interval between ticks.
    interval = Math.floor(data.length / (numValues-1));

    // If it's not perfect, record it in the residual.
    residual = Math.floor(data.length % (numValues-1));

    // Always label our first datapoint.
    tickIndices = [0];

    // Set stop point on the interior ticks.
    last = data.length-interval;

    // Figure out the interior ticks, gently drift to accommodate
    // the residual.
    for (i=interval; i<last; i+=interval)
    {
      if (residual > 0)
      {
        i += 1;
        residual -= 1;
      }
      tickIndices.push(i);
    }
    // Always graph the last tick.
    tickIndices.push(data.length-1);
  }

  if (accessor)
  {
    return tickIndices.map(function(d) { return accessor(d); });
  }
  return tickIndices.map(function(i) { return data[i]; });
}

You call the function via:
getTickvalues(yourData, numValues, [optionalAccessor]);

Where yourData is your array of data, numvalues is the number of ticks you want.  If your array contains a complex datastructure then the optional accessor comes in handy.
Lastly, you then feed this into your axis.  Instead of ticks(numTicks) which is only a hint to d3 apparently, you call tickValues() instead.
I learned the hard way that your tickValues have to match your data exactly for ordinal scales.  This may or may not be as helpful for linear scales, but I thought I'd share it anyways.
Hope this helps.

*

*Pat

A: You can fix this by replacing the x.ticks(11) with your desired array.
So if your code looks like this and x is your linear scale:
chart.selectAll("line")
    .data(x.ticks(11))
    .enter()
    .append("line")
    .attr("x1", x)
    .attr("x2", x)
    .attr("y1", 0)
    .attr("y2",120)
    .style("stroke", "#CCC");

You can replace x.ticks(11) with your array:
var desiredArray = [0, 25, 50, 75, 100, 125, 150, 175, 200, 225, 250]
chart.selectAll("line")
    .data(desiredArray)
    .enter()
    .append("line")
    .attr("x1", x)
    .attr("x2", x)
    .attr("y1", 0)
    .attr("y2",120)
    .style("stroke", "#CCC");

The linear scale will automatically place your desired axes based on your input. The reason why the ticks() isn't giving you your desired separation is because d3 just treats ticks() as a suggestion.

A:   axis.tickvalues((function(last, values) {
    var myArray = [0];
    for(var i = 1; i < values; i++) {
      myArray.push(last*i/(values-1))
    }
    return myArray;
  })(250, 11));

This should give you an evenly spaced out array for specifying the number of tick values you want in a particular range.


text:
Q: Error 400 when using Jira REST API from Oracle APEX I'm trying to create an issue in Jira through REST API from Oracle APEX, but I'm always getting only Error 400 in response. By the way, everything is fine when I read issues with GET method, by both POST and PUT cause error.
I used quite a simple piece of code:
DECLARE
req utl_http.req;
res utl_http.resp;
url varchar2(4000) := 'http://host:port/rest/api/latest/issue/';
buffer varchar2(4000);
content varchar2(4000) :=
'{
"fields": {
"project":
{
"id": "10000"
},
"summary": "Auto generated",
"description": "Creating of an issue using the REST API",
"issuetype": {
"id": "3"
}
}
}';

begin

-- Make request
req := utl_http.begin_request(url, 'POST');
utl_http.set_header(req, 'Authorization', 'Basic bG9naW46cGFzc3dvcmQ=');
utl_http.set_header(req, 'Content-Type', 'application/json');
utl_http.write_text(req, content);

-- Get response
res := utl_http.get_response(req);
utl_http.read_text(res, buffer);

Response from server contains only res.status_code = 400 and res.reason_phrase = null. I've studied quite a lot of materials, but none of them could resolve my problem.

A: 400 means Bad Request and JIRA generally outputs really informational error messages as to why it failed. Capture the actual body of the response instead of just the status code and/or reason and see what it says.

A: Well, I finally figured out, what was the problem. Despite of using HTP/1.1 protocol version (by default), it is still mandatory to specify Content-Length header (measured in bytes).


text:
Q: Accessing model that has the same name as a local variable I'm really confused because i have the following case:
Class Game extends CI_Model{
  $this->load->model('user');
  public $user = 'foo';

  $var = $this->user; // Model Or Local Variable?
}

How can i tell which one should it use, the Model User or the local public variable $user?

A: $this->user is not the same as $user
The model you loaded with $this->load->model('user'); is only accessable through the $this variable. Furthermore, you should only acccess it through the variable scope which the model already is placed in (makes more sense, if you will).
Local method variables, as you're trying to do with $var = $this->user;, is only accessable through a method.
So, correcting your code, it would look something like this:
Class Game extends CI_Model{

    public function get_player() {
      $this->load->model('user'); // Load the User model

      $user = 'foo'; // Variable with the string value 'foo'.

      $var = $this->user;
      // $var is a copy of the model you loaded before
      // which means using:
      $name = $this->user->get_username();
      // is the same as
      $name = $var->get_username();

      retun $name;

    }
}

A: Simple and fast solution :

    If you would like your model assigned to a different object name you can specify it via the second parameter of the loading function:

    $this->load->model('Model_name', 'fubar');

    $this->fubar->function();


text:
Q: disable inherited transition (all) for only one css property I have in my CSS file the following code, which globally turns on transitions on all links for all CSS properties on anchor elements:
a{
    display:block;
    -webkit-transition: all 0.2s ease;
    -moz-transition: all 0.2s ease;
    -o-transition: all 0.2s ease;
    -ms-transition: all 0.2s ease;
    transition: all 0.2s ease;
}

Later in CSS file, I would like to turn off transition on specific links (let's say with class notrans) but only for background-position.
Something like:
a.notrans{
    -webkit-transition: background-position 0;
    -moz-transition: background-position 0;
    -o-transition: background-position 0;
    -ms-transition: background-position 0;
    transition: background-position 0;
}

But this code does not work.
I must turn background-position transition and keep other transitions, so sprite - background image would not move on a.notrans ...

A: You just have to declare new property for transitions, and old inherited ones are gone.
So, i just used this>
a.notrans{
-webkit-transition:color .2s;
-moz-transition:color .2s;
-o-transition:color .2s;
-ms-transition:color .2s;
transition:color .2s;
}

After this, only color transition is working!
Maybe there is better solution ?


text:
Q: Appearing To Reverse Object's Rotation Can it be done, and if so, how does one you explain mathematically the ability to cause a rotating object to appear to change the direction of rotation?  I believe it has something to do with angular momentum.
The thought experiment:
I have a satellite rotating around the earth in geosynchronous orbit.  If the satellite approaches the planet will the earth appear to change its direction of rotation from the perspective of the satellite?  At what point in its distance or angular velocity?
Second thought experiment:
In a similar illusion to the tires of a car in a movie, at what frame rate would a camera need to be filming the earth from a static position in order to have the earth appear to have a rotation from east to west?

A: Assuming your rotating object (e.g. the Earth) is rotating at a steady speed the only way to change it's apparent speed of rotation is if you're rotating around it.
You give the example of a geostationary satellite. This rotates around the Earth at the same angular velocity as the Earth rotates, so the Earth appears to be stationary (hence the name "geostationary"). Any satellite orbiting farther away than the geostationary orbit has an angular velocity lower than the Earth's so it will see the Earth rotate west to east. Any satellite orbiting closer than the geostationary orbit has an angular velocity higher than the Earth's so it will see the Earth rotate east to west.
There is an unrelated effect: if you hover above the North Pole you'll see the Earth rotating anti-clockwise. If you fly over to the South Pole and hover there you'll see the Earth rotate clockwise. Does this count as reversing the rotation?
Finally (and this is a nice question :-) if you film the Earth at a frame rate of one frame per 24 hours it will appear to be stationary because between each frame the Earth rotates round to the same place it was at the last frame. If you increase the frame rate the Earth will appear to rotate east to west (i.e. in reverse) until at one frame every 12 hours each frame shows 180° rotation so you can't tell which way the Earth is rotating. If you increase the frame rate still further the Earth starts rotating west to east (i.e. the normal direction).
The reverse happens if you decrease the frame rate. The Earth will appear to rotate west to east until the frame rate is one every 36 hours at which point the rotation reverses.
These frame rates are far slower than films use, but that's because wagon wheels rotate much faster than the Earth does.
Response to comment
The angular velocity of a satellite in orbit round the Earth is calculated by matching it's acceleration to the gravitational acceleration of the Earth. Suppose the satellite is orbiting at a distance $r$ and an angular velocity $\omega$, then the acceleration towards the Earth is $r\omega^2$. The gravitational acceleration is simply given by Newton's law of gravitation $GM/r^2$ and equating these gives:
$$ r\omega^2 = \frac{GM}{r^2} $$
or:
$$ \omega = \sqrt{\frac{r^3}{GM}} $$
If the angular velocity of the Earth is $\omega_e$ = 2$\pi$/(seconds in a day = 86400), then the apparent angular velocity at a distance $r$ is:
$$ \omega_{apparent} = \sqrt{\frac{r^3}{GM}} - \frac{2\pi}{86400} $$
If you put in the geostationary orbit distance, $4.2164 \times 10^7$m (distance from the centre of the earth not its surface), then you'll get $\omega_{apparent}$ = 0 as you'd expect. Increase $r$ and $\omega_{apparent}$ gets increasingly positive while decrease $r$ and $\omega_{apparent}$ gets increasingly negative. So $\omega_{apparent}$ does indeed change sign at the geostationary orbit.


text:
Q: Vm virtualbox ubuntu, cant run .c file from terminal I have the file example_action.c in example folder.
In terminal I enter
cd example
ls
and it shows example_action.c example.file
I am then trying to run the example_action.c over example.file and output the result.
./example_action example.file result.file
but every variation I try gives a different error.
bash:example_action not found
command not recognised
and so on.
Do I need to install something to make this work?
Thanks for any help.

A: To run a c program file, first compile it using gcc. U should have the gcc installed in your virtual machine. Then compile it by typing "gcc filename.c" in a terminal opened in that folder. It will generate a "a.out" file. Then run the c file by typing "./a.out".
And also you should add the file extension ".c" with your file name every time.
bash:example_action not found

This error is because the filename is example_action.c

A: You are trying to run a C source code file (extension .c). You will need to translate the file into machine language first (speak: compiling), like so:
gcc -o example_action example_action.c

(-o to specify the name of the output file, otherwise gcc will use a.out by default)
Then you can use the produced executable:
./example_action example.file result.file


text:
Q: Create a Container witch shape is like image(see attached image) see below image

I want create a container(or other widget) with custom shape that like same as image.
I don't want create content in that, just shape of that.
This isn't BorderRadius, because those sides is curved.(I want create this sides like that image).
I prefer that implemented without CustomPaint.
Thank you

A: It totally border radius bro just try  The width & height
Align(
        child: Container(
          height: 50,
          width: 100,
          margin: EdgeInsets.only(top: 40, left: 40, right: 40),
          decoration: new BoxDecoration(
            color: Colors.green,
            border: Border.all(color: Colors.black, width: 0.0),
            borderRadius: new BorderRadius.all(Radius.elliptical(100, 50)),
          ),
          child: Text('     '),
        ),
      ),


text:
Q: Dynamically dropping files while reading using lapply I've got the following code to read several files and append them separately to a single list along with the file name
foo <- function(fname){
fread(fname, skip = 5, header = TRUE, sep = " ") %>%
mutate(fn = fname)
}

all <- lapply(files, FUN = foo)

After the file is read, I would like to insert a condition in the function which checks for some properties in the file failing which it drops the file along with the filename.
Not strictly related to reading a table but other files also
Edit:
I also use the following efficient method of doing it from here:
all <- setNames(lapply(files, foo), files)

A: I tried the following fairly simple option using Filter.
I used the condition in the Filter
all <- setNames(lapply(myFiles, function(x) {readLAS(x)}), myFiles)
all <- Filter(function(x) {area(x) >= 640}, all)

Not while running the lapply function but it uses only one extra line of code


text:
Q: php get SOAP header Username and Password from SOAP SERVER I have to create PHP, SOAP API. I need to authenticate SOAP client from SOAP Server.
This is the code of SOAP Client.
 $client = new SoapClient("cust.wsdl",array(
"trace"      => 1,
"exceptions" => 0,
"user" => 'username',
"pass" => 'password'));

$result = $client->getDetails($value1);

I need to capture and validate these username and password from server (SOAP SERVER) side.
This is my SOAP Server Code
class getDb {
//return DATA
}

$server = new SoapServer("cust.wsdl");
$server->setClass("getDb");
$server->handle();

I need to Validate Client's Username and Password from SOAP Server.
Anyone know how to capture SOAP Username and Password ("user" => 'username',
"pass" => 'password') from SOAPSERVER please provide.

A: Auth details can be captured like follows.
    if(($_SERVER['PHP_AUTH_PW']!= $pass || $_SERVER['PHP_AUTH_USER'] != $login)|| !$_SERVER['PHP_AUTH_USER'])
{
    header('WWW-Authenticate: Basic realm="Test auth"');
    header('HTTP/1.0 401 Unauthorized');
    echo 'Auth failed';
    exit;
}

Any output can be generated for header('HTTP/1.0 401 Unauthorized');

A: $client = new SoapClient("cust.wsdl",array(
    "trace"      => 1,
    "exceptions" => 0,
    **"user" => 'username',
    "pass" => 'password'));**

Those 2 items above are generally http auth username and password.  If you need to validate them then you can do so on the apache basic auth level.  If you need to do it at the php level then you will need to write a http auth based session handler that requires security in order to show the resources.  An example of that is here: http://php.net/manual/en/features.http-auth.php  Most developers just use apache basic auth that is tied into LDAP or some other service to handle the auth request and have the soap service just deal with the actual work.

A: I have used below method and got success SOAP PHP authentication response from HTTP Auth method.
My SOAP client statement as look like
$client = new SoapClient("name.wsdl",array(
"trace"      => 1,
"exceptions" => 0,
"login" => 'xxx',
"password" => 'xxx'));

I used this PHP statement for Authenticate PHP Auth header
    if(($_SERVER['PHP_AUTH_PW']!= $pass
 || $_SERVER['PHP_AUTH_USER'] != $login)
 || !$_SERVER['PHP_AUTH_USER'])
    {
        header('WWW-Authenticate: Basic realm="Test auth"');
        header('HTTP/1.0 401 Unauthorized');
        // OR ANY THING
}

A: You can use php input stream to get the raw xml of que request and then extract the header part.


text:
Q: Setting up google test on Xcode 7.2.1 I'm new to Xcode and Google Test and I want to set up the unit testing environment for C++ using Google Test. I'm getting the typical #include "gtest/gtest.h" file not found error, when I'm building my tests module.
Details for google test:
I followed the tutorial here : http://bitrage.de/wp/google-test-with-xcode-6-and-c11/
Also, I followed the steps on this link gtest.h file not found googletest xcode 7.0, but that too didn't solve my problem.
I have added the path to the built gtest.framework to my User Header Paths under the Tests module of the project. I have also added the path to the framework under User Framework paths of Xcode project-> Build Settings under the Tests module.
I have linked the binary with framework under the Build Phases for Tests as well. Also, I found out that the header file was under a folder named Headers inside the framework. But #include "Headers/gtest.h" doesn't work as well.
Thanks in advance.


text:
Q: Следующая запись +1 Есть код:
$result = mysql_query("SELECT * FROM inv where username='".$_SESSION['username']."' ");
while ($inv= mysql_fetch_array($result)){
echo "

i['запись'] = new Array('".$inv['id']."','".$inv['id_img']."','".$inv['kolovo']."',0,'".$inv['title']."',0,'".$inv['about']."',0,6);

";

}

Как сделать чтоб каждая следующая запись было на один больше тоисть:
i['1']
i['2']
i['3']

...
A: function fetch($res){
     while($row=mysql_fetch_assoc($res)) {$data[] = $row;}
     return $data;
}
// Db connection
$data = fetch(mysql_query("SELECT * FROM inv where username='".$_SESSION['username']."' "));

// возможно это и все что вы хотели, но если нет и вы хотели увеличить
// какие либо значения массива -

// array increment
$dataLength = count($data);
for($i=0; $i<$dataLength; ++$i) {
     ++$data[$i]['id']; // например увеличим значение id
}

PS:учите матчасть, с ней у вас явно не лады...


text:
Q: UITextView is not firing up inside a UICollectionViewCell I have a UITextView that's inside a view that belongs to a UICollectionViewCell. Unfortunately when I tap on the UITextView nothing happens. textViewDidBeginEditing is not called at all. All the delegates are setup properly such that the buttons in said view work just fine.
UITextView -> UIView -> UICollectionViewCell
However, when I call becomeFirstResponder to a cell's view's textview, it fires up the keyboard and works just fine. What might cause this problem? Thanks!

A: This is most likely because the UITableViewCell is receiving the touch input and not passing it to the UITextView. You can programmatically call the UITextView inside didSelectItemAtIndexPath.


text:
Q: Newton's Law of Cooling: $\delta Q$ or $\mathrm{d}Q$? In this popular answer, I invoked Newton's Law of Cooling/Heating:
$$\dot{q}=hA\Delta T\tag{1}$$
$$\dot{q}=\frac{\mathrm{d} Q}{\mathrm{d}t}\tag{2}$$
$$\dot{q}=\frac{\delta Q}{\mathrm{d}t}\tag{3}$$
$$\mathrm{d}U=\delta Q-p\mathrm{d}V\tag{4}$$
$$\dot{q}=-mc_p\frac{\mathrm{d}T}{\mathrm{d}t}\tag{5}$$
$$\delta Q= mc_p\mathrm{d} T\tag{6}$$
$$-mc_p\frac{\mathrm{d}T}{\mathrm{d}t}=hA\Delta T\tag{7}$$
$(1)$ leads to $(2)$, $(5)$ and $(7)$ which usually is an ODE with analytical solution.
At some point member '@EricDuminil' weighed in, in the comments, claiming I needed to use $(3)$ because of $(4)$ (First Law of Thermodynamics, no less!) Eric has since scrubbed his comments but did suggest an edit according to $(3)$, which I accepted.
My question is, was Eric right or is this $\delta Q$ lark just pedantry, at least in this specific context?

Edit: Following several useful answers, I've reverted back to $(3)$ in my own text.

A: I suppose what you consider pedantry is ultimately a matter of personal opinion.  I would guess that I tend towards the more pedantic end of PhysSE users, so I'll give my point of view.
To me, the notation $\mathrm dQ$ means "the differential of some function $Q$"; that is, there exists some function $Q$, and $\mathrm dQ$ is a tiny change in its value. When we write the first law as
$$dU = \delta Q - \delta W\qquad (\star)$$ we change the notation because  $Q$ and $W$ are not functions.  If they were, it would imply that it makes sense to talk about the heat or work present in a system, which it of course does not.  Instead, $(\star)$ reads

An infinitesimal change in the internal energy function during some process is equal the heat added to the system during the process minus the work done by the system during the process.

$\delta Q$ is not to be interpreted as "the $\delta$ of some function $Q$"; rather, $\delta Q$ is a primitive symbol in its own right which denotes an infinitesimal bit of heat added to the system.
Now with that being said, one could define a function $q(t)$ which gives e.g. the total heat added to the system since time $t=0$.  $\mathrm dq = \dot q \mathrm dt$ is perfectly well-defined in this case.  Furthermore, when the process in question is "the system is supplied with heat over a time interval $\mathrm dt$," we have that $\delta Q = \dot q \mathrm dt$.
Though it is tempting to write $\delta Q/dt = \dot q$ and then say "ah, well then $Q=q$, let's just use the same symbol for both" or some such thing, I would regard that as an abuse of notation.  Leaving it as $\delta Q = \dot q \mathrm dt$ makes it (more) clear that the tiny bit of heat added to the system ($\delta Q$) is given by the differential of your "cumulative heat function" $q$.

Stepping down off of my soapbox, I would express things as follows.  If $q(t)$ is the total heat added to the system by time $t$, then $\dot q(t)$ is the rate at which heat is being added at time $t$.  Assuming that the system has temperature $T(t)$ and its surroundings have temperature $T_0$ (assumed constant for simplicity), we would have
$$\dot q(t) = P_{in}(t)-hA\big(T(t) - T_0\big)$$
where $P_{in}(t)$ is the power being added at time $t$ (in your linked answer, from the microwave). By definition of the specific heat capacity, the addition of some heat $\delta Q$ causes a corresponding increase in temperature given by
$$\delta Q = mc \mathrm dT$$
Since $\delta Q = \dot q\mathrm dt$, we obtain
$$mcT'(t) = \dot q = P_{in} - hA(T-T_0)$$
which is the ODE to which you refer.

A: Relationships (3) and (4) are true in general since heat and work depend on the path and are therefore treated using inexact differentials.  But in this case for heat you know the path by relationship (1), so you can treat the heat as an exact differential as in relationship (2).

A: The suggestion of using $(3)$ is not pedantry, but it is plainly wrong. And my statement remains true whatever is the status of work and heat, whether exact differentials or not.
The reason is the following. Whatever is the attitude about the expression of the first principle, the differentials appearing there correspond to a linear approximation of the variation of the corresponding function as a function of state variables. This is a different functional dependence as the time dependence. More explicitly, while we cannot write in general.
$$
{\mathrm d} U = {\mathrm d} Q +{\mathrm d} W,
$$
we can write
$$
\frac{{\mathrm d} U}{{\mathrm d} t} = \frac{{\mathrm d} Q}{{\mathrm d} t} + \frac{{\mathrm d} W}{{\mathrm d} t}.
$$
In the first case, a state variable dependence is implied. In the second, it is just required the time dependence of quantities like $Q(t)$ and $W(t)$ which may or may not be exact differentials as a function of the state variables. Said in another way, it is impossible to speak meaningfully about differences of heat or work in general. Still, it is always possible to take differences of time-varying functions between two different times.
Notice that all I wrote above cannot be considered a matter of opinion, but it is sound math. The only side of this problem that could be considered opinion is the way of writing equation $(3)$. I add that, following people who knew quite well thermodynamics, like Max Planck, I prefer to write the first principle as
$$
{\mathrm d} U = q + w
$$
eliminating the need to introduce an ill-defined entity like inexact differentials and make it easier to understand time variations.

A: I'm the original commenter.
Process function vs state function.
My argument is simply that heat is a process function, and not a state function.
A system does not have heat. It does not make sense to talk about variation of heat for a system, so it's for example forbidden to write $\Delta Q$, which would mean $Q_2 -  Q_1$. Sadly, this notation is used many times over the Internet.
What is defined, though, is: "At the end of a process, how much energy has been transferred from one body to another, due to temperature difference?" This is heat, and it's simply written $Q$.
Exact differential vs inexact differential
Writing $dQ$ would basically mean "a very small $\Delta Q$". But $\Delta Q$ isn't defined, so another notation needs to be used. That's why $\delta Q$, an inexact differential can be used instead of $dQ$, which would be an exact differential.
From "Fundamentals of Engineering Thermodynamics":

Note that exact differentials are mathematically well-defined, and come with a number of nice properties, which heat or work do not have.
For example, integrating a state function $U$ over a cycle, $$\oint \mathrm{d} U = 0 \, ,$$
while for a path function $Q$
$$\oint \delta Q \neq 0 \, .$$
If $Q$ and $W$ were state functions, engines would be useless : they would absorb no heat and do no work at all, since $Q$ and $W$ would be reset at each cycle.
$\delta Q$ is basically a "tread lightly" sign, indicating that not every operation is allowed or even defined. It's not a differential, it is just a "small bit of heat transferred to the system".
Your question
As mentioned in J.Murray's excellent answer, it is possible to define a new $q$ function for your specific case, and say that $\delta Q = \dot q \mathrm dt$. It's also mentioned in the "Fundamentals of Engineering Thermodynamics":

As far as I can tell, it's never wrong to write $\delta Q$, but it can be wrong to write $dQ$ (e.g. in $dU = dQ + dW$) so I find it easier to stick to $\delta Q$.
In your specific case, $\dot{Q}$ might be the easiest way to avoid confusion.


text:
Q: react router and setState clashing Is this save? will this.props.history push ignore setState since setState is async?
if (id) {
    this.props.history.push(`/edit/${data.id}`)

  this.setState({
    showMsg: 'saved'
  })
}

or I should do this?
if (id) {
  this.setState({
    showMsg: 'saved'
  }, ()=>this.props.history.push(`/edit/${data.id}`))
}

A: The second parameter of setState method is a callback and it will not accept it as argument.
change this
  if (id) {
      this.setState({
        showMsg: 'saved'
      }, this.props.history.push(`/edit/${data.id}`))
    }

to this
if (id) {
  this.setState({
    showMsg: 'saved'
  },()=> this.props.history.push(`/edit/${data.id}`))
}

Is this save?

Yes when you set a state and once its set; you get through callback. It will push to history after state was set.


text:
Q: Image style drupal Please let me know below code is correct to fetch the image style in drupal
$image = theme(
  'image_style',
  array(
    'path' => 'public://my_example_image.jpg',
    'style_name' => 'my_custom_image_style',
    'alt' => 'Alternate Text',
    'title' => 'Title Text',
  )
);

A: You can fetch image url in specific style with:
https://api.drupal.org/api/drupal/modules!image!image.module/function/image_style_url/7
One parameter is image style name and other is image URI (not the path!). You can manually define image tag content and for href attribute print out value image_style_url() returned.

A: Try this function
 $img_url = $node->field_image['und'][0]['uri'];
 <img src="<?php print image_style_url("thumbnail", $img_url); ?>" />

You can change 'thumbnail' to your image style name,and replace $img_url with your image field machine name.


text:
Q: Multi-language bot using LUIS I'm trying to create a multilanguage bot by detecting the language and selecting the proper set of LUIS keys and strings. My problem is, that my LuisDialog serializes itself and the MakeRoot method is not being called anymore.
My code (roughly):
 public async Task<HttpResponseMessage> Post([FromBody]Activity activity)
 {
    if (activity.Type == ActivityTypes.Message)
    {
        var languageData = DetectLanguage(activity); // here I have the keys, strings etc.

        await Conversation.SendAsync(activity, () => new Dialogs.RootDialog(languageData));
    }
    else
    {
        HandleSystemMessage(activity);
    }
    var response = Request.CreateResponse(HttpStatusCode.OK);
    return response;
}

I've tried with the intermediate dialog, which selects the language and context.Forward everything to the LuisDialog, but I'm struggling with managing that. If this is a good strategy, I can share more code. I'm also considering scoreables.

A: If your need is about switching the language of your LUIS Dialog at its start
You have to make a method to get each LUIS parameter by language and as you know the language with your DetectLanguage, choose the right ones.
Then pass them to your LuisDialog like the following:
public async Task<HttpResponseMessage> Post([FromBody]Activity activity)
{
    if (activity.Type == ActivityTypes.Message)
    {
        var languageData = DetectLanguage(activity); // here I have the keys, strings etc.

        var luisService = new LuisService(new LuisModelAttribute("yourLuisAppIdGivenTheLanguageData", "yourLuisAppKeyGivenTheLanguageData", domain: "yourLuisDomainGivenTheLanguageData"));
        await Conversation.SendAsync(activity, () => new Dialogs.RootDialog(luisService));
    }
    else
    {
        HandleSystemMessage(activity);
    }
    var response = Request.CreateResponse(HttpStatusCode.OK);
    return response;
}

And your RootDialog shoud look like this:
public class RootDialog : LuisDialog<object>
{
    public RootDialog(params ILuisService[] services) : base(services)
    {
    }

If you have a more complex project
We implemented a complex project allowing language switch at any time. Due to this possibility, activity's locale field could not be fully trusted even if you override it on the beginning of its processing.
The strategy is the following:

*

*Detect user's language in MessagesController's Post method, for every incoming message

*Store the user language in bot state (userData) when it's changing

Then:

*

*When displaying a text, get the value in the right language using userData

*When using a language specific tool like LUIS, get the right parameter using userData

You will need an intermediate RootDialog to handle this LUIS language switch, and you have to complete your LuisDialog after every detection (or to check the language before every MessageReceived on your LuisDialog).


text:
Q: How to embed extra information in a View in android? I am beginning android development and in my sample application I have a ListView which I populate as follows:
ListView listView = (ListView) findViewById(R.id.listView1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, getEntityLabels());
listView.setAdapter(adapter);

The getEntityLabels() is a function that returns a list of strings.
In the underlying model, the labels are not unique. Instead each entity has an id field which is unique for every entity.
class Entity{
  int id;
  String label;
}

When the user clicks on an item in the ListView, I would like to do some processing. So, I added an ItemClickListener as follows:
listView.setOnItemClickListener(new OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
{
      //I would like to get the Id of the Entity, not just the label
}});

The processing depends on the id of the entity. However, as the view in the list is just a text and contains only the label, I cannot access it.
Is there a way to embed some information like id(in my case) with the views or an alternate way to get the ids?
I am aware of the way where I can override the toString() method of Entity to return label and use ArrayAdapter<Entity> instead of ArrayAdapter<String>. However, I am not looking for this. I am looking for a more generic way where I can embed any information with any View, if possible!

A: You can use tags and assign tag to each view set in your adapter. Then you can read your tag from clicked view in OnClickListener and proceed. As tag can be anything (Object) you like that should solve your problem. See setTag() and related.


text:
Q: Android: Cannot execute more than one Internet process at the same time I am developing an Android application, but I have problem. When I execute a process from Internet via async task, I cannot run another Internet process from different thread at the same time. The other process does not start until first one ends. Async tasks start, but http requests wait for the other one.
How can I handle this problem?
Thanks

A: You are probably using execute() to run your AsyncTask. Quoting the AsyncTask JavaDocs:

When first introduced, AsyncTasks were executed serially on a single background thread. Starting with DONUT, this was changed to a pool of threads allowing multiple tasks to operate in parallel. Starting with HONEYCOMB, tasks are executed on a single thread to avoid common application errors caused by parallel execution.
If you truly want parallel execution, you can invoke executeOnExecutor(java.util.concurrent.Executor, Object[]) with THREAD_POOL_EXECUTOR.

Or, use an HTTP library that offers asynchronous operation as part of the library itself, like OkHttp.


text:
Q: Spring Boot Non Unique Result Exception Hello everyone I am using SpringBoot with Mysql . I have this error when i   try to show information
I have below code in my controller :
query did not return a unique result: 2; nested exception is javax.persistence.NonUniqueResultException: query did not return a unique result: 2
org.springframework.dao.IncorrectResultSizeDataAccessException: query did not return a unique result: 2; nested exception is javax.persistence.NonUniqueResultException: query did not return a unique result: 2

Code
 @GetMapping("showdeveforma/{id}")
 public String ShowDeveFormation(Model m , @PathVariable Long id)

 {
     Formation frm = frmreop.findById(id).get();

     m.addAttribute("avis", srv.findByforma(frm));

     return"ChefProjetAffichageAffectationDeveForma";
 }

A: Your DAO method returns more than one row but you have a single value as the result type defined and not a Collection.

A: Your repository's return type is a single value: srv.findByforma(frm).
The query returns more then one results. You can use a collection if it is the expected behaviour or you need to investigate why more than one entity exists to the given Formation.
(Check your entity relationships)

A: I retry this but i can't resolve information Controller :
 @GetMapping("showdeveforma/{id}")
 public String ShowDeveFormation(Model m , @PathVariable Long id)

 {
    //Formation frm = frmreop.findById(id).get();

    // m.addAttribute("avis", srv.findByforma(frm));
    m.addAttribute("ide", id);
    m.addAttribute("avis" , srv.getAvisFormation());
    return"ChefProjetAffichageAffectationDeveForma";
 }

and my page html is :

 Titre Formation

 Description Formation
 Adresse Formation
 Formateur
Telephone Foramteur
 Nom Devellopeur
 Prenom Devellopeur
 Telephone Devellopeur
 Emain Devellopeur

A: As Simon Martinelli mentioned DAO method "findBy..." returns more than one row, if you need only one row you should use "findFirst...".


text:
Q: Can Google App Engine Java support TLS>1.0 We have a Java app on Google App Engine. We use Google's custom domains and SSL support. A recent security audit has found two issues that we need to resolve relating to the SSL configuration:
1) The server-side SSL/TLS endpoint is configured to allow weak SSL/TLS cipher suites. Specifically: block ciphers having block size of 112 bits - DES, 3DES and Cipher suites that use block ciphers (e.g. AES, 3DES) in CBC mode.
2) The server-side SSL/TLS endpoint is configured to allow connections using TLS protocol version 1.0 ("TLSv1.0"), which contains known weaknesses
Looking at the App Engine docs, I believe both of these are outside the scope of control we have over the App Engine environment. So we cannot change them unless we put a different loadbalancer or SSL termination point in front of App Engine (Maybe CloudFlare, or our own custom instance for example)
My question is, is there any way to control the SSL and TLS settings in App Engine, and if not, is the best alternative to put CloudFlare (or other proxy) in front of it?
Or, if there is a reasonable defence/explanation of these security weaknesses from Google, I could use that to defend the current configuration Google has for App Engine apps.

A: I heard back from two incredibly helpful GCE engineers, the gist of it is:
"the settings are shared with the servers serving most Google services, balancing client compatibility with modern best practices"
"[App Engine] runs our standard GFE configuration"
"While we deprecate what we can, we have to balance that with compatibility. Modern browsers do not allow the configuration of a TLS connection to be downgraded and so supporting older protocols like TLS 1.0 doesn't affect them."
So basically, it's good enough for Google, and their security teams are making those security choices based on a number of factors - as they see fit they will deprecate the older versions.


text:
Q: How to manipulate Date object How can I increase by day a date object? being careful of the month.

A: Depends on what you mean by "increase by a day".  If you mean "increase by exactly 24 hours", then:
new Date(date.getTime() + 24*60*60*1000);

If you want to correct for the fact that not all days are 24 hours (daylight savings switchover days, for example), see the other answers.

A: That's a job for the Calendar class.
Basically
Calendar cal = Calendar.getInstance();
cal.setTime(myDate);
cal.add(Calendar.DATE, 1);
myDaye = cal.getTime();

If you're serious about Date/Time manipulation, check out Joda-Time

A: This is terribly difficult and that's why we should use Calendar for that. Otherwise you'll have to handle the different month lengths and leap years. The Calendar implementation can do that already.


text:
Q: Segurança Autenticação Token Django Rest Framework Bom pessoal eu estou usando o DRF(sou novato rs), para montar uma pequena API. O problema vem na autenticação... pensando em expandir futuramente minha API para usar em um app mobile, eu já venho querendo utilizar o token authentication. Ta tudo funcionando as mil maravilhas porém eu não sei onde salvar o token em uma aplicação web. Salvar o token em um cookie não me parece nada seguro :/ Queria saber qual a melhor forma de salvar o token em uma aplicação web. Seria melhor criar uma api para mobile(token) e outra para web(sessão e cookie) ? Agradeço desde já :D

A: Sugiro usar SessionAuthetication para versão web e TokenAuthentication para versão mobile, já que é possível usar mais de um esquema de autenticação devido à forma como a autenticação é determinada. O próprio DRF usa SessionAuthentication em sua BrowsableApi, aqui ele adiciona as rest_framework.urls que apontam para as views de login e logout do Django.


text:
Q: How to reference a variable in previous function? I am trying to call back the "numberofDays" in the second function, which is an user input while executing the first function. Is there a way to achieve this? Right now it shows 'number of Days is not defined'.
Or should I just combine them into one function?
Thanks!
def chooseStockandDays():
    stk = input("Please enter the stock symbol:")
    numberofDays = input("please enter the number of days for the analysis:")
    return generateReport(stk)

def generateReport(stk):
    dt = datetime.date.today()
    dtPast = dt + datetime.timedelta(days=numberofDays)
    print(dt)
    print(dtPast)

A: Pass it as an additional parameter like this:
def chooseStockandDays():
    stk = input("Please enter the stock symbol:")
    numberofDays = input("please enter the number of days for the analysis:")
    return generateReport(stk, numberofDays)

def generateReport(stk, numberofDays):
    dt = datetime.date.today()
    dtPast = dt + datetime.timedelta(days=numberofDays)
    print(dt)
    print(dtPast)

A: You have to pass the numberofDays variable as an additional parameter
def chooseStockandDays():
    stk = input("Please enter the stock symbol:")
    numberofDays = input("please enter the number of days for the analysis:")
    return generateReport(stk,numberofDays)

def generateReport(stk,numberofDays):
    dt = datetime.date.today()
    dtPast = dt + datetime.timedelta(days=numberofDays)
    print(dt)
    print(dtPast)


text:
Q: Java date comparator issue I'm having issues sorting out my comparator by dates. The date format should be in "dd/MM/yyyy" So I call in my information from an SQL Database and then convert strings to date by doing this:
  public void setDeadlineDate(String deadDate) throws ParseException {
        this.d_date = deadDate;
        //convert strings to dates
        formatter = new SimpleDateFormat("dd/MM/yyyy");
        convertedDeadlineDate = (Date)formatter.parse(deadDate);
    }

I then make a get method below to call for my comparator. I have to examples but there is always a discrepancy in regards to an odd date being out of place and the comparing not being right.
Example 1:
  @Override
    public int compare(JobRequest j1, JobRequest j2) {

        if (j1.getConvertedDeadlineDate().before(j2.getConvertedDeadlineDate())) {
            return -1;
        } else if (j1.getConvertedDeadlineDate().after(j2.getConvertedDeadlineDate())) {
            return 1;
        }
        else {
            return 0;
        }
    }

Example 2:
public int compare(JobRequest j1, JobRequest j2){
return j1.getConvertedDeadlineDate().compareTo(j2.getConvertedDeadlineDate());
}

both these examples give me issues and my priorityqueue deadlinedate not to be in the correct order as I would like.
in my db they are saved as a varchar in the following format "01/12/2012" , 1st december 2012 as it wouldnt let me use their date function to have it in the english format.
is their a better way for me to convert strings and then compare or am i missing something?
thanks
EDIT:
output getting for ordered dates:

*

*05/04/2011

*16/12/2012

*18/06/2012

*17/12/2013

*17/12/2013

*16/12/2013

*17/12/2013

*14/08/2012

*19/12/2013

Where I declare PriortyQueue:
private Comparator<JobRequest> comparator = new JobQueueComparator(); //calls my comparator
    private PriorityQueue< JobRequest> scheduledJobs = new PriorityQueue<JobRequest>(100, comparator);

    public void addJob(JobRequest job) {
        // now add job to priority queue
        scheduledJobs.add(job); // add jobs from the resultset into queue
    }

scheduledJobs.add(job) just populates the queue from a resultset and keeps adding to queue until all fields in database have been read, see below
public void populateQueueFromDB() {
        // create priority queue
        try {
            String url = "jdbc:mysql://localhost:3306/project";
            Connection conn = DriverManager.getConnection(url, "root", "nbuser");

            PreparedStatement stmt = conn.prepareStatement("SELECT user_id,s_date,e_date,d_date,department,projectname,projectapplication,priority,cores,disk_space,analysis FROM booking");
            ResultSet rs;
            rs = stmt.executeQuery();

            //List<JobRequest> jobList = new ArrayList<JobRequest>();

            while (rs.next()) {
                JobRequest job = new JobRequest();
                User user = new User();
                user.setUserID(rs.getString("user_id"));
                job.setUserID(user.getUserID()); // changes the /user id to the job.setuser id so can call for my queue print.
                job.setStartDate(rs.getString("s_date"));
                job.setEndDate(rs.getString("e_date"));
                job.setDeadlineDate(rs.getString("d_date"));
                job.setDepartment(rs.getString("department"));
                job.setProjectName(rs.getString("projectname"));
                job.setProjectApplication(rs.getString("projectapplication"));
                job.setPriority(rs.getInt("priority"));
                job.setCores(rs.getInt("cores"));
                job.setDiskSpace(rs.getInt("disk_space"));
                job.setAnalysis(rs.getString("analysis"));

                schedulerPriorityQueue.addJob( job );

            }
            schedulerPriorityQueue.printQueue();

            conn.close();

        } catch (Exception e) {
            System.err.println("Got an exception! ");
            System.err.println(e.getMessage());
        }

    }

}

PRINT QUEUE:
public void printQueue() {
        for (JobRequest jr : scheduledJobs) {

            System.out.print(jr.getUserID() + "-->");
            System.out.print(jr.getStartDate() + "--START-->");
            System.out.print(jr.getEndDate() + "---END-->");
            System.out.print(jr.getDeadDate() + "--DROP-->");
            System.out.print(jr.getDepartment() + "-->");
            System.out.print(jr.getProjectName() + "-->");
            System.out.print(jr.getProjectApplication() + "-->");
            System.out.print(jr.getPriority() + "--PRIORITY-->");
            System.out.print(jr.getCores() + "-->");
            System.out.print(jr.getDiskSpace() + "-->");
            System.out.println(jr.getAnaylsis());

        }
    }

A: when you do: for (JobRequest jr : scheduledJobs) { ... you're actually using an implicit Iterator, which doesn't guarantee that the items will be returned in order of Priority (defined by your comparator).
Like mentioned above, the documentation states that:

This class and its iterator implement all of the optional methods of
  the Collection and Iterator interfaces. The Iterator provided in
  method iterator() is not guaranteed to traverse the elements of the
  priority queue in any particular order. If you need ordered traversal,
  consider using Arrays.sort(pq.toArray()).

Meaning that the order of the jobs in queue and the order of the iterator isn't necessarily the same.
If you just need to list the jobs, use the Arrays.sort approach mentioned in the docs.
If you want to make sure that your PriorityQueue is working, you'll have to use it as one, doing something like:
while(!scheduledJobs.isEmpty()) {
     ... = scheduledJobs.poll();
     //print, do whatever
}

Keep in mind that this removes the elements from the Queue, and should only be used for testing purposes, or to actually handle the jobs as you need. But this should show you the dates in the actual Priority order.
It seems to me that there's some confusion on how the PriorityQueue should be used. I would say that the regular use case would be something like:

*

*Add elements to the queue

*Define a method to handle the "jobs" (each element), in the queue

*While the queue isn't empty, get each element using poll (returns the smallest), and do whatever you need to do with it.

A: The documentation of PriorityQueue says that

The Iterator provided in method iterator() is not guaranteed to
  traverse the elements of the priority queue in any particular order.
  If you need ordered traversal, consider using
  Arrays.sort(pq.toArray())

.
http://docs.oracle.com/javase/6/docs/api/java/util/PriorityQueue.html

A: This works perfectly for me:
public class JobRequest implements Comparable<JobRequest> {

    static final DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
    Date convertedDeadlineDate;

    Date getConvertedDeadlineDate() {
        return convertedDeadlineDate;
    }

    public JobRequest(String deadDate) {
        try {
            convertedDeadlineDate = (Date) formatter.parse(deadDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    @Override
    public int compareTo(JobRequest j) {
        return this.getConvertedDeadlineDate().compareTo(
                j.getConvertedDeadlineDate());
    }

    public static void main(String[] args) {
        List<JobRequest> list = new ArrayList<>();
        list.add(new JobRequest("10/10/2010"));
        list.add(new JobRequest("09/09/2009"));
        list.add(new JobRequest("11/11/2011"));
        list.add(new JobRequest("08/08/2008"));

        Collections.sort(list);

        for (JobRequest j : list) {
            System.out.println(formatter.format(j.getConvertedDeadlineDate()));
        }
    }

}

Which results in the output:
08/08/2008
09/09/2009
10/10/2010
11/11/2011


text:
Q: How can I append, or not, when writing to a file, based on a flag? I know this won't work, but it should make clear what I want to do:
if (append) {
   std::ofstream f(fname, std::ios::app);
} else {
   std::ofstream f(fname);
}
f << stuff;
//etc;
f.close()

How can I do this?

A: One option, especially if there is additional logic in the if/else, is to use open:
std::ofstream f;
if (append) {
   f.open(fname, std::ios::app);
} else {
   f.open(fname);
}
f << stuff;
//etc;
f.close()

A: std::ofstream f(fname, append ? std::ios::app : std::ios::out);

will do it.
Reference https://en.cppreference.com/w/cpp/io/basic_ofstream/open


text:
Q: How to pass complex type using json to ASP.NET MVC controller I have a View that allows a user to enter/edit data for a new Widget.  I'd like to form up that data into a json object and send it to my controller via AJAX so I can do the validation on the server without a postback.
I've got it all working, except I can't figure out how to pass the data so my controller method can accept a complex Widget type instead of individual parameters for each property.
So, if this is my object:
public class Widget
{
   public int Id { get; set; }
   public string Name { get; set; }
   public decimal Price { get; set; }
}

I'd like my controller method to look something like this:
public JsonResult Save(Widget widget)
{
   ...
}

Currently, my jQuery looks like this:
var formData = $("#Form1").serializeArray();

$.post("/Widget/Save",
   formData,
   function(result){}, "json");

My form (Form1) has an input field for each property on the Widget (Id, Name, Price).  This works great, but it ultimately passes each property of the Widget as a separate parameter to my controller method.
Is there a way I could "intercept" the data, maybe using an ActionFilterAttribute, and deserialize it to a Widget object before my controller method gets called?

A: Note that (in MrDustpan's solution) the parameter name widget in the MVC Action method must match with the prefix used in the name attribute in the ASPX file.
If this is not the case then the Action method will always receive a null object.
<input type="text" name="widget.Text" value="Hello" /> - OK
<input type="text" name="mywidget.Text" value="Hello" /> - FAILS

A: Phil Haack has a good blog post about model binding that might be helpful.  Not 100% what you're talking about here, but I think it might give you a better overall understand about the DefaultModelBinder.

A: Thanks Jeff, that got me on the right path.  The DefaultModelBinder is smart enough to do all the magic for me...my problem was in my Widget type.  In my haste, my type was defined as:
public class Widget
{
   public int Id;
   public string Name;
   public decimal Price;
}

Notice that the type has public fields instead of public properties.  Once I changed those to properties, it worked.  Here's the final source code that works correctly:
Widget.aspx:
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" AutoEventWireup="true" CodeBehind="Widget.aspx.cs" Inherits="MvcAjaxApp2.Views.Home.Widget" %>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
    <script src="../../Scripts/jquery-1.2.6.js" type="text/javascript"></script>
    <script type="text/javascript">
    function SaveWidget()
    {
        var formData = $("#Form1").serializeArray();

        $.post("/Home/SaveWidget",
        formData,
        function(data){
            alert(data.Result);
        }, "json");
    }
    </script>
    <form id="Form1">
        <input type="hidden" name="widget.Id" value="1" />
        <input type="text" name="widget.Name" value="my widget" />
        <input type="text" name="widget.Price" value="5.43" />
        <input type="button" value="Save" onclick="SaveWidget()" />
    </form>
</asp:Content>

HomeController.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;

namespace MvcAjaxApp2.Controllers
{
    [HandleError]
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewData["Title"] = "Home Page";
            ViewData["Message"] = "Welcome to ASP.NET MVC!";
            return View();
        }

        public ActionResult About()
        {
            ViewData["Title"] = "About Page";
            return View();
        }

        public ActionResult Widget()
        {
            ViewData["Title"] = "Widget";
            return View();
        }

        public JsonResult SaveWidget(Widget widget)
        {
            // Save the Widget
            return Json(new { Result = String.Format("Saved widget: '{0}' for ${1}", widget.Name, widget.Price) });
        }
    }
    public class Widget
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public decimal Price { get; set; }
    }
}

A: What you want to do is structure your javascript form object in the same way your backend object is structured:
{ Id : "id", Name : "name", Price : 1.0 }

Then use the toJSON plugin to convert it into the above string. You send this string to your backend and use something like the JayRock libraries to convert it to a new Widget object.


text:
Q: How to see in Xcode using c++ std::vector elements types and values? in visual studio when i used to debug code with c++ std::vector i could see all the elements in it and even drill down to each element , somehow in Xcode 5.1 i can see this option
all i see is the iterators of the vector.
here is what i see in Xcode when i try to watch vector elements :

how can i see the vectors elements in the debug window .

A: For me (Xcode 6.0.1), this happens only with reference (&) types.
Try one of the following:

*

*Add a custom watch expression *&strLineOfChrsVec (dereference the address of the variable).

*Go up the stack and watch the original variable that you've passed to the function.

A: In order to temporarily see the values of a single element in the vector you can right click on it and then select:

Print Description of "[i]"

It will print to the output something like:

Printing description of *([1]): (std::__1::basic_string, std::__1::allocator >) [1] = "Hi"

where "Hi" was the value of the vector at position 1.


text:
Q: How do I disable the variable type hint for a 'var' declared variable in Rider? In Jetbrains Rider the type of a 'var' declared variable is shown as hint by default. I don't want that. How can I get rid of it?

A: Disable Parameter Name Hints as shown below:

A: In JetBrains Rider 2022.2, I found the checkbox Enable Inlay Hints in .NET languages under
Settings --> Editor --> Inlay Hints.

That solved it for me.

A: It is not in Inlay settings but under "Syntax Style".


text:
Q: Is it safe to replace array of XXX with TArray I have quite a few variables declared as
var
  Something: array of XXX;
begin
  SetLength(Something, 10);
  try
    ...
  finally
    SetLength(Something, 0);
  end;
end;

To what extend is safe to have them replaced:
var
  Something: TArray<XXX>;
begin
  SetLength(Something, 10);
  try
    ...
  finally
    SetLength(Something, 0);
  end;
end;

A: It is perfectly safe to do this. The compiler will produce identical output.
I personally would, all other things being equal, recommend doing so. The use of the generic array TArray<T> gives you much more flexibility and better type compatibility.
Of course those benefits can only be seen with more realistic code that does some work. You most typically see benefits when using generic containers. But you might also see benefits when trying to build code using multiple different libraries.
The use of generic arrays allows easy type compatibility. Before generic arrays you would define an array type like this:
TIntArray = array of Integer;

If two libraries do this then you have incompatible types. If the libraries agree to use generic arrays then there will be compatibility.
To see this more clearly, consider this fragment:
type
  TIntArray1 = array of Integer;
  TIntArray2 = array of Integer;
....
var
  arr1: TIntArray1;
  arr2: TIntArray2;
....
arr1 := arr2;

This assignment is not valid and fails with a type mis-match compiler error. This is entirely to be expected within the Pascal language. It is after all strongly typed and these are distinct types. Even if they are implemented identically.
On the other hand:
var
  arr1: TArray<Integer>;
  arr2: TArray<Integer>;
....
arr1 := arr2;

is valid and does compile. The documentation for generic type compatibility says:

Two instantiated generics are considered assignment compatible if the base types are identical (or are aliases to a common type) and the type arguments are identical.

A: As already answered, TArray<XXX> is exactly like any other custom type defined as array of XXX. In fact, TArray<XXX> is a custom type defined as array of XXX.
That said, a custom type defined as array of XXX is not equivalent to array of XXX in the context of a procedure or function parameter. In procedure Foo(x: array of Integer), x is an open array parameter, which can accept any type of integer array. In contrast, procedure Foo(x: TArray<Integer>) takes an actual TArray<Integer> type only. You can see the difference when attempting to pass a fixed-size array, but also when attempting to pass a TDynIntegerArray (a different type, also defined as array of Integer).
So, for variables, sure, if you have array of XXX, change it to TArray<XXX> all you want. Just make sure you don't do a global search and replace.


text:
Q: guava and bonecp in webstart giving security exception I have an APP that is run via java webstart. It is using the BoneCP library which is dependent on the Google guava library. When it starts to down load it fails on the guava jar file. Antiviruses blocks the download giving me the following.Security Exception
Anyone else have this issue?
Thanks for any help!


text:
Q: How is diagonal matrices a subspace of upper triangular matrices? I'm kind of confused that the diagonal matrices is a subspace of the upper triangular matrices. Suppose I have the following matrices:
$$U=\begin{bmatrix}
a & b\\
0 & d
\end{bmatrix}
; \;
D=\begin{bmatrix}
a & 0\\
0 & d
\end{bmatrix}$$
I read in the book that the matrix $D$ is a subspace of $U$. But how's it so? At first, I thought the reason why the diagonal matrices are subspaces of the upper triangular matrices was because the the matrix $D$ is just a case of matrix $U$ with $b=0$ and that's why it is a subspace of it.
But on a second thought, if my assumption was true, then everything, even the identity matrix is a subspace of the upper triangular matrices and the upper triangular matrices would be subspace of any 2 by 2 matrices. This doesn't make sense at all.
So how is this being looked at that $D$ is a subspace of $U$?

A: Generally to check that a given subset is a Subspace of a vector space you should check to things:
a)
The operation $*$ of the vector space $U$ (in your case i assume to be addition between $2\times2$ matrices) is closed in $D$ i.e. it is well define as a bilinear map $$+:D\times D\to D,$$ and this is easy to check.
b)
You have to check that multiplication by scalar elements of the field (usually your matrices are defined over a field, i.e real/complex matrices, or more generally $K$ - matrices where $K$ is a field), is well define as a bilinear map $$\cdot:K\times D \to D.$$
Now you should check that both these two operations are well defined on $D$ as I have described previously.
But then you can onclude that $D$ is a subspace of $U$.
Note that in this case, since you are working with square matrices, you can as well have a product defined in $U$, namely $$*:U\times U\to U,$$ which is the usual product between matrices. Equipped with this operation, $U$ becomes more than a vector space, it becomes an Algebra. The interesting thing is that, if you consider the restriction to the subspace $D$, you obtain another bilinear map $$*:D\times D\to D,$$ and so in this case you can view $D$ as a subalgebra of $U$, not only as a subspace.
Now let's come to your doubts:
The identity matrix is not a subspace: for example what happens if you multiply by a scalar element of the field? you obtain something different from the identity but this contradicts b).
Finally the space of the upper triangular matrices is a subspace of $M_2(K)$, the vector space of the $2\times 2$ matrices over a generic field $K$. But, as i pointed out before, this is more than just a subspace, it is a subalgebra of $M_2(K)$.
Recalling everything.. You have the follwing $$D\leq U\leq M_2(K).$$ Where $\leq$ means "to be a subspace of." In your case this can be read even as "to be a subalgebra of." Hope everything is clearer now.

A: I don't know whether you are dealing with $2\times 2$ matrices or general $n \times $n$ matrices.  The result is true in either case.
It may not be clear to you what these spaces are.  Define addition of matrices by adding corresponding entries. So for example
$$\begin{bmatrix}
1 & 2\\
0 & 3
\end{bmatrix}
+
\begin{bmatrix}
5 & 3\\
0 & 1
\end{bmatrix}
=
\begin{bmatrix}
6 & 5\\
0 & 4
\end{bmatrix}
$$
If $c$ is a constant (a scalar, a number) then you multiply a matrix by $c$ by multiplying each entry by $c$. So for example
$$3\begin{bmatrix}
1 & 2\\
0 & 3
\end{bmatrix}
=
\begin{bmatrix}
3 & 6\\
0 & 9
\end{bmatrix}
$$
A vector space of matrices is a collection $V$ of matrices (of the same size) such that if $A$ and $B$ are matrices in the collection, then so is the sum $A+B$, and also if $c$ is any scalar, then $cA$ is in the collection.
So typically a vector space of matrices will have many matrices in it. The only vector space of matrices that consists of a single matrix is the space whose only element is the all $0$'s matrix.
In particular, the identity matrix by itself ($1$'s down the main diagonal, $0$'s elsewhere) is not a subspace of the collection of $2\times 2$ matrices, for if the identity matrix $I$ is in the subspace, then $cI$ has to be in the subspace for all numbers $c$.  The collection of all matrices which are $0$ off diagonal, and have all diagonal terms equal is a subspace of the space of all matrices.  Maybe that will take care of part of your objection.
Let $V$ be any vector space, and take a collection $U$ of some of the elements of $V$.  Then $U$ is called a subspace of $V$ if $U$ by itself is a vector space, meaning that the sum of any two elements of $U$ is in $U$, and any constant times an element of $U$ is in $U$.
You quoted something to the effect that a certain $D$ is a subspace of the space of upper triangular matrices.  That's not true.  The collection of all matrices of the shape you described, with everything off diagonal equal to $0$, is a subspace.  So $D$ is supposed to be not a single matrix, it is a largish collection of matrices.
Now let's look at your particular problem. Let $V$ be the collection of all upper triangular matrices. Is this a vector space?  Take any two upper triangular matrices $A$ and $B$. Is $A+B$ upper triangular? Yes. If $c$ is a constant, and $A$ is upper triangular, is $cA$ upper triangular? Yes. So $V$ is a vector space.
Let $D$ be the collection of all diagonal matrices? Is this a vector space? Yes, the sum of two diagonal matrices is diagonal, a constant times a diagonal matrix is a diagonal matrix. $D$ is a subspace of the upper triangular matrices, because any diagonal matrix is in particular upper triangular, it is a special upper triangular matrix.


text:
Q: opening google map in a tab in android not working I'm trying to open a google map application I did in a tab but its not working, it keep getting the force close message when I run it. I created the main activity file[TabtestingActivity] which creates the tabs [HelloGoogleActivity class contains the map code and it works fine without tabs]
public class TabstestingActivity extends TabActivity {
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    Resources res = getResources();
    TabHost tabHost = getTabHost();  // The activity TabHost
    TabHost.TabSpec spec;  // Reusable TabSpec for each tab
    Intent intent;  // Reusable Intent for each tab

        intent = new Intent().setClass(this, HelloGoogleActivity.class);

    spec = tabHost.newTabSpec("tabOne");
    spec.setContent(intent);
    spec.setIndicator("Tab One",res.getDrawable(R.drawable.tabselect));
    tabHost.addTab(spec);
        tabHost.setCurrentTab(0);
    }
}

if I create a class which only has a text in it it works fine with tabs but when I add the map class it stops working.
This is my main.xml:
<?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/tabhost"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >

<TabWidget
 android:id="@android:id/tabs"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content" />
<FrameLayout
 android:id="@android:id/tabcontent
 android:layout_width="fill_parent"
 android:layout_height="fill_parent" >

 <RelativeLayout
            xmlns:android="http://schemas.android.com/apk/res/android"
            android:orientation="vertical"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent">

  <com.google.android.maps.MapView
    android:id="@+id/mapview"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:clickable="true"
    android:apiKey="my key"
    android:layout_weight="1"/>
</RelativeLayout>
</FrameLayout>

</LinearLayout>
</TabHost>

is there any problem with my main.xml?
This is the logcat:
10-26 00:47:10.207: ERROR/AndroidRuntime(303): FATAL EXCEPTION: main
10-26 00:47:10.207: ERROR/AndroidRuntime(303): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.tabtest/com.example.tabtest.TabstestingActivity}: android.view.InflateException: Binary XML file line #12: Error inflating class com.google.android.maps.MapView
10-26 00:47:10.207: ERROR/AndroidRuntime(303):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
10-26 00:47:10.207: ERROR/AndroidRuntime(303):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
10-26 00:47:10.207: ERROR/AndroidRuntime(303):     at android.app.ActivityThread.access$2300(ActivityThread.java:125)
10-26 00:47:10.207: ERROR/AndroidRuntime(303):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
10-26 00:47:10.207: ERROR/AndroidRuntime(303):     at android.os.Handler.dispatchMessage(Handler.java:99)
10-26 00:47:10.207: ERROR/AndroidRuntime(303):     at android.os.Looper.loop(Looper.java:123)
10-26 00:47:10.207: ERROR/AndroidRuntime(303):     at android.app.ActivityThread.main(ActivityThread.java:4627)
10-26 00:47:10.207: ERROR/AndroidRuntime(303):     at java.lang.reflect.Method.invokeNative(Native Method)
10-26 00:47:10.207: ERROR/AndroidRuntime(303):     at java.lang.reflect.Method.invoke(Method.java:521)
10-26 00:47:10.207: ERROR/AndroidRuntime(303):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
10-26 00:47:10.207: ERROR/AndroidRuntime(303):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
10-26 00:47:10.207: ERROR/AndroidRuntime(303):     at dalvik.system.NativeStart.main(Native Method)
10-26 00:47:10.207: ERROR/AndroidRuntime(303): Caused by: android.view.InflateException: Binary XML file line #12: Error inflating class com.google.android.maps.MapView
10-26 00:47:10.207: ERROR/AndroidRuntime(303):     at android.view.LayoutInflater.createView(LayoutInflater.java:513)
10-26 00:47:10.207: ERROR/AndroidRuntime(303):     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:565)
10-26 00:47:10.207: ERROR/AndroidRuntime(303):     at android.view.LayoutInflater.rInflate(LayoutInflater.java:618)
10-26 00:47:10.207: ERROR/AndroidRuntime(303):     at android.view.LayoutInflater.rInflate(LayoutInflater.java:621)
10-26 00:47:10.207: ERROR/AndroidRuntime(303):     at android.view.LayoutInflater.inflate(LayoutInflater.java:407)
10-26 00:47:10.207: ERROR/AndroidRuntime(303):     at android.view.LayoutInflater.inflate(LayoutInflater.java:320)
10-26 00:47:10.207: ERROR/AndroidRuntime(303):     at android.view.LayoutInflater.inflate(LayoutInflater.java:276)
10-26 00:47:10.207: ERROR/AndroidRuntime(303):     at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:198)
10-26 00:47:10.207: ERROR/AndroidRuntime(303):     at android.app.Activity.setContentView(Activity.java:1647)
10-26 00:47:10.207: ERROR/AndroidRuntime(303):     at com.example.tabtest.TabstestingActivity.onCreate(TabstestingActivity.java:15)
10-26 00:47:10.207: ERROR/AndroidRuntime(303):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
10-26 00:47:10.207: ERROR/AndroidRuntime(303):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
10-26 00:47:10.207: ERROR/AndroidRuntime(303):     ... 11 more
10-26 00:47:10.207: ERROR/AndroidRuntime(303): Caused by: java.lang.reflect.InvocationTargetException
10-26 00:47:10.207: ERROR/AndroidRuntime(303):     at com.google.android.maps.MapView.<init>(MapView.java:238)
10-26 00:47:10.207: ERROR/AndroidRuntime(303):     at java.lang.reflect.Constructor.constructNative(Native Method)
10-26 00:47:10.207: ERROR/AndroidRuntime(303):     at java.lang.reflect.Constructor.newInstance(Constructor.java:446)
10-26 00:47:10.207: ERROR/AndroidRuntime(303):     at android.view.LayoutInflater.createView(LayoutInflater.java:500)
10-26 00:47:10.207: ERROR/AndroidRuntime(303):     ... 22 more
10-26 00:47:10.207: ERROR/AndroidRuntime(303): Caused by: java.lang.IllegalArgumentException: MapViews can only be created inside instances of MapActivity.
10-26 00:47:10.207: ERROR/AndroidRuntime(303):     at com.google.android.maps.MapView.<init>(MapView.java:282)
10-26 00:47:10.207: ERROR/AndroidRuntime(303):     at com.google.android.maps.MapView.<init>(MapView.java:255)
10-26 00:47:10.207: ERROR/AndroidRuntime(303):     ... 26 more

A: The trace is pretty clear,
"10-26 00:47:10.207: ERROR/AndroidRuntime(303): Caused by: java.lang.IllegalArgumentException: MapViews can only be created inside instances of MapActivity."

You can't use the MapView outside of a MapActivity.


text:
Q: I have this form, and I cant get it it to get validated I have this form and it needs to be validated. For example, no numbers in the name field, and Message part can't be more than 200 characters. I have tried writing JavaScript code but it doesn't just work.

    <form id="quote" >

Get A Quote

        Name

        <input type="text" placeholder="Name">

        Email

        <input type="email" placeholder="Email Address">

        Message

        <textarea placeholder="Message"></textarea>

      <button class="button_1" type="submit">Send</button>
    </form>

I expect for it also to say if a part is not filled but I can't get it to work.

A: You can validate which name accepts only text and spaces you can use this expression /^[a-zA-Z\s]+$/ read about it in this answer https://stackoverflow.com/a/12778207/615274. Validating the message is a little simpler. It is possible to define the maximum number of characters to accept in textarea using maxlength attribute. This possibility can prevent you from writing code. Please look at the following example

const form = document.forms.form;

form.addEventListener('submit', handleSubmit, true);

function handleSubmit(event) {
    event.preventDefault();

    const name = this.name.value;
    const message = this.message.value;

    if (!isValidName(name)) {
        alert('Not valid name!');

        return false;
    }

    if (!isValidMessage(message)) {
        alert('Not valid message!');

        return false;
    }

    this.submit();
}

function isValidName(name) {
    // const expresion = /^[A-Za-z]+$/;
    const expresion = /^[a-zA-Z\s]+$/;

    return expresion.test(name);
}

function isValidMessage(message) {
    if (message.length > 200) {
        return false;
    }

    return true;
}
<form action="#" name="form">

Get A Quote

        Name

        <input type="text" id="name" name="name" placeholder="Name">

        Email

        <input type="email" placeholder="Email Address">

        Message

        <textarea id="message" name="message" minlength="1" maxlength="200" placeholder="Message"></textarea>

    <button class="button_1" type="submit">Send</button>
</form>

A: You can use the pattern attribute for this and on js side use checkValidity() to check if the input is valid or not.

$('#name').on('keyup', (ev) => {
  var isValid = $('#name')[0].checkValidity();
 $('span').html(isValid ? 'yes': 'no');
});

<input type="text" id="name" placeholder="Name" pattern="[a-zA-Z]*">

isValid:

A: The link provided by Andreas is definitely your friend for this issue.
For your specific needs, you want "required", maxlength="200", and (I think) "pattern='^\D+$'".


text:
Q: How to add more than one SQL statement/Query String on 1 DataSource? I currently have the following statement with QueryString set to ProductCategory on my ListView control:
SELECT * FROM Products WHERE (ProductCategory = ?)

I would like to add this statement and query string on the same DataSource to allow query string for ProductModel as well, how can I do that?
SELECT * FROM Products WHERE (ProductModel = ?)

ListVIew
  <asp:ListView runat="server" ID="listView" GroupItemCount="3"
        DataSourceID="AccessDataSource1">
    <LayoutTemplate>

            <asp:PlaceHolder runat="server" ID="groupPlaceHolder" />
        <asp:DataPager runat="server" ID="dpMyDatePager" PageSize="9"
 PagedControlID="listView">
<Fields>
    <asp:NextPreviousPagerField ButtonType="Button" ShowLastPageButton="True"
     ShowFirstPageButton="True" />
     <asp:NumericPagerField />
</Fields>
</asp:DataPager>

    </LayoutTemplate>
    <GroupTemplate>

            <asp:PlaceHolder runat="server" ID="itemPlaceHolder" />

    </GroupTemplate>
    <ItemTemplate>

        <img src='<%# Eval("ProductUrl") %>' >

            <%# Eval("ProductBrand") %>
            <%# Eval("ProductModel") %>

        Our Price: S$<%# Eval("NormalPrice") %>

        Add to cart

    <asp:HyperLink ID="HypViewDetails" style="text-decoration:none"      NavigateUrl='<%#Eval("ProductId", "ProductDetails.aspx?ProductID={0}")%>'
 runat="server">View Details</asp:HyperLink>

</ItemTemplate>
    <ItemSeparatorTemplate>

    </ItemSeparatorTemplate>
    <GroupSeparatorTemplate>

    </GroupSeparatorTemplate>
    <EmptyDataTemplate>
    </EmptyDataTemplate>
</asp:ListView>
    <asp:AccessDataSource ID="AccessDataSource1" runat="server"
        DataFile="~/App_Data/TabStoreDB.mdb"

            SelectCommand="SELECT * FROM Products WHERE (ProductCategory = ?) OR    (ProductBrand = ?)">
        <SelectParameters>
            <asp:QueryStringParameter Name="?" QueryStringField="ProductCategory" />
            <asp:QueryStringParameter Name="?" QueryStringField="ProductBrand" />
        </SelectParameters>
    </asp:AccessDataSource>

A: Unless I am totally not understanding your problem. You can just add AND/OR to you WHERE clause
OR WHERE clause
SELECT *
FROM Products
WHERE (ProductCategory = ?)
OR (ProductModel = ?)

AND WHERE Clause
SELECT *
FROM Products
WHERE (ProductCategory = ?)
AND (ProductModel = ?)

Based on your edit you have both query parameters are ? - they each need to have a specific name
SelectCommand="SELECT * FROM Products WHERE (ProductCategory = @ProductCategory) OR    (ProductBrand = @ProductBrand)">
        <SelectParameters>
            <asp:QueryStringParameter Name="ProductCategory" QueryStringField="ProductCategory" />
            <asp:QueryStringParameter Name="ProductBrand" QueryStringField="ProductBrand" />
        </SelectParameters>

If you are unsure of how to use the parameters, I suggest the following reading:
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.sqldatasource.selectparameters.aspx
http://msdn.microsoft.com/en-us/library/xt50s8kz.aspx

A: You gave both parameters the same name.  You need to be specfic -- try this:
SelectCommand="SELECT * FROM Products WHERE (ProductCategory = @cat) OR    (ProductBrand = @brand)">

And then this:
<SelectParameters>
            <asp:QueryStringParameter Name="cat" QueryStringField="ProductCategory" />
            <asp:QueryStringParameter Name="brand" QueryStringField="ProductBrand" />
        </SelectParameters>


text:
Q: How to correct Python Attribute error: 'SMOTE' object has no attribute 'fit_sample' Hello: I am trying to run the following code:
os = SMOTE(random_state=0)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)
columns = X_train.columns
os_data_X,os_data_y=os.fit_sample(X_train, y_train)

But get the error message described above - AttributeError: 'SMOTE' object has no attribute 'fit_sample'
I am using imbalanced-learn version 0.8.0 and scikit-learn version 0.24.1.
Thank you for any suggestions you can provide. I have imbalanced classes and am trying to adjust the sampling.

A: fit_sample was renamed to fit_resample in v0.4.
Replace with:
os_data_X, os_data_y = os.fit_resample(X_train, y_train)

See documentation here: https://imbalanced-learn.org/stable/references/generated/imblearn.over_sampling.SMOTE.html


text:
Q: MySQL: Optimized join across tables That query is slow (about 1.5 seconds).  It should simply return a list of posts

SELECT SQL_NO_CACHE p.id
    FROM 1_posts p
    LEFT JOIN 1_topics t ON (p.cid = t.cid AND p.container = t.id)
    WHERE t.cid = 1010699;

EXPLAIN gives:

+----+-------------+-------+------+-----------------------+-----------+---------+---------------+------+--------------------------+
| id | select_type | table | type | possible_keys         | key       | key_len | ref           | rows | Extra                    |
+----+-------------+-------+------+-----------------------+-----------+---------+---------------+------+--------------------------+
|  1 | SIMPLE      | t     | ref  | PRIMARY,cid           | cid       | 4       | const         |  216 | Using where; Using index |
|  1 | SIMPLE      | p     | ref  | PRIMARY,cid,container | container | 4       | forumdb.t.id |   49 | Using where              |
+----+-------------+-------+------+-----------------------+-----------+---------+---------------+------+--------------------------+

Note that SQL_NO_CACHE is there for testing purposes only.
Partial structure of tables:
1_posts:

mysql> explain 1_posts;
+----------------+----------------------+------+-----+---------+----------------+
| Field          | Type                 | Null | Key | Default | Extra          |
+----------------+----------------------+------+-----+---------+----------------+
| cid            | int(20) unsigned     | NO   | PRI | 0       |                |
| id             | int(20) unsigned     | NO   | PRI | NULL    | auto_increment |
| container      | int(20) unsigned     | NO   | MUL | 0       |                |

mysql> explain 1_topics;
+-----------------+----------------------+------+-----+---------+----------------+
| Field           | Type                 | Null | Key | Default | Extra          |
+-----------------+----------------------+------+-----+---------+----------------+
| cid             | int(10) unsigned     | NO   | PRI | 0       |                |
| id              | int(10) unsigned     | NO   | PRI | NULL    | auto_increment |
| container       | int(20)              | NO   | MUL | 0       |                |

Table posts has many millions of entries, topics about a 500k.
cid and id, on both tables are primary combo keys.  cid means Community ID. These tables host many different forums.
Thank you for any help you could give with speeding this stuff up.

A: When JOIN-ing on multiple fields (with AND) it helps to have a composite index on those fields.
In your case you can change your cid index in posts to (cid, container), that way mysql will be able to lookup the rows directly (you can still use it for queries with only cid conditions).
Also you should probably make it an INNER JOIN (as @AndrewK noted), for better readability.

A: Just by looking at your query you can simplify it.
Since you are reducing the set to where t.cid = 1010699 you are stating that it cannot bet null. So you can use an inner join.
SELECT SQL_NO_CACHE p.id
FROM 1_posts p
JOIN 1_topics t ON p.container = t.id
WHERE t.cid = 1010699 AND p.cid = t.cid;

EDIT:
As Vatev pointed out removing p.cid = t.cid does change the results of the query. I added it back in the WHERE clause for readability


text:
Q: How does an app verify the installation and usage of another application? I have come across several apps that have a section that provides ways to earn free in-app credit by interacting with their list of recommending apps. This includes things like "install and run" or "install and complete tutorial", and "install and reach level 10".
My Question: How does the application track this progress, which I can assume it can do even without being active, since you cannot assume a user will leave it running while getting through another app for an extended period of time. Maybe it inspects achievements attached to it like your Google Play account? Or something else?