text:
Q: Killer RJ45 cable for Polycom SoundStation 2? I was working from a conference room, and because the Wifi was dropping, I ended up unplugging a Polycom SoundStation 2 and connected the RJ45 terminated cable into my laptop.  I thought that at best I would ride the VoIP network out to the internet, and at worst it would not work.   To my surprise, a horrible electronics burning smell came out of my laptop NIC.  (Surprisingly my laptop hasn't crashed -yet?   And it even shows that I still have a NIC in device manager)
First I thought, "The cable fried my NIC!"   But thinking about it some more, it doesn't fully add up.  Was this just a coincidence?

*

*I did expect that a cable like this would be PoE (because Polycom has no AC adapter), but there is nothing wrong hooking up a non-PoE device in to a PoE cable, is there?  I'm also aware that PoE comes in different voltages, but that doesn't matter either, does it?

*I have had lot of trouble with static electricity in the last couple of days.  I would touch my laptop after being away from it, feel the static and laptop would crash.  I could still boot it up after no problem.   Maybe there was a static discharge from that cable and it pushed that component over the edge?

On the other hand the piece of evidence that makes me think it was the cable that fried my NIC is this:

*

*I looked up the specs for SoundStation2 and it says that it uses analog RJ11.  That was very weird to see because what I plugged in is NOT RJ11 and yet it fits perfectly fine into the Polycom ( and the Polycom works)   So does that mean that this was RJ45 pinned-out for analog operation + power?   If that's the case I would certainly expect "bad things to happen"... but it is just a plain looking RJ45 with all 6 pins terminated.  Pin out is  black,brown,red,orange,yellow,green,blue,white if that gives any hints.  Also, I'm somewhat familiar with these Polycom varieties, and the way this one starts up and is ready to use instantly makes me think it's a non-VoIP, analog model (VoIP models have to boot).  So maybe there are analog models with this killer RJ45 cable?

The reason I'm asking, is that if there is such as thing as a NIC killer cable, it violates all the assumptions about what I thought I was likely to encounter in a non-hostile office environment.  I've been plugging my stuff to hundreds of different devices in my long career of troubleshooting, but this is the first time a cable fried my NIC
What should I watch out if for if I don't want to fry my NIC again?

A: RJ-45 is simply a shape of plug.  It says nothing about what sort of signal is being carried over the cable -- I've seen it used for multi-line telephone, Ethernet, RS-232 serial, and other things.
A "Polycom SoundStation 2" appears to be a standard analog telephone system.  The reason you fried your NIC is because you fed standard analog 60-volt power into an Ethernet card that wasn't expecting it.


text:
Q: Fastlink edit and refresh links unable to connect Recently we got the fastlink urls(private urls and public urls) for add,edit refresh,
In these 3 operations add link working fine, but we face problem with edit and refresh url.
Error is : oauth_error_problem=signature_invalid&oauth_error_code=407
The signature generating process for the 3 operations same.
and here we are using private credentials for the 3 operations.
Please let me know required details for your testing.

A: oauth_error_code=407 means the signature generated is incorrect, I would suggest you to check the details and see if no extra space is being provided while generating signature. As well please check the siteAccountId you would be providing is correct.
Here is the documentation link which explains in detail and params needs to be used for generating Fast Link signature.

redpajama_set_name: RedPajamaStackExchange


text:
Q: No such directory when committing files using CVS from Eclipse I am using Eclipse solely as a CVS client. Mostly it works very good, but once in a while, when I am right-clicking a file to commit it (a file that it itself says is changed and ready for commit), it tells me "cvs [server aborted]: no such directory `...'
But the directory DOES exist?! If I navigate to the folder using tortoise CVS and right click for commit, it works fine? (this is the way I finally have to get those files committed)
Has anyone experienced this as well, and more importantly - has anyone solved it? :)
I am running Vista on the client PC and the CVS server is a Windows Server 2003 (please dont tell me to just switch to Linux - that is not much help).
Thank you very much for your help!

A: Not sure about Eclipse but I faced the same issue with WinCVS client. I could do CVS operations once I copied the CVS folder in each directory along the path.
For example: Suppose I am at C:\source\dir1. I select the flat-view and find the file with path C:\source\dir1\dir2\dir3\file.cpp, I should have the CVS folder present in each of following directories: dir1, dir2 and dir3. If the one/more folders are not present, we see below error.
cvs diff -u -- dir2\dir3\file.cpp (in directory C:\Source\dir1\)
cvs [diff aborted]: no such directory `dir2/dir3'

A: My solution -

*

*backup files you have changed in notepad or ...

*delete folder from eclipse.

*Synchronise again(eclipse shows files in minus)

*override and update now.

*copy contents of changed file

*commit


text:
Q: How to retrieve data from Yahoo Finance to my website? I am making an ASP.NET website where I want to retrieve data from Yahoo Finance, e.g.:
http://finance.yahoo.com/d/quotes.csv?s=RHT+MSFT&f=sb2b3jk
I am referring to above link to fetch data from Yahoo Finance.
The above link gives data in CSV format.
So how can I fetch data from the above link into my website? Any code or reference to some tutorial would be of great help.

A: Use the System.Net.WebClient to request the CSV, then something like FileHelpers to parse the file into a usable object. Then stuff into whatever you want.

A: Got the answer.
Used System.Net.WebRequest to download the CSV and then parsed it using answer in below link.
How to parse a CSV file in an ASP.NET website?
Hope this helps someone.


text:
Q: Get folder path in jsp Task: Copy Folder and contents from one vdi to another vdi. This application is internally facing within the company.
Method:

*

*In jsp have user browse for folder

*The folder selection is in a text box, the folder path is passed into an action class

*The folder path is placed into a teradata table

*A script is called to query the table for the source path and target path (pre-determined) and make the copy

Due Dilligence: So far I have tried the <input type="file", which selects a file, not a folder. Also, the file path is not passed through due to security reasons. I have read other possible solutions but none work.
Question: Are sevlets a viable solution, and if so, how do I create one?

A: I'm going to go with no. There are several reasons for this.

*

*A Java Enterprise Edition application (be it a Servlet or Java Server Page) is not supposed to access the file system directly.

*It is inherently unsafe to expose internal infrastructure through an external website.

I think you need to break it up a bit more.

*

*Save a list of shares the server has access to in a data store of some sort, like a new teradata table or  for a quick proof of concept plain text file (if you're on Linux you can use the output of something like showmount -e localhost).

*Let the user pick the src share from a combobox or something similar.

*Continue from your step 2.

This gives you two immediately obviously advantages, which may or may not be relevant.

*

*You can use the system without having access to the physical shares.

*You can add metadata (like description or aliases).


text:
Q: Filtering with Scala and Apache Spark I have created a unlabeled Dataset which has some columns. The values in one of the Column are France,Germany,France and UK
I know how to filter and count using below code.
val b =data.filter(_.contains("France")).count

However, I am not sure how to count values other than France.
I tried below code but it is giving me wrong result
val a =data.filter(x=>x!="France").count

PS: My question is a bit similar to Is there a way to filter a field not containing something in a spark dataframe using scala? but I am looking for some simpler answer.

A: You are trying to filter those elements which is equal to "France".
Try this
val a=data.filter(!_.contains("France")).count

A: To cricket_007 's point, should be something like this
val myDSCount = data.filter(row => row._1 != "France").count()

I am not sure what column your data is in, so the row._1 would change to the correct number.  You can run the following to see all of your columns:
 data.printSchema


text:
Q: What is the shortest Ph.D. thesis? The question is self-explanatory, but I want to make some remarks in order to prevent the responses from going off into undesirable directions.
It seems that every few years I hear someone ask this question; it seems to hold a perennial fascination for research mathematicians, just as quests for short proofs do.  The trouble is that it has strong urban-legend tendencies: someone will say, "So-and-so's thesis was only $\epsilon$ pages long!" where $\epsilon \ll 1$.  It will often be very difficult to confirm or disconfirm such claims, since Ph.D. theses are often not even published, let alone readily available online.  If you Google around for a while, as I did, you will find many dubious leads and can easily waste a lot of time on wild goose chases.  Frankly, I'm a bit fed up with this state of affairs.  I am therefore asking this question on MO in the hope that doing so will put this old question to rest, or at least establish provable upper bounds.
I would therefore request that you set yourself a high standard before replying.  Don't post a candidate unless you're sure your facts are correct, and please give some indication why you're so sure.  Read the meta discussion before posting.  (Note that the meta discussion illustrates that even a MathSciNet citation isn't always totally definitive.)  Include information about the content and circumstances of the thesis if you know it, but resist the temptation to gossip or speculate.
I'm not making this question community wiki or big-list because it should ideally have a definite answer, though I grant that it's possible that there are some borderline cases out there (perhaps there are theses that were not written in scholarly good faith, or documents that some people would regard as equivalent to a Ph.D. thesis but that others would not, or theses in subjects that are strictly speaking distinct from mathematics but that are arguably indistinguishable from mathematics dissertations).
Finally, to anticipate a possible follow-up question, there is a list of short published papers here (search for "Nelson").  Note that the question of the shortest published paper is not as urban-legendy because the facts are easier to verify.  I looked up the short papers listed there myself and found them to be quite interesting.  So in addition to trying to settle an urban legend, I am hoping that this question will bring to light some interesting and lesser known mathematics.

A: Kurt Gödel seems to be a good candidate for this "prize".
Let me quote from this review (see Page 74) of Kurt Gödel Collected Works.

The first three works of Godel in this volume are his dissertation of 1929
  (twenty-one pages in English), a revised and substantially abbreviated version
  (eleven pages in English) published in 1930, and a brief abstract based on a
  presentation of Godel's results in Konigsberg on 6 September 1930. Of all of
  Godel's longer, published writings, his dissertation has been, until now, the
  most difficult to obtain, and is here translated for the first time into English,
  by Stefan Bauer-Mengelberg and van Heijenoort.

A: According to mathscinet, Eva Kallin's thesis was 14 pages.

A: David Rector's thesis ("An Unstable Adams Spectral Sequence", MIT 1966) is 9 pages, according to the record at the MIT library.  I haven't seen the actual thesis for many years, but I'm pretty the actual mathematical content takes about 3 pages total, and is largely identical to the published version in Topology (1966, same title, doi link: https://doi.org/10.1016/0040-9383(66)90025-5), which is 3 pages plus bibliography.  (Dan Kan, his advisor, likes short papers.)

A: John Nash's thesis was 26 pages, and had two references in the bibliography.

A: Edmund Landau's thesis was 13 pages long.

A: Barry Mazur's thesis on the proof of the Schoenflies conjecture (and introducing the method of infinite repetition in topology) is 5 pages long.

A: I believe the shortest PhD thesis is of Burt Totaro "Milnor K-theory is the simplest part of algebraic K-theory", 12 pages.
Milnor K-theory is the simplest part of algebraic K-theory, Ph.D. thesis, University of California, Berkeley, 1989; published as: K-Theory 6 (1992), 177-189 (Portico archived version).
Burt Totaro's webpage at Cambridge, including a pdf of the published version.

A: This is not really an answer because these PhD's were never actually written, but anyway: in his book  A mathematicians miscellany (in the chapter on math with minimum raw material)  Littlewood gave 2 examples that could have been 2-line PhDs:
(1) Cayley's projective definition of length
(2)Theorem: An integral function never 0 or 1 is a constant.
  Proof: $\exp(i\Omega(f(z)))$ is a bounded integral function. ($\Omega$ is inverse to the elliptic modular function.)

A: I already posted this on meta where there was some discussion of whether the page count was correct. My guess is that it is, so I will post it here too:
MR2615548
Martens, Henrik Herman Buvik
A NEW PROOF OF TORELLI'S THEOREM.
Thesis (Ph.D.)–New York University. 1962. 12 pp.


text:
Q: What is the use of DB_VERSION attribute in Sq Lite database in android? I am using Sq Lite database in my android application. I created helper class to create tables in Sq Lite. In helper class i used DB_VERSION attribute and I used DB_VERSION to call super class(SQLiteOpenHelper) constructor. Can anyone tell me what is the use of DB_VERSION attribute in db helper class.
Thank you.

A: db_version is a value you specify manually. When a database is created, it stores this db_version you set manually for further uses.
Everytime the helper class iniziates it checks if db_version is the same than the one internally stored. If this number is different, then onUpgrade() method is call yo you can perform upgrade operations. Let me put you an example:

*

*You create an app and with db_version == 1.

*You develop a new
functionality wich introduces changes in the database (for example,
a new column). You will change db_version to 2. In the onUpgrade()
method, you will add the new column to all existing rows.

*When you intall the new version of your app in the device, when you first
open your db, the version it is checked. Your database has version 1
but db_version is 2 now, so onUpgrade() is called and the new column
added.

And that is the use.


text:
Q: How can i add a background color to a div(that has an id), that is inside a wrapper? Below is my code. Im using the framework skeleton. I have separate divs that represents three,seven and six columns that equal 16(skeleton is a 16 column framework). Therefore the the 3 divs are all inline accross the screen. The wrapper has a background color grey, therefore making the whole scree grey. However, i want to make the background color of the 3 div classes black. Any ideas? As ive tried to put all 3 divs into another div with an id, and set the background black however did not work?

Stephen Carter

I am  currently studentying at Leeds Beckett University, and this module is called Advanced Internet Development B

        About
        Portfolio
        Blog
        Contact

A: Add background color to your classes
.three, .seven, .six{
    background-color:black;
}

Fiddle with skeleton

A: Maybe I'm thinking to easy, but how about:
#wrapper {
    background: grey;
}
.three, .seven, .six {
    background: lightblue;
}

See this JSFiddle.
If it doesn't work for you, please share your CSS.

A: //try this css code
.three, .seven, .six {
    background-color:#000000 !important;
}

A: Did you try this?
#wrapper .three, #wrapper .seven, #wrapper .six {
    background-color:#000000 !important;
}

A: May be your div#wrapper background color overrides the div#wrapper inside div background color,so add like below:
#wrapper{background:grey;}
#wrapper div{background:black;}

or add !important like below:
#wrapper div{background:black !important;}

A: You just need to do that :

And change the hexadecimal value for the color you want.
Or do that with CSS by usign your classes :
.yourClass {
background-color: #000000;
}


text:
Q: jQuery how to auto adjust the number list when 1 of the list is removed? I want to automatically adjust the number list that was created using .append(). Example, if there are 4 items added on the list which will numbered from 2-4 respectively and if I removed item number 3, the item number 4 will automatically be number 3 and if I add a new item, it will be the last on the list. Here's my code below.

$('#display').click(function() {
  $('#show').show();
});
var c = 1;
$('#append').click(function() {
  var cnt = $('.cnt').val();
  for (var i = 0; i < cnt; i++) {
    c++;
    $('#inputs').append("
" + c + ".)<button id='remove' name='" + c + "'>X</button>
");
  }
});
$(document).on('click', '#inputs #remove', function() {
  var nm = $(this).attr('name');
  $('div[name="' + nm + '"]').remove();
  c--;
});
#show {
  display: none;
}

<button id='display'>Display</button>

  <input type='text' class='cnt' value='1' placeholder="num of append" />
  <button id='append'>+</button>

    1.)

Here is the jsfiddle of the code.

A: You should not be using the same ID for different elements
Also the way you could do this is by creating a function that resets the elements counting after each add/delete event
When creating and appending elements in jQuery its better to use this syntax:
$('<ELEMENT TAG/>',{
  ATTRIBUTE: VALUE
});

When looping through elements in jQuery its better to use $.each
$('#append').on('click', function(){
    $('
', {
        'class': 'inputs',
        html: '<input type="text" class="time" name="0" value="00:00:00"/><button>X</button>'
    }).appendTo('#inputs');
    resetInputsCount();
});

$('#inputs').on('click', '.inputs button', function(){
    var $this = $(this);
    $this.parent().remove();
    resetInputsCount();
});

//The function that resets the count span text and the name value based on the current count of elements
function resetInputsCount(){
    //looping through elements
    $('#inputs div.inputs').each(function(i){
        //caching the current element in a var named $this
        var $this = $(this);
        //changing the count span text to i+2 the 2 is added because the index starts at 0 and there is already one element 1.)
        $('.count', this).text((i+2) + '.) ');
        //change the value of the input name
        $('input', $this).attr('name', i+2);
    });
}

Demo on JSFiddle

A: here is your answer
Fiddle Here

$('#display').click(function() {
  $('#show').show();
});
var c = 1;
$('#append').click(function() {
  var cnt = $('.cnt').val();
  for (var i = 0; i < cnt; i++) {
    c++;
    $('#inputs').append("
" +c + ".)<button class='remove' name='" + c + "'>X</button>
");
  }
});
$(document).on('click', '#inputs .remove', function() {
  var nm = $(this).attr('name');
  $('div[name="' + nm + '"]').remove();
  c--;
resetCount();
});
function resetCount(){
    $('#inputs div.inputs').each(function(i){
        $('.number', $(this)).text(i+2);
        $('input', $(this)).attr('name', i+2);
    });
}
#remain,
#total {
  background-color: #333;
  width: 60px;
  height: 20px;
  color: #fff;
  padding: 0 10px;
}
input:focus {
  background-color: #000;
  color: #fff;
}
input {
  background-color: #ccc;
}
#show {
  display: none;
}

<button id='display'>Display</button>

  <input type='text' class='cnt' value='1' placeholder="num of append" />
  <button id='append'>+</button>

    1.)

A: I know theres an answer already but since I did the work I might as well post it.
Here's the fiddle for the example
here's the code:
Html

 Add

CSS
#button span {
    padding: 5px 15px;
    background: #ccc;
    cursor: pointer;
}
#button {
    margin: 5px 0;
}
.delete {
    cursor: pointer;
    padding: 0 5px;
    border: 1px solid gray;
}

jQuery
$(document).ready(function() {
    var index = 1;
    $('#button').on('click', function() {
        var add = '
' + index + '<input type="text"/>x
';
        $('#content').append(add);
        index++;
    });
    $(document).on('click', '.delete', function() {
        index--;
        $(this).parent().remove();
        var index2 = 1;
        var newelement = $('.new');
        $(newelement).each(function() {
            $(this).find('.number').text(index2);
            index2++;
        });
    });

});

A: Using your html structure and adding some input fields (to be sure we maintain values)
Here is my approach:
(Also fixed duplicate id and names you have)

$('#display').click(function() {
  $('#show').show();
});
var c = 1;
var inputs = [];

$('#append').click(function() {
  var cnt = $('.cnt').val();
  for (var i=0; i<cnt; i++) {
    c++;
    $div = $("
").data('index', c);
    $span = $("").text(c+".)");
    $button = $("<button class='input_remove' />").text("X");
    $input =  $("<input type='text' class='small' />").attr("name","input"+c);
    $div.append($div).append($span).append($input).append($button);
    $('#inputs').append($div);
  }
});

$(document).on('click', '.input_remove', function() {
  index = $(this).parent().data('index');
  $("#inputs").find('#input'+index).remove();
  c = 1;
  $("#inputs").find('div').each(function(index,ele){
    c++;
    $(ele).attr('id',"input"+c).data('index',c)
          .find("span").text(c+".)").end()
          .find("input").attr("name","input"+c);
  });
});
#show {
  display: none;
}
.small { width:100px; }

<button id='display'>Display</button>

  <input type='text' class='cnt' value='1' placeholder="num of append" />
  <button id='append'>+</button>

    1.)


text:
Q: Locality of Reference - English explanation for equidistant locality I am reading the Wikipedia article on Locality of Reference, and I cannot help but find the explanation given for Equidistant Locality to be rather cryptic.
I cannot really make much sense of it, and I wondered if anyone could make an attempt to explain it in plain English?

Equidistant locality: it is halfway between the spatial locality and
  the branch locality. Consider a loop accessing locations in an
  equidistant pattern, i.e. the path in the spatial-temporal coordinate
  space is a dotted line. In this case, a simple linear function can
  predict which location will be accessed in the near future.

What does it mean with "a loop accessing locations in an equidistant pattern"?  Are the locations just an equal distance from each other?
What's all this garbage about "the spatial-temporal coordinate space is a dotted line."?  That makes no sense to me.
If anyone could give some clarification on what Equidistant locality is supposed mean, that would be great!

A: I think this is best explained with examples. These principles of locality are often used to optimize things. A possible component in a modern CPU is a memory prefetcher, which will try to guess which memory you'll use and get it in cache by the time you need it. This relies heavily on the locality principle.
Take an array for example, if you do something like this (c++ example):
#include <iostream>
#include <vector>

int main()
{
    std::vector<int> test = { 1, 2, 3, 4, 5};
    for(int& i: test)
    {
        std::cout << i << std::endl;
    }
}

In a vector (or array in other languages) elements are packed in a contiguous block with fixed strides. So if the first element of test is at address X, then the second element will be at X+Y, the third at X+2Y, .... A vector itself is therefore a very basic example of spatial locality, and even better the locality is very predictable.
Next to that the elements are accessed in a tight loop, so we have good temporal spatiality also. Because the elements are also sequentially accessed, we have an equidistant spatiality in 'spacetime'. This means that as soon the CPU recognizes the X+Y, X+2Y, X+3Y pattern int he lookup it can start pulling in future elements in the cache.
You can contrast this with for example:
#include <iostream>
#include <list>

int main()
{
    std::list<int> test = { 1, 2, 3, 4, 5};
    for(int& i: test)
    {
        std::cout << i << std::endl;
    }
}

In a linked list, elements refer to eachother, and individual elements can be at any place in the memory so you lose your spatial locality. You access the elements in a loop however, so you still have your temporal spatiality. Something like this is much harder to detect and optimize for prefetching (not impossible however).
Finally, as an indicator why combined spacetime spatiality is important, consider this (little bit contrived) example:
#include <iostream>
#include <vector>
#include <algorithm>
#include <random>
#include <iterator>

int main()
{
    std::vector<int> test = { 1, 2, 3, 4, 5 };
    std::vector<unsigned int> indices = { 0, 1, 2, 3, 4 };
    std::random_device rd;
    std::shuffle(std::begin(indices), std::end(indices), std::mt19937 { rd() });
    for (unsigned int& i : indices)
    {
        std::cout << test[i] << std::endl;
    }
}

If you purely look at the test container it had again good spatial locality (strided as in the first example). If you look at the test access in the loop, you see there is a temporal locality in lookups. However, in "timespace" the lookups are not equidistant as you jump from one part of the array to the other, the access is not sequential, so there is no equidistant spatiality in both space and time. This is almost impossible to optimize.

A:
a loop accessing locations in an equidistant pattern

That is pretty cryptic, but if I had to guess, it means that all iterations of the loop have the same level of spatial/temporal locality: if the loop is simply iterating through an array, then in each iteration, we access the element located next to the previous element(so the spatial locality is the same as in the last iteration), and it's just as "recent" as it was in the last iteration (so temporal locality is unchanged as well).
So the equidistant locality is the same for every iteration.


text:
Q: Getting more information about a transformer I'm trying to figure out more information about a small transformer on a old board that we are reverse engineering, can someone give me some advices about how can we reverse engineer this transformer? Do the numbers on it represent something?
4783
6610741

A: The numbers aren't going to help you.  Remove the unit from the board, and you can probe around with a ohmmeter to figure out what is connected to what and what the DC resistance of each coil is.  Then inject a sine wave of a few volts into one of the windings, and measure the open circuit voltage of the other windings to find the turns ratio.  Then you can load individual outputs with known resistances to see how the voltage drops to get some idea of impedance.
From context, you can hopefully get some idea of what the transformer is intended to do.  From the small size and apparent lack of isolation (although we can't be sure from this picture), it is probably not handling wall power.  It could be a audio transformer, or maybe something for a switching power supply, but that is less likely if this was really built in 1983.  It seems too big for a pulse transformer.
I'd start with using 1 kHz for the AC test signal and see where that leads.  1 kHz is a good frequency for probing audio transformers.


text:
Q: Regex to replace [something]KeepThisPart I need some regex to strip the [ and ] off the start of the string, and anything in the middle, so:
[text]KeepThis should be KeepThis.
I can't seem to get my head around how to do it (far to long since I used regex :) )

A: $result = preg_replace( '/^\[.*?\]/', '', $string );

The regex finds any pair of brackets and their content from the beginning of the string and replaces it with an empty string.


text:
Q: Sending and receiving imagepng output via json encode AJAX I created a PNG image using PHP GD Library, added some text based on user input, and instead of saving it, I want to display it until user commits to changes.
They will add a few words, change a font, etc. so it needs to display their changes.  The only way I got this to work is to save the image to the server, but it saves dozens of images for dozens of slight changes the user makes.  I need to either overwrite the file, or do the below idea if it is proper.  The idea would be to create a temp file to manipulate.
So, how do I send it to the "success callback" just like the other variables I processed?  I read about how to use ob_get_contents() and I believe that is supposed to somehow store the image temporarily.  Is this how it works?
How do I display the image on the form page (not the processing PHP page) and is this a good plan to prevent saving to the server until the user commits?
// more image manipulation code above

ob_start();
imagepng( $my_img );
$imageData = ob_get_contents();
ob_clean();

$results = array(
'price' => $_GET['priceX'],
'imageprocessed' => base64_encode($imageData) <<<  EDIT change based on answer.
);

$json = json_encode($results);
echo $json;
?>

EDIT:  This is the javascript used in the success callback to receive the base64_encode.
<script type="text/javascript">
function doGen(){
var priceX = $('#couponprice').val();

$.get('processimage.php',
{priceX:priceX},
function(data) {
var imgFldr = '/images/';
data = $.parseJSON(data);
$('.price-placeholder').html(data.price);
var imageCallback = (data.couponnamecall);
$('#couponbuilt img').attr('src', 'data:image/jpeg;base64,' + imageCallback);
// ...
});
return false;
};
</script>

A: You could base64encode($imageData).
On the client side you simply create an data url out of the base64 encoded data and pass it into the src-attribute of an image tag.
I tested it out:
PHP code
ob_start();
imagepng($my_img);
$imageData = ob_get_contents();
ob_clean();

$results = array(
  'price' => $_GET['priceX'],
  'image' => base64_encode($imageData)
);

$json = json_encode($results);
echo $json;

Javascript code:
$.getJSON("/ajax-script.php", function(data) {
  $("#element").append($("<img />").attr('src', 'data:image/png;charset=utf8;base64,' + data.image));
});

A: You don't need json or XHR ('ajax') for that.
The simplest approach is to simply create the image on-the-fly, and request it the new one by changing the src of your image to a PHP file that produces the image on-the-fly.
You can do this in several ways. The simplest is described here:
If the data in your form isn't much (No kilobytes of text and such), then you can simply set the src of a preview-image to the URL of your PNG producing script. So your img src is a PHP script, NOT a stored static png-file.
Make sure your receiving PHP script sends the right headers (image/png), and you are ready to go. You'll need some JavaScript to assemble the URL, and put that into the img src.
In case you want to make the image permanent, simply add an extra name/value pair to the url, like storepermanent=yes


text:
Q: Jmeter - distributed set up - Response body is coming as empty, but response is coming if I hit each server individually Issue faced in distributed Jmeter setup

Hello All,
I connected 4 servers through jmeter - distributed set up, If I run from the master server, I am able to connect all 4 servers and get the response. I am able to see REsponse Code, but Response body is coming as null.
If I run each server individually - I am able to see the response body.
This was working before and stopped working now. Please help me to resolve this. Thank you in advance.

A: This is by design, according to JMeter Documentation:

mode
sample sending mode - default is StrippedBatch since 2.9. This should be set on the client node.
StrippedBatch
remove responseData from successful samples, and use Batch sender to send them.

If you want to see response data for any reason you need to add the next line to user.properties file on all slave machines:
mode=Standard

or
mode=Batch

restart of the slave process will be required to pick the property up.
Be aware that it will cause a lot of network traffic as all the slaves will be transmitting response data to the master machine so make sure you have enough resources to handle this (resources can be monitored using i.e. JMeter PerfMon Plugin)
More information: Apache JMeter Distributed Testing Step-by-step


text:
Q: How is input to the MySQL function md5 handled? I'm having problems understanding how input to the md5 function in MySQL 4.1.22 is handled. Basically I'm not able to recreate the md5sum of a specific value combination for comparison. I guess it has something to do with the format of the input data.
I have set up a table with two columns of type double(direction and elevation) + a third for storing a md5 sum.
With a setup script i add data to the direction and elevation fields + create a checksum using the following syntax:
insert into polygons (
  direction,
  elevation,
  md5sum
)
values (
  (select radians(20.0)),
  (select radians(30.0)),
  ( md5( (select radians(20.0)) + (select radians(20.0)) ) )
)

which ends up as: 0.349065850398866, 0.523598775598299, '0c2cd2c2a9fe40305c4e3bd991812df5'
Later I compare the stored md5sum with a newly calculated, the newly calculated is created using md5('0.349065850398866' + '0.523598775598299') and I get the following checksum:
'8c958bcf912664d6d27c50f1034bdf34'
If I modify the last decimal in the passed "string" from a 9 to a 8 0.523598775598298 i get the same checksum as previously stored, '0c2cd2c2a9fe40305c4e3bd991812df5'. Any value of the last decimal from 8 down to 0 gives the same checksum.
Using BINARY, (md5( (select BINARY(radians(20.0))) + (select BINARY(radians(20.0))) ) in the setup script creates the same checksum as the my original "runtime calculation"
Worth mentioning is that the original method works for all other rows I have (55)
I guess I'm using the function in a somewhat strange way, but I'm not sure of a better way, so in order to find a better way I feel I need to understand why the current is failing.

A: The two numbers you are adding are stored in binary form, but displayed in decimal form.  There is no guarantee that you will get exactly the same number back if you give the decimal form back to the machine.
In this case, this causes the addition to give a slightly different result, which gives an entirely different MD5 sum:
mysql> select radians(20.0) + radians(30.0), '0.349065850398866' + '0.523598775598299';
+-------------------------------+-------------------------------------------+
| radians(20.0) + radians(30.0) | '0.349065850398866' + '0.523598775598299' |
+-------------------------------+-------------------------------------------+
|              0.87266462599716 |                          0.87266462599717 |
+-------------------------------+-------------------------------------------+
1 row in set (0.00 sec)

If you want to consistently get the same result, you need to store the results of radians(20.0) and radians(30.0) in variables somewhere, never relying on their printed representations.

A: The output of radians(20.0) is computed with many more digits than are shown in the printed output. When the result is passed to the md5 function, the full non-truncated value is used, whereas the printed value only will show a limited number of digits. Thus, it is not the same value being passed into the md5 function in the two cases.


text:
Q: PHP extract domain of request (including HTTP) Laravel5.3 I'm saving a list of domains in my database like:
id|domain
1 http://xyz.or
2 http://xyz.ne
3 http://xyz.pw

Now when a user visits a website of I would need to get the domain of his request in this format so I can search database for existence.
What's the best way to extract the domain so I can perform a check for the above database design (domains contain subdomains too)?

A: You can get it using $request->root(), where the request is type of Illuminate\Http\Request


text:
Q: Interoperability: Fortran to C++ I would like to develop a Fortran Static Library that include a custom subroutine that takes a long time to complete.
This static library will be linked in my C++ application statically too.
My goal is monitoring the current status of this subroutine in my C++ application in real-time.
So, for each step of a "fortran loop", I would like to send the loop index to my C++ application.
I'm new in Fortran world, so I was thinking that this task could be something like this:
My C++ header:
extern "C" void fortran_status(int* value);
My Fortran-90 file:
module my_interfaces
    use iso_c_binding
        interface
            subroutine fortran_status(progress_value) bind(C, name = 'fortran_status')
                use, intrinsic :: iso_c_binding
                integer(c_int), intent(out) :: progress_value
            end subroutine fortran_status
        end interface
end module my_interfaces

! My long calc subroutine
subroutine my_long_calc(progress_value) BIND(C, name = 'my_long_calc')
    use, intrinsic :: ISO_C_BINDING
    use my_interfaces
    implicit none

    EXTERNAL fortran_status

    integer (C_INT), INTENT(INOUT) :: progress_value
    integer (C_INT) :: count

    do count = 0, 5
        progress_value = progress_value + 1

        ! Send 'progress_value' to a C++ function:
        call fortran_status(progress_value)

        ! Wait 1 second:
        call sleep(1)
    end do

end subroutine my_long_calc

This Fortran code gives me a compile-time error:
error #6406: Conflicting attributes or multiple declaration of name.   [FORTRAN_STATUS]       C:\Users\lamar\Desktop\Lib1_interface\Lib1.f90    18

I'm using Microsoft Visual Studio 2019 with Intel Visual Fortran (Windows 10 x64).
How could I monitoring that subroutine status? Or get the fortran loop index in my C++ application?
UPDATE 1:
I removed the EXTERNAL fortran_status and now I got no errors in compile-time of my Fortran code.
Now, I would like to link this static Lib (x86) with my C++ code:
#include <iostream>

extern "C" {
  void my_long_calc(void);
  void fortran_status(int* value);
}

void fortran_status(int* value)
{
  std::cout << "Fortran current status = " << *value << std::endl;
}

int main (void)
{
  std::cout << "Monitoring Fortran subroutine..." << std::endl;

  my_long_calc();

  return 0;
}

I'm trying to compile and link it using MingW:
g++ -Wall -L. .\Lib2.lib -lgfortran .\main.cpp -o app.exe
And I got this linker error:
undefined reference to my_long_calc
How can I link it?
I would like to see in my terminal output:
Monitoring Fortran subroutine...

Fortran current status = 0
Fortran current status = 1
Fortran current status = 2
Fortran current status = 3
Fortran current status = 4
Fortran current status = 5

UPDATE 2
Now this changed Fortran code compiles and it work well ONLY if I'm using MingW g++ (x86).
Fortran code:
module my_interfaces
  use iso_c_binding
  interface
    subroutine fortran_status(progress_value) bind(C, name = 'fortran_status')
      use, intrinsic :: iso_c_binding
      integer(c_int), intent(out) :: progress_value
    end subroutine fortran_status
  end interface
end module my_interfaces

! My long calc subroutine
subroutine my_long_calc() BIND(C, name = 'my_long_calc')
  use, intrinsic :: ISO_C_BINDING
  use my_interfaces
  implicit none

  integer (C_INT) :: progress_value
  integer (C_INT) :: count

  progress_value = 0

  do count = 0, 5
    progress_value = count

    ! Send 'progress_value' to a C++ function:
    call fortran_status(progress_value)

    ! Wait 1 second:
    call sleep(1)
  end do
end subroutine my_long_calc

C++ Code:
#include <iostream>

extern "C" {
    void my_long_calc(void);
    void fortran_status(int* value);
}

void fortran_status(int* value)
{
    std::cout << "Fortran current status = " << *value << std::endl;
}

int main (void)
{
    std::cout << "Monitoring Fortran subroutine..." << std::endl;

    my_long_calc();

    return 0;
}

Compile c++: g++ -Wall -c .\main.cpp
Compile fortran: gfortran -c .\gfortran.f90
Link all together: g++ .\main.o .\gfortran.o -o app.exe -lgfortran
The problem now is that I need to use Visual Studio 2019 and Visual Fortran to develop my Fortran Code.
And I would like to compile all Fortran code to a single static library (*.lib) file using Visual Studio.
What I need to change to get to link the *.lib file (from Visual Fortran) using the MingW g++ command?
I was thinking to use something like this:
g++ main.cpp my_lib.lib -o app.exe
But I got this linker error:
undefined reference to my_long_calc
What I need to do?

A: The code in your "Update 2" is perfectly fine and works with Intel Visual Fortran and Microsoft Visual C++. See also the discussion you started in https://community.intel.com/t5/Intel-Fortran-Compiler/Interoperability-Fortran-to-C/m-p/1144147
I do not recommend mixing Intel Visual Fortran compiled objects/libraries with g++ on Windows. You can get Microsoft Visual Studio Community Edition free if you meet the rather liberal license terms. If you insist on using g++, mix it with gfortran.


text:
Q: Infinitesimal orbit type decomposition of Hamiltonian $G$-manifolds Let $G$ be a compact connected Lie group acting in a Hamiltonian fashion on a symplectic manifold $M$ with momentum map $\mu:M\to \mathfrak{g}^\ast$, where $\mathfrak{g}$ is the Lie algebra of $G$. Then several standard textbooks (for example Ortega–Ratiu: Momentum Maps and
Hamiltonian Reduction (MSN)) treat the stratification of the symplectic quotient
$$
M//G:=J^{-1}(0)/G
$$
by orbit types $(H)$ of the $G$-action:
$$
M//G=\bigsqcup_{(H)}(M//G)_{(H)},\qquad (M//G)_{(H)}=M_{(H)}/G,
$$
where $M_{(H)}=\{p\in M: \exists\, g\in G,\; G_p =gHg^{-1}\}$, $G_p$ being the isotropy group of the point $p$.
Now, there is also a decomposition of $M//G$ by infinitesimal orbit types:
$$
M//G=\bigsqcup_{(\mathfrak{h})}(M//G)_{(\mathfrak{h})},\qquad (M//G)_{(\mathfrak{h})}=M_{(\mathfrak{h})}/G,
$$
where $M_{(\mathfrak{h})}=\{p\in M: \exists\, g\in G,\; \mathfrak{g}_p=\operatorname{Ad}(g)\mathfrak{h}\}$, $\mathfrak{g}_p$ being the isotropy algebra of the point $p$.
If $G$ is the circle group $S^1$, then this decomposition is a stratification and is described, for example, in Lerman–Tolman: Intersection cohomology of $S^1$ symplectic quotients and small resolutions (MSN).
However, I could not find a reference in which the infinitesimal orbit type decomposition (or indeed stratification?) is considered in the general case. Which is a good textbook or paper on this subject?


text:
Q: Windows 7 x64 refuses to boot due to an SSD-related issue This is my setup:

*

*Motherboard: ASUS P5KC

*Hard drive: Intel SSD 330 series connected via IDE

*OS: Windows 7 x64

The thing is that after having installed the SSD, on each and every a cold boot, Windows hangs on loading the classpnp.sys driver. It's only visible when booting into the safe mode, otherwise it just freezes. The strange thing here is the fact that restarting the machine solves the problem. In fact, I can start up the PC, instantly restart and everything is fine.
Now, I tried:

*

*deleting the classpnp.sys file and letting the recovery DVD restore the default driver file

*repairing the boot sector of the SSD

*changing the Plug'n'Play OS support option in BIOS

*changing the ATA/IDE Configuration (Disabled, Compatible and Enhanced) option in BIOS

... to no avail! What's rotten in the state of Denmark, I wonder?


text:
Q: Static and instance methods in Python Can I define a Python method to be both static and instance at the same time? Something like:
class C(object):
    @staticmethod
    def a(self, arg1):
        if self:
            blah
        blah

So that I can call it with both:
C.a(arg1)
C().a(arg1)

The intent is to be able to run two sets of logics. If accessed as an instance method, it would make use of instance variables and do stuff. If access as a static method, it will do without.

A: formencode has a classinstancemethod decorator, which does what what you want. It requires the method to have 2 arguments (self and cls, one of them could get passed None depending on calling context)
Lifted from formencode/declarative.py
class classinstancemethod(object):
    """
    Acts like a class method when called from a class, like an
    instance method when called by an instance.  The method should
    take two arguments, 'self' and 'cls'; one of these will be None
    depending on how the method was called.
    """

    def __init__(self, func):
        self.func = func

    def __get__(self, obj, type=None):
        return _methodwrapper(self.func, obj=obj, type=type)

class _methodwrapper(object):

    def __init__(self, func, obj, type):
        self.func = func
        self.obj = obj
        self.type = type

    def __call__(self, *args, **kw):
        assert not kw.has_key('self') and not kw.has_key('cls'), (
            "You cannot use 'self' or 'cls' arguments to a "
            "classinstancemethod")
        return self.func(*((self.obj, self.type) + args), **kw)

    def __repr__(self):
        if self.obj is None:
            return ('<bound class method %s.%s>'
                    % (self.type.__name__, self.func.func_name))
        else:
            return ('<bound method %s.%s of %r>'
                    % (self.type.__name__, self.func.func_name, self.obj))

Sample usage
class A(object):
    data = 5

    @classinstancemethod
    def print_(self=None, cls=None):
        ctx = self or cls
        print ctx.data

>>> A.print_()
5
>>> a = A()
>>> a.data = 4
>>> a.print_()
4

A: No. What would self mean inside the method, if you could do that?

A: import functools

class static_or_instance(object):
  def __init__(self, func):
    self.func = func

  def __get__(self, instance, owner):
    return functools.partial(self.func, instance)

class C(object):
  @static_or_instance
  def a(self, arg):
    if self is None:
      print "called without self:", arg
    else:
      print "called with self:", arg

C.a(42)
C().a(3)

A: Your code will work if you remove the self parameter to a().  When you call it with C().a(arg1) the instance is ignored.
But you want this method to work as both a static method and a method that receives an instance. You can't have it both ways.


text:
Q: Best way to plot an updating webGL mesh/surface I need to create a surface or mesh (or particle system) in WebGL which updates with a new row at a given time interval. This is essentially a spectral display (similar to a waterfall, but it needs to be in 3D) in which every 2 seconds, the display needs to add an additional column of spectral information. I want this to gradually grow into a surface with coloured vertices/faces/particles based on the relative height as compared to the overall maximum height.
All in all, a very simple endeavour I'd think. Yet I struggle to locate what type of geometry to best use for this also for performance reasons. Ultimately, there are as many as ~1000x1000 points making up a surface, and there are at least 2 such surfaces in the scene at one time.
Options I have played around with thus far include:

*

*Using a BufferedGeometry with a particle system material. This seems to perform best, but I can't find an elegant way to update this in real time. So when updating it, the entire scene locks up.

*Using a mesh. But there's no simple way to add a row of points and triangulate the whole geometry, make faces etc. in real time. This again either blocks up or the helper triangulation function chokes (randomly it seems).

*Using a PlaneGeometry default set to 1000x1000 in size, and then modifying each point as the data columns are received. I haven't actually tried this yet… but it's crossed my mind as an (undesirable) option.

Neither of the first two options I've tried however perform as nicely as what I need them to. Every 2 seconds, ~1000 points in a row are received and need to be added to the (existing) geometry. Is that really such a complex endeavour? Any hints greatly appreciated!

A: You are looking for streaming vertex buffers.
When creating the buffer, you can specify "how" it will be used (see this).
I believe that STREAM_DRAW would suit your needs the best.
So, you gradually receive the date, and update only the parts of the buffer that you need to (gl.bufferSubData etc), and this parameter will optimize certain things for you.
~2M points shouldn't be a problem on some newer GPU.
Tutorial:
Animating million letters with Three.js -> here (but without streaming).


text:
Q: Intriguing behavior when set prototype on Constructor in javaScript Begin with an simple attempt, I defined an Constructor and used it to create an instance myobject:
function MyConstructor () {};
var myobject = new MyConstructor ();

Then, I modified the prototype property of this Constructor and created another instance myobject1 with it:
MyConstructor.prototype = {};
var myobject1 = new MyConstructor ();

I repeated the same procedure and created another instance myobject2:
MyConstructor.prototype = {name: '2'};
var myobject2 = new MyConstructor ();

Now I am testing the constructor property of each instance, which is not what I expect:
myobject.constructor == MyConstructor;
//true
myobject1.constructor == MyConstructor;
//false
myobject2.constructor == MyConstructor;
//false

When looking up the [[prototype]], it is different from each other.
myobject.__proto__ == myobject1.__proto__
//false
myobject2.__proto__ == myobject1.__proto__
//false

Could anyone explain what happens to MyConstructor when changing its prototype property?

A: When you creating constructor:
function MyConstructor() {};

it has prototype.constructor set to MyConstructor:
MyConstructor.prototype.constructor === MyConstructor; //true

When you overwrite prototype of MyConstructor by
MyConstructor.prototype = { foo: function () {} };

then origignal MyConstructor.prototype object is replaced by passed object { foo: function () {} } and this object does not have property 'constructor' set to MyConstructor but to function Object because Object is constructor bound to all object created by object literals.
So after this:
MyConstructor.prototype = { foo: function () {} };
MyConstructor.prototype.constructor === Object;

and when you create new object with this constructor
var foo = new MyConstructor();

then:
foo.constructor === Object; // true

so to repair this problem, after you overwrite prototype then you have to correct constructor field:
MyConstructor.prototype = { foo: function () {} };
MyConstructor.prototype.constructor = MyConstructor;

and then your constructor has prototype with correct constructor field.
You could also write:
MyConstructor.prototype = { foo: function () {}, constructor: MyConstructor };

and final effect will be the same.

A: The constructor is held in prototype.  By destroying the prototype with {} you effectively remove any reference to the constructor.


text:
Q: How do you add numbers to an int? I'm trying to make a basic calculator in c#.
The only problem is, I don't know how I could add numbers to an int; for instance, if I wanted button1 to do something like this in a textbox, it'd be
textBox1.text += "1"

but this is for the operations, and the textbox displays the operator, so I couldn't convert it to an int. I'd really appreciate some help.

A: You can do it with something like (where s is a string):
s = (Int32.Parse(s) + 1).ToString();

Just make sure that s is actually a valid number, otherwise you'll have to cobble together something with TryParse and figure out what to do when it's not a number, like leave it alone:
int val;
if (Int32.TryParse(s, out val)) {
    val++;
    s = val.ToString();
}

You can also restrict user input so that they can only enter integers, have a look at MaskedTextBox and set the Mask property. See the documentation here.

A: C# is a strongly typed language. A textbox contains a string, which you must convert to an int before performing arithmetical operations.
Converting a string to an int can be done with int.Parse(), then you must convert back to a string to change the textbox contents:
int temp = int.Parse(textBox1.Text) + 1;
textBox1.Text = temp.ToString();

This will throw an exception if textBox.Text cannot be converted to an int. To deal with this, look up the int.TryParse() function.


text:
Q: How to pass both JavaScript variables and checkbox results in submit form to controller in laravel 6.x I get stuck in finding the way to pass JavaScript variables and some checkbox results from submit form to controller. Could you please tell me the way I could get all values from the request in controller. All your help is appreciated.
Here is my blade:
<form class="form-horizontal" id="form_input" action="#">

            Node Profile:

              <select id="node_id" name="node_id" class="form-control" data-placeholder="choose node">
              </select>

            Overall

                <input type="checkbox" name="check_id[]" value="Overall" aria-label="Checkbox for following text input">

            History

                <input type="checkbox" name="check_id[]" value="History" aria-label="Checkbox for following text input">

      <input type="submit" id="btnSubmit" name="btn_Submit" class="btn btn-primary btn-block" value="printFile">

</form>

And I am using select2 to load data of equipments that appear in dropdown, then here is my code js to load and get id of element after selecting from dropdown:
$('#node_id').on('select2:select', function(e) {
  var node = e.params.data;
  alert(node.id);
});


text:
Q: add an existing .js file to an angularjs 2 application At my company we have a standard header for all websites which consists of a .js file and some .css to display it with the corporate style.
We have successfully used this in an AngularJS1 application by adding the following to the index.html
<script src="header/js/header.min.js"></script>
<link rel="stylesheet" href="header/css/header.light.min.css">

We are now in the process of converting our site to AngularJS2 and I have added both these lines to the index.html file of the new AngularJS2 application.
The header displays correctly but when I run NPM start it says it can't find the .js file.
I have tried all the answers I can find but I can't get it to work.
Please could someone put me out of my misery
Thank you very much


text:
Q: What is right and left of element in CSS What is right and left of elements in CSS.
When I tried to move element left: 150px . It moves right and vice versa.

A: When you specify a position of element (relative/absolute/fixed/ect) the left and right tags all you to align to and offset:
ex. (left:0px;) will align to the left by 0 px or (left:15px;) will align to the left and offset by 15px..
(offset meaning, it pushes from the left 15px out)
Relative positioning you must specify a value- won't take %
absolute position is in relation to it's parents positioning, so you can use % with absolute positioning and left/right:

A: You can use float: left; and float: right; to achieve basic positioning. If you are looking for more advanced positioning could you please post your code so that we can see what you are trying to do! :)

A: left is the distance from the left edge; right is the distance from the right edge.
For instance, if I set left: 10px, it will move the element 10px away from the left edge of the element.
If you want to move to the left, you can use negative values, e.g. left: -10px.
The same applies to the top and bottom properties.

W3Schools puts it this way:
Sets the left edge of the image [distance] to the right of the left edge of its containing element


text:
Q: how to create application that always run in the background? I want to create an application that listen to sms and always run in the background.
The service must start when the user turn his android on - and always in action until the android device is down.
I know only how to create application with GUI ( with activity ) - but on this case i don't want to have any GUI with it.
I don't find any example of how to do it.

A: If you only need to react to incoming sms, you can just register a broadcast receiver for that. No special background service needed. Your code will be called whenever a SMS is received.
In your android manifest point out a java class that extends BroadcastReceiver to be called for incoming SMS:
<receiver android:name="mypackage.SmsReceiver">
            <intent-filter>
                <action android:name="android.provider.Telephony.SMS_RECEIVED" />
            </intent-filter>
</receiver>

Don't forget the permission:
<uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission>

And then implement your SmsReceiver class:
public class SmsReceiver extends BroadcastReceiver {
    private static final String ACTION = "android.provider.Telephony.SMS_RECEIVED";

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (ACTION.equals(action)) {
            Bundle bundle = intent.getExtras();
            if (bundle != null) {
                Object messages[] = (Object[]) bundle.get("pdus");
                if (messages != null) {
                    SmsMessage smsMessages[] = new SmsMessage[messages.length];
                    for (int n = 0; n < messages.length; n++) {
                        smsMessages[n] = SmsMessage.createFromPdu((byte[]) messages[n]);
                        SmsMessage smsMessage = smsMessages[n];
                        String from = smsMessage.getOriginatingAddress();
                        //do your thing
                    }
                }
            }
        }
    }
}


text:
Q: Check if something exists in MySQL database I'm trying to check if a string is already present in my database.
UPDATED:
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

// Start SQL check
$steamid = $_POST["steamid"];

$sql = "SELECT steamid FROM blacklist WHERE steamid = $steamid";

if ($result=mysqli_query($con,$sql))
{
// Return the number of rows in result set
$rowcount=mysqli_num_rows($result);
}

if($rowcount >=1)
{

    echo "not added as we already have steam id in databse";

}
else
{

echo "code to add it here";
    //SteamID not in database
     //Add it to databse
     $sql = "INSERT INTO blacklist (steamid, permBanned)
            VALUES ('$steamid', false)";

    mysqli_query($con,$sql);
      echo "Added to blacklist";

}

mysqli_close($con);

The insert does work but the select and checking to see if it exists doesn't. I don't know why?
Thanks for any help.
(Table structure: blacklistID : autonumber, steamid : string, permBanned : bool)

So I updated it to try and use MySQLi but I don't seem to be getting anywhere with this.. Can anyone now help? I really appreciate it.

A: Try
$sql = mysql_query("SELECT steamid FROM blacklist WHERE steamid =". $steamid);

if(mysql_num_rows($sql)>0)
{

echo "not added as we already have that ID in the database";

}


text:
Q: How to display a dart:html file image in Flutter web? I upload a file from the users device this way:
void uploadImage() async {
    html.InputElement uploadInput = html.FileUploadInputElement();
    uploadInput.click();
    uploadInput.onChange.listen(
      (changeEvent) {
        final file = uploadInput.files.first;
        final reader = html.FileReader();

        reader.readAsDataUrl(file);
        reader.onLoadEnd.listen(
          (loadEndEvent) async {
            setState(() {
              image = file; //image is a dart:html File object, it's a field of my statefulwidget
            });
          },
        );
      },
    );
  }
}

I would like to display this image. I tried using an Image.file:
           Container(
              width: 100,
              height: 100,
              child: Image.file(
                image,
                fit: BoxFit.contain,
              ),
            ),

However this gives me this error:

The argument type 'File (where File is defined in C:\Users\Asus\Documents\flutter\bin\cache\pkg\sky_engine\lib\html\html_dart2js.dart)' can't be assigned to the parameter type 'File (where File is defined in C:\Users\Asus\Documents\flutter\bin\cache\pkg\sky_engine\lib\io\file.dart)'.dartargument_type_not_assignable
html_dart2js.dart(15975, 7): File is defined in C:\Users\Asus\Documents\flutter\bin\cache\pkg\sky_engine\lib\html\html_dart2js.dart
file.dart(241, 16): File is defined in C:\Users\Asus\Documents\flutter\bin\cache\pkg\sky_engine\lib\io\file.dart
Peek Problem (Alt+F8)
No quick fixes available

Is there a way to convert a dart:html File into a dart:io File? Or should I try another way of displaying the image? In that case how do I display a dart:html File?
Thanks for your help in advance!

A: One solution is to use the image_whisperer package.
Lets say that your html.File is variable myfile, The following works for me:
import 'package:flutter/painting.dart';  // NetworkImage
import 'package:image_whisperer/image_whisperer.dart';  // BlobImage
...

BlobImage blobImage = new BlobImage(myfile, name: myfile.name);
final image = NetworkImage(blobImage.url);

// Use image here
...


text:
Q: gevent spawing - in sequence rather than concurrent I am trying my hand on asynchronous programming with gevent and not able to understand the way my code works.
I am trying to ping google.com using sockets on a closed port (22) and expecting the ping function to happen concurrently but it is not happening
I have a python code as below
class Ping(object):

   def checkReachability(self,index):

      sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
      sock.settimeout(2)

      print index

      try:
           sock.connect(('google.com',22))
           gevent.sleep(0)
      except socket.error as e:
           print str(e)

      sock.close()

 def ping(self):

      threads = [gevent.spawn(self.checkReachability, i) for i in range(3)]
      gevent.joinall(threads)

if __name__ == 'main':
    m = Ping()
    m.ping()

I am expecting to see:
0
1
2
timeout
timeout
timeout

This is what I am getting
0
timed out
1
timed out
2
timed out

Any help would be helpful.
Thanks

A: Figured the solution.
Adding a monkey patch in import solved my issue.
from gevent import monkey
monkey.patch_socket()


text:
Q: Removing an email template from a managed package Is it possible to remove an email template from a managed package release?
I used to want to distribute a template but I don't use it anymore so it just redundant.

A: You have two choices:

*

*You can roll back to a beta package. Note that you must roll back to the version that originally included the template to do this, and this requires that all customers using any later version (including any sandboxes, demo accounts, etc) uninstall the later version first.

*You can request access to the pilot program that allows deleting arbitrary elements from a managed package. You must use this with care, as any elements deleted this way are permanently lost; the "name" of the element becomes permanently unavailable for future use within that package. For example, if the template name is MassEmailUsers, and you delete it, you cannot later decide to create a new template called MassEmailUsers.


text:
Q: NonTemplate Function Friend of Template Class Can somebody explain me what I am doing wrong? This is teh error I get from the compiler.
Many Thanks
1>------ Build started: Project: Ch16, Configuration: Release Win32 ------
1>  p643_inclusion.cpp
1>  p643_inclusion_main.cpp
1>  p643_print.cpp
1>p643_print.cpp(5): error C2065: 'T1' : undeclared identifier
1>p643_print.cpp(5): error C2065: 'T2' : undeclared identifier
1>p643_print.cpp(6): warning C4552: '<<' : operator has no effect; expected operator with side-effect
1>p643_print.cpp(7): warning C4552: '<<' : operator has no effect; expected operator with side-effect
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

p643_inclusion.h
#ifndef P643H
#define P643H

template< class T1, class T2> class Car {

    friend void  print (const Car<T1, T2> &c1);
    private:
        T1 Wheels;
        T2 DriversName;
    public:
        Car(): Wheels(4), DriversName("None") {}
        Car(T1, T2);
};

template <class T1, class T2> class Driver {
    private:
        T1 Name;
        T2 Surname;
    public:
        Driver(): Name("None"), Surname("None") {}
};

#include "p643_inclusion.cpp"

#endif

p643_inclusion.cpp
# ifndef P643CC
#define P643CC

#include <iostream>
#include <string>
using std::string;
using std::cout;
using std::endl;
#include "p643_inclusion.h"

template<class T1, class T2>
Car<T1, T2>::Car(T1 w, T2 d) {
    Wheels = w;
    DriversName = d;
}

#endif

p643_print.cpp
#include "p643_inclusion.h"
template< class T1, class T2> class Car;

void  print (const Car<T1, T2> &c1) {
    cout << c1.Wheels << endl;
    cout << c1.DriversName << endl;
    }

main
#include "p643_inclusion.h"
#include<iostream>
#include<string>
using namespace std;

int main()
{

    Car<int, string> myCar;
    Driver<string, string> myDriver;

    print(myCar);

    return 0;
}

A: Your function is not actually a non-template function.
void  print (const Car<T1, T2> &c1) {
    cout << c1.Wheels << endl;
    cout << c1.DriversName << endl;
}

This is wrong. Can you ask yourself what exactly is T1? and T2?

You should implement this as:
template<class T1, class T2>
void  print (const Car<T1, T2> &c1) {
    cout << c1.Wheels << endl;
    cout << c1.DriversName << endl;
}

And you should make it friend as:
template< class T1, class T2> class Car {

    //choose different name for type params, because enclosing class
    //already using T1, and T2
    template<class U, class V>
    friend void  print (const Car<U, V> &c1);

    //...

A: Mixing templates and friendship is not always as simple as it might seem. My advice is that you define the befriended function in the class definition, and then your problem will basically go away:
template <typename T1, typename T2>
struct test {
   friend void print( test const & t ) { ... };
};

For each instantiation of the template test, it will declare and define a (non templated) free function that takes a test object instantiated with the same template arguments that triggered the instantiation of the template.
Other options available (I would stay clear of these if possible):
You can make print be a template and declare that template a friend of your class template (the whole template):
template <typename T1, typename T2>
struct test {
   template <typename U, typename V>
   friend void foo( test<U,V> const & ); // befriend template, all instantiations
};
template <typename T1, typename T2>
void foo( test<X,Y> const & x ) {...}

This opens your internals to all of the potential instantiations of the template, including possible specializations, and you might not want to do that. If you want to befriend only a particular instantiation of that template, you can do so, but it becomes more cumbersome:
template <typename T1, typename T2> struct test;  // forward declaration

template <typename T1, typename T2>
void foo( test<T1,T2> const & );                  // forward declaration

template <typename T1, typename T2>
struct test {
   friend void foo<T1,T2>( test<T1,T2> const & ); // befriend specific instantiation
};

template <typename T1, typename T2>
void foo( test<T1,T2> const & x ) { ... }         // implement

For a further explanation, you can look at the answer here


text:
Q: Unable to resolve path [Player.playerName_en], unexpected token [Player] I have this error can any one help me please
Here is my stacktrace:
Etat HTTP 500 - Request processing failed; nested exception is org.springframework.orm.hibernate4.HibernateQueryException: Unable to resolve path [Player.playerName_en], unexpected token [Player] [SELECT NEW PlayerTransient .

Here is my code:
    Session session = sessionFactory.getCurrentSession();
    Transaction tx = session.getTransaction();
    tx.begin();

    try {
            String sql="SELECT NEW PlayerTransient (Player.playerName_en,Player.playerName_fr,Player.playerName_ar,Player.playerName_Abreviation, Player.playerImage,preference_player.identifier) FROM Player left join preference_player on Player.playerId= preference_player.playerId and preference_player.identifier=Player.identifier";
        playerTransients =  session.createQuery(sql).list();
        tx.commit();

    } catch (RuntimeException e) {

        tx.rollback();
        throw e;
    }

    return playerTransients;
}

}
`

A: There are many errors in your HQL query:
1/You've missed the alias after Player classname :
from Player as Player

2/ Your join clause left join preference_player on Player.playerId= preference_player.playerId is not correct you have to put :
left join Player.preference_player // without the on part (which is sql syntax)

Here the complete query :
SELECT NEW PlayerTransient (Player.playerName_en,Player.playerName_fr,Player.playerName_ar,Player.playerName_Abreviation, Player.playerImage,preference_player.identifier) FROM Player as Player
left join Player.preference_player  where Player.preference_player.identifier=Player.identifier;


text:
Q: Anyone using Laravel with Facebook Messenger platform api? Anyone using Laravel framework? Need some help
I am developing Messenger Chat bot on Laravel I have set up everything such as Route,Webhook and also subscribed page but no respond from messenger chat..
Any idea?
ps. It's working without Laravel

A: Please, provide the laravel log file.
Also you can check class VerifyCsrf and add webhook URL to disabled routed array:
protected $routes = [
        'webhook/facebook/url/paste/here',
        'another/route/here',
];


text:
Q: abspath returns different results when py_compile input path is different in Python? I want to know abspath of python script followed by steps below.

*

*built it to byte code by py_compile.

*execute it to check abspath.
But I got 2 results when I execute it.I found the results based on the path of script followed by py_compile.
Here is my script test.py :
import os
import inspect

print os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))

Build it with py_compile, then got 2 results when I enter different path of test.py:
1.enter the folder and compile with only script name.Then chdir to execute
[~]cd /usr/local/bin/
[/usr/local/bin/]python -m py_compile test.py
[/usr/local/bin/]cd ~
[~]python /usr/local/bin/test.pyc
/home/UserXX

2.In other folder and compile with absolute script name.
[~]python -m py_compile /usr/local/bin/test.py
[~]python /usr/local/bin/test.pyc
/usr/local/bin

how come got 2 different results?

A: When we want to get the path of one python file, typically we can use any of following methods:
1.
a)
import os
import inspect
print os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))).replace('\\', '/')

b)
import os
import inspect
print os.path.dirname(os.path.abspath(inspect.stack()[0][1])).replace('\\', '/')

2.
a)
import os
import sys
print os.path.dirname(os.path.abspath(__file__)).replace('\\', '/')

b)
import os
import sys
print os.path.dirname(os.path.abspath(sys.argv[0])).replace('\\', '/')

For most of scenarios, we use 1 is enough, we seldom to use inspect like 2, as inspect maybe slower.
When will we use 2? Say use inspect to get file path?
One scenario I can remember is execfile, when fileA.py execfile fileB.py in its program, and fileA & fileB not in the same folder. (Maybe more scenario)
Then if we use __file__ in fileB.py, you will find its directory is just same as fileA.py, because here the directory will be the caller's directory.
Then we had to use inspect to get fileB.py's directory.
Anyway, for your situation, if your test.py just at the top of callgraph, just suggest you to use __file__, it's quicker, no need to use inspect.
With this if you use -m py_compile, it works for you.
Finally, why inspect not work with -m py_compile?
Unfortunately, I did not find official document to explain this.
But suppose your test.py is in the folder tt, then let's do cd ..; python -m py_compile tt/test.py, you will get a test.pyc in tt folder.
Let open this pyc file, although you will see something not suitable for man to read, you still can find some clue:
One line is something like:
currentframe(^@^@^@^@(^@^@^@^@(^@^@^@^@s^G^@^@^@tt/a.pyt
Do you see the folder name tt already in pyc file?
If you use inspect.stack() to test, it will more clear, print inspect.stack()[0][1] will always take your current compile folder in pyc file if you use -m py_compile.
This directly means during the process of py_compile, something was fixed to pyc file. This something I call fix makes you can just run your program in the same folder you do -m py_compile.
Hope this can give you some clue & helps you.


text:
Q: Put 1000 vectors into a list I have 1000 vectors: c1,c2,...,c1000
I want to put them in a list looks like:
list1<-list(c1,c2,...,c1000)

How can I do it in a loop please?

A: We can use mget on a vector of strings created using paste.  The output will be a list with list elements as the values stored in the object names.
list1 <- mget(paste0('c', 1:1000))

If we need to remove the vector object names from the global environment,
rm(list=paste0('c', 1:1000))

as @Frank mentioned in the comments.


text:
Q: Convert Java Date to UTC String The java.util.Date toString() method displays the date in the local time zone.
There are several common scenarios where we want the data to be printed in UTC, including logs, data export and communication with external programs.

*

*What's the best way to create a String representation of java.util.Date in UTC?

*How to replace the j.u.Date's toString() format, which isn't sortable (thanks, @JonSkeet!) with a better format?

Addendum
I think that the standard way of printing the date in a custom format and time zone is quite tedious:
final Date date = new Date();
final String ISO_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS zzz";
final SimpleDateFormat sdf = new SimpleDateFormat(ISO_FORMAT);
final TimeZone utc = TimeZone.getTimeZone("UTC");
sdf.setTimeZone(utc);
System.out.println(sdf.format(date));

I was looking for a one-liner like:
System.out.println(prettyPrint(date, "yyyy-MM-dd'T'HH:mm:ss.SSS zzz", "UTC"));

A: The following simplified code, based on the accepted answer above, worked for me:
public class GetSync {
    public static String ISO_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS zzz";
    private static final TimeZone utc = TimeZone.getTimeZone("UTC");
    private static final SimpleDateFormat isoFormatter = new SimpleDateFormat(ISO_FORMAT);
    static {
        isoFormatter.setTimeZone(utc);
    }

    public static String now() {
        return isoFormatter.format(new Date()).toString();
    }
}

I hope this helps somebody.

A: tl;dr
You asked:

I was looking for a one-liner like:

Ask and ye shall receive. Convert from terrible legacy class Date to its modern replacement, Instant.
myJavaUtilDate.toInstant().toString()

2020-05-05T19:46:12.912Z

java.time
In Java 8 and later we have the new java.time package built in (Tutorial). Inspired by Joda-Time, defined by JSR 310, and extended by the ThreeTen-Extra project.
The best solution is to sort your date-time objects rather than strings. But if you must work in strings, read on.
An Instant represents a moment on the timeline, basically in UTC (see class doc for precise details). The toString implementation uses the DateTimeFormatter.ISO_INSTANT format by default. This format includes zero, three, six or nine digits digits as needed to display fraction of a second up to nanosecond precision.
String output = Instant.now().toString(); // Example: '2015-12-03T10:15:30.120Z'

If you must interoperate with the old Date class, convert to/from java.time via new methods added to the old classes. Example: Date::toInstant.
myJavaUtilDate.toInstant().toString()

You may want to use an alternate formatter if you need a consistent number of digits in the fractional second or if you need no fractional second.
Another route if you want to truncate fractions of a second is to use ZonedDateTime instead of Instant, calling its method to change the fraction to zero.
Note that we must specify a time zone for ZonedDateTime (thus the name). In our case that means UTC. The subclass of ZoneID, ZoneOffset, holds a convenient constant for UTC. If we omit the time zone, the JVM's current default time zone is implicitly applied.
String output = ZonedDateTime.now( ZoneOffset.UTC ).withNano( 0 ).toString();  // Example: 2015-08-27T19:28:58Z

About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes. Hibernate 5 & JPA 2.2 support java.time.
Where to obtain the java.time classes?

*

*Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later  - Part of the standard Java API with a bundled implementation.

*

*Java 9 adds some minor features and fixes.

*Java SE 6 and Java SE 7

*

*Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.

*Android

*

*Later versions of Android bundle implementations of the java.time classes.

*For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….

Joda-Time
UPDATE: The Joda -Time project is now in maintenance mode, with the team advising migration to the java.time classes.

I was looking for a one-liner

Easy if using the Joda-Time 2.3 library. ISO 8601 is the default formatting.
Time Zone
In the code example below, note that I am specifying a time zone rather than depending on the default time zone. In this case, I'm specifying UTC per your question. The Z on the end, spoken as "Zulu", means no time zone offset from UTC.
Example Code
// import org.joda.time.*;

String output = new DateTime( DateTimeZone.UTC );

Output…
2013-12-12T18:29:50.588Z

A: java.time.Instant
Just use Instant of java.time.
    System.out.println(Instant.now());

This just printed:
2018-01-27T09:35:23.179612Z

Instant.toString always gives UTC time.
The output is usually sortable, but there are unfortunate exceptions. toString gives you enough groups of three decimals to render the precision it holds. On the Java 9 on my Mac the precision of Instant.now() seems to be microseconds, but we should expect that in approximately one case out of a thousand it will hit a whole number of milliseconds and print only three decimals. Strings with unequal numbers of decimals will be sorted in the wrong order (unless you write a custom comparator to take this into account).
Instant is one of the classes in java.time, the modern Java date and time API, which I warmly recommend that you use instead of the outdated Date class. java.time is built into Java 8 and later and has also been backported to Java 6 and 7.

A: Following the useful comments, I've completely rebuilt the date formatter. Usage is supposed to:

*

*Be short (one liner)

*Represent disposable objects (time zone, format) as Strings

*Support useful, sortable ISO formats and the legacy format from the box

If you consider this code useful, I may publish the source and a JAR in github.
Usage
// The problem - not UTC
Date.toString()
"Tue Jul 03 14:54:24 IDT 2012"

// ISO format, now
PrettyDate.now()
"2012-07-03T11:54:24.256 UTC"

// ISO format, specific date
PrettyDate.toString(new Date())
"2012-07-03T11:54:24.256 UTC"

// Legacy format, specific date
PrettyDate.toLegacyString(new Date())
"Tue Jul 03 11:54:24 UTC 2012"

// ISO, specific date and time zone
PrettyDate.toString(moonLandingDate, "yyyy-MM-dd hh:mm:ss zzz", "CST")
"1969-07-20 03:17:40 CDT"

// Specific format and date
PrettyDate.toString(moonLandingDate, "yyyy-MM-dd")
"1969-07-20"

// ISO, specific date
PrettyDate.toString(moonLandingDate)
"1969-07-20T20:17:40.234 UTC"

// Legacy, specific date
PrettyDate.toLegacyString(moonLandingDate)
"Wed Jul 20 08:17:40 UTC 1969"

Code
(This code is also the subject of a question on Code Review stackexchange)
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

/**
 * Formats dates to sortable UTC strings in compliance with ISO-8601.
 *
 * @author Adam Matan <adam@matan.name>
 * @see http://stackoverflow.com/questions/11294307/convert-java-date-to-utc-string/11294308
 */
public class PrettyDate {
    public static String ISO_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS zzz";
    public static String LEGACY_FORMAT = "EEE MMM dd hh:mm:ss zzz yyyy";
    private static final TimeZone utc = TimeZone.getTimeZone("UTC");
    private static final SimpleDateFormat legacyFormatter = new SimpleDateFormat(LEGACY_FORMAT);
    private static final SimpleDateFormat isoFormatter = new SimpleDateFormat(ISO_FORMAT);
    static {
        legacyFormatter.setTimeZone(utc);
        isoFormatter.setTimeZone(utc);
    }

    /**
     * Formats the current time in a sortable ISO-8601 UTC format.
     *
     * @return Current time in ISO-8601 format, e.g. :
     *         "2012-07-03T07:59:09.206 UTC"
     */
    public static String now() {
        return PrettyDate.toString(new Date());
    }

    /**
     * Formats a given date in a sortable ISO-8601 UTC format.
     *
     *

     *
     * final Calendar moonLandingCalendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
     * moonLandingCalendar.set(1969, 7, 20, 20, 18, 0);
     * final Date moonLandingDate = moonLandingCalendar.getTime();
     * System.out.println("UTCDate.toString moon:       " + PrettyDate.toString(moonLandingDate));
     * >>> UTCDate.toString moon:       1969-08-20T20:18:00.209 UTC
     *
     *

     *
     * @param date
     *            Valid Date object.
     * @return The given date in ISO-8601 format.
     *
     */

    public static String toString(final Date date) {
        return isoFormatter.format(date);
    }

    /**
     * Formats a given date in the standard Java Date.toString(), using UTC
     * instead of locale time zone.
     *
     *

     *
     * System.out.println(UTCDate.toLegacyString(new Date()));
     * >>> "Tue Jul 03 07:33:57 UTC 2012"
     *
     *

     *
     * @param date
     *            Valid Date object.
     * @return The given date in Legacy Date.toString() format, e.g.
     *         "Tue Jul 03 09:34:17 IDT 2012"
     */
    public static String toLegacyString(final Date date) {
        return legacyFormatter.format(date);
    }

    /**
     * Formats a date in any given format at UTC.
     *
     *

     *
     * final Calendar moonLandingCalendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
     * moonLandingCalendar.set(1969, 7, 20, 20, 17, 40);
     * final Date moonLandingDate = moonLandingCalendar.getTime();
     * PrettyDate.toString(moonLandingDate, "yyyy-MM-dd")
     * >>> "1969-08-20"
     *
     *

     *
     *
     * @param date
     *            Valid Date object.
     * @param format
     *            String representation of the format, e.g. "yyyy-MM-dd"
     * @return The given date formatted in the given format.
     */
    public static String toString(final Date date, final String format) {
        return toString(date, format, "UTC");
    }

    /**
     * Formats a date at any given format String, at any given Timezone String.
     *
     *
     * @param date
     *            Valid Date object
     * @param format
     *            String representation of the format, e.g. "yyyy-MM-dd HH:mm"
     * @param timezone
     *            String representation of the time zone, e.g. "CST"
     * @return The formatted date in the given time zone.
     */
    public static String toString(final Date date, final String format, final String timezone) {
        final TimeZone tz = TimeZone.getTimeZone(timezone);
        final SimpleDateFormat formatter = new SimpleDateFormat(format);
        formatter.setTimeZone(tz);
        return formatter.format(date);
    }
}

A: If XStream is a dependency, try:
new com.thoughtworks.xstream.converters.basic.DateConverter().toString(date)

A: Well if you want to use java.util.Date only, here is a small trick you can use:
String dateString = Long.toString(Date.UTC(date.getYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds()));

A: Why not just use java.text.SimpleDateFormat ?
Date someDate = new Date();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
String s = df.format(someDate);

Or see:
http://www.tutorialspoint.com/java/java_date_time.htm


text:
Q: Concurrent Akka Agents in Scala I'm working on a scala project right now, and I've decided to use Akka's agent library over the actor model, because it allows a more functional approach to concurrency.However, I'm having a problem running many different agents at a time. It seems like I'm capping at only having three or four agents running at once.
import akka.actor._
import akka.agent._
import scala.concurrent.ExecutionContext.Implicits.global

object AgentTester extends App {
// Create the system for the actors that power the agents
implicit val system = ActorSystem("ActorSystem")

// Create an agent for each int between 1 and 10
val agents = Vector.tabulate[Agent[Int]](10)(x=>Agent[Int](1+x))

// Define a function for each agent to execute
def printRecur(a: Agent[Int])(x: Int): Int = {
    // Print out the stored number and sleep.
    println(x)
    Thread.sleep(250)

    // Recur the agent
    a sendOff printRecur(a) _

    // Keep the agent's value the same
    x
}

// Start each agent
for(a <- agents) {
    Thread.sleep(10)
    a sendOff printRecur(a) _
}
}

The above code creates an agent holding each integer between 1 and 10. The loop at the bottom sends the printRecur function to every agent. The output of the program should show the numbers 1 through 10 being printed out every quarter of a second (although not in any order). However, for some reason my output only shows the numbers 1 through 4 being outputted.
Is there a more canonical way to use agents in Akka that will work? I come from a clojure background and have used this pattern successfully there before, so I naively used the same pattern in Scala.

A: My guess is that you are running on a 4 core box and that is part of the reason why you only ever see the numbers 1-4.  The big thing at play here is that you are using the default execution context which I'm guessing on your system uses a thread pool with only 4 threads on it (one for each core).  With the way you've coded this in this sort of recursive manner, my guess is that the first 4 agents never relinquish the threads and they are the only ones that will ever print anything.
You can easily fix this by removing this line:
import scala.concurrent.ExecutionContext.Implicits.global

And adding this line after you create the ActorSystem
import system.dispatcher

This will use the default dispatcher for the actor system which is a fork join dispatcher which does not seem to have the same issue as the default execution context you imported in your sample.
You could also consider using send as opposed to sendOff as that will use the execution context that was available when you constructed the agent.  I would think one would use sendOff when they had a case where they explicitly wanted to use another execution context.


text:
Q: Change password screen. Should we always require the old password? Consider an application using OpenIdConnect. The mobile devices store on their end the access token. My question is about the change password screen. Having a valid access token on the device should we:
1) require the user to enter his current password and twice the new password
or
2) we should only require entering the new password twice.
I am aware that it depends on the application and client requirements but if you are building an application for yourself what approach you are going to take?

A: From a general security practice, I would require entering the old password as well. This adds a layer of protection that confirms the user really is the owner of the account, and not someone who grabbed their phone while the app was open (e.g. their kid, their friend, etc.).
EDIT: I forgot to add this, but this method should have a back-up way of changing the password that provides a similar method of authentication, such as an email they supplied when creating their account. This way, if the user forgets their old password and wants to change it, they can use their email to validate it is them. Send a token (randomly generated numbers/letters) to the address in their account, then require that token to change their password, provided they enter it within a time limit*. After they enter the token, then only allow them to change their password, as opposed to seeing their old password or requiring they enter their old password.
*Note that the token should be sufficiently long (~10 chars) and the time period to enter it be relatively short(~10 min)-this makes it difficult to brute-force accounts.

A: you can use this method , if possible ,

*

*if you want to enter the current and new password , then when the user first log's in to app , you have to save username and password in Shared preference or DataBase (normally i use Shared Preferences ) in android and in IOS respective method (i don't no much about ios , i think its UserDetails in ios). and you can make it one time login application, every time you can do login using these details in the background in Splash Screen
change password screen , you can give current and new password , u can verify old password with the password which is stored in the Shared Preferences if they are same hit Change Password API to server . then on successful change password , change the password in the Shared Preferences also.

*if you don't want to store the password then you can directly give the new Password and Re-type New password  ,
its always better to ask the old password.
Hope it helps you

A: from my wn knowledge i know that all the big companies including facebook are asking for the old password as descriebed in the first option. the usage of this is to know 100% that you are changing the passwrod and not your little daughter or something that took over the control on youar account**.to avoid forgettig the password use the first option.**


text:
Q: How to capture an event when touching the external buttons of my android device? I want do an action when the user press the external button of a device.
I've googled and don't find many help.
Anyone have some idea?

A: Does this help?
public boolean onKey(View v, int keyCode, KeyEvent event) {
    switch (keyCode) {
        case KEYCODE_HOME:
//do whatever
        break;
        case KEYCODE_MENU:
//do whatever
        break;
        case KEYCODE_VOLUME_DOWN:
        case KEYCODE_VOLUME_UP:
        break;

      return true;
    }
    return false;
}


text:
Q: Find rotation angle (line tangential to ellipse) I want to find the rotation angle $\theta$ so that a line with given slope $m$ and y-intersect $t$ is tangential to an ellipse with a given minor axis $a$, major axis $b$ and center $h,k$. The rotation axis is the global z-axis.

Given:

*

*The blue ellipse with $a$,$b$ in a given reference state (center: $h=r+a, k=0$)

*The green line with $m$,$t$.

Todo:

*

*Rotate the green line around the origin until it is tangential to the blue ellipse (result is grey line) OR

*Rotate the blue ellipse until it is tangential to the green line (result is grey ellipse)

What I know:
(1) Equation of a straight line $$y=m*x+t$$
(2) Rotation around z-axis $$x'=x*\cos(\theta)-y*\sin(\theta)$$ $$y'=x*\sin(\theta)+y*\cos(\theta)$$
(3) Equation of a ellipse in the given reference state (blue ellipse) $$\frac{(x-h)^2}{a^2}+\frac{(y(x)-k)^2}{b^2}-1$$
I can find the implicit derivative of the ellipse $$\frac{d}{dx}y(x)=-\frac{b^2*(2*h-2*x)}{2*a^2*(k-y(x))}$$
and I know that this must be equal to the slope $m$ of the line. But here comes the problem. Not with the slope $m$ of the green line but with the slope $m$ of the rotated line (which is unknown, since I don't know the rotation angle.)
Can anybody help me to find what I'm missing? I think somehow I have to use equation 1 and 2 but I don't see how to solve for the angle $\theta$.
I would appreciate help very much.

A: HINT...When you rotate the green line by $\theta$ clockwise, to get the grey line, the equation of this line is $$y(\cos\theta+m\sin\theta)=x(m\cos\theta-\sin\theta)+t$$
This is of the form $y=Mx+C$, (assuming $\cos\theta+m\sin\theta \neq0)$.
If you solve this simultaneously with the equation of the ellipse $$\frac{(x-h)^2}{a^2}+\frac{y^2}{b^2}=1,$$
the resulting quadratic in $x$ must have double roots since the line is a tangent.
Putting the discriminant $=0$ results in the equation $$-2MCh-C^2+b^2-M^2h^2+a^2M^2=0$$
where $$M=\frac{m\cos\theta-\sin\theta}{\cos\theta+m\sin\theta}$$
and  $$C=\frac{t}{\cos\theta+m\sin\theta}$$
You then have an equation for  $\theta$ to solve.

A: Assume the ellipse is given by
$(r - r_0)^T Q (r - r_0) = 1$
where $r_0 = (h, k) $ and $Q$ is a positive definite matrix.
If the ellipse is in the standard orientation given in the problem then
$Q = \begin{bmatrix} \dfrac{1}{a^2} && 0 \\ 0 && \dfrac{1}{b^2} \end{bmatrix} $
Also we have the line.  Its equation is given by
$n^T (r - r_1) = 0$
where $n$ is the unit normal to the line, $n = ( - \dfrac{ m}{ \sqrt{m^2 + 1}} , \dfrac{1}{\sqrt{m^2 + 1}} ) = (\cos \theta_N , \sin \theta_N )$
and $r_1 = (0, t)$.
Now we'll rotate the ellipse about the origin of the coordinate system by an angle $\theta$.
The rotation matrix $R$ is given by
$R = \begin{bmatrix} \cos \theta && -\sin \theta \\ \sin \theta && \cos \theta \end{bmatrix} $
The image of a point $r$ on the ellipse is $r' = R r$. Therefore, $r = R^T r'$.  Plug this into the equation of the ellipse, this results in
$ (R^T r' - r_0)^T Q (R^T r' - r_0) = 1 $
which simplifies to
$(r' - R r_0)^T R Q R^T (r' - R r_0) = 1$
Rename $r'$ as $r$
$(r - R r_0)^T R Q R^T (r - R r_0) = 1$
Note that the center of the rotated ellipse is now $R r_0 $.
The normal vector to the rotated ellipse at a point $p$ on it is
$g = 2 R Q R^T (p - R r_0 )$
and we want this vector to be parallel to the normal vector to the line , which is vector $n$, so
$R Q R^T ( p - R r_0 ) = \alpha n$
from which
$p - R r_0 = \alpha R Q^{-1} R^T n$
Plug this into the ellipse equation, and you get
$\alpha = \dfrac{1}{\sqrt{ n^T R Q^{-1} R^T n } } $
So now the tangency point $p$ is known.  It is given by
$p = R r_0 + \dfrac{ R Q^{-1} R^T n } { \sqrt{ n^T R Q^{-1} R^T n } }$
So far we have found the point that has a tangent parallel to the line.  If this tangency point is on the line then
the following equation must be satisfied
$ ( p - R r_0) \cdot n = -n^T (R r_0 - r_1) \hspace{15pt} (*)$
The left hand side is the projection of the vector $(p - R r_0)$ along the normal vector $n$ , and the right hand side is the perpendicular distance between the center of the ellipse and the line.
Now the left hand side $= \dfrac{ n^T R Q^{-1} R^T n }{\sqrt{ n^T R Q^{-1} R^T n} } = \sqrt{ n^T R Q^{-1} R^T n } $
Hence, by squaring $ (*)$
$\begin{equation} \begin{split}
n^T R Q^{-1} R^T n &= (R r_0 - r_1)^T n n^T  (R r_0 - r_1) \\
&= r_0^T R^T n n^T R r_0 - 2 r_1^T n n^T R r_0 + r_1^T n n^T r_1\\
&= n^T R r_0 r_0^T R^T n - 2 n^T R r_0 r_1^T n + r_1^T n n^T r_1 \hspace{15pt} (**)\\
\end{split} \end{equation}  $
Define $u = R^T n = (\cos \phi, \sin \phi )$
(Note that since $u$ is a rotation of the unit vector $n$, it is also a unit vector)
Now equation $(**)$ becomes
$ u^T Q^{-1} u = u^T r_0 r_0^T u - 2 u^T (r_0 r_1^T n) + r_1^T n n^T r_1 $
And this is of the form
$ A \cos \phi + B \sin \sin \phi + C \cos (2 \phi) + D \sin (2 \phi) + E = 0$
and can be solved by introducing the transformation
$ z = \tan \dfrac{\phi}{2} $
which results in a quartic (4th degree) polynomial in $z$.
Find its roots, then find the corresponding $\phi$'s, $\phi_i = 2 \tan^{-1} z_i $ where $z_i$ is the $i$-th root of the quartic polynomial.
Once we have the $\phi$'s, we can find the rotation angles by noting that  $\phi = \theta_N - \theta $
where $\theta_N$ is the polar angle of the unit normal vector $n$.


text:
Q: Flutter : Not able to generate release apk in after migrating to AndroidX, getting error for camera plugin After migrate my app into AndroidX, I am able to generate and run debug apk in my flutter project, but when i try to build release apk, i am getting following error.
Running Gradle task 'assembleRelease'...
Running Gradle task 'assembleRelease'... Done                     293.0s (!)
The built failed likely due to AndroidX incompatibilities in a plugin. The tool is about to try using Jetfier to solve the incompatibility.
Building plugin camera...
Running Gradle task 'assembleAarRelease'...
Running Gradle task 'assembleAarRelease'... Done                    0.8s

FAILURE: Build failed with an exception.

* What went wrong:
A problem occurred configuring root project 'camera'.
> SDK location not found. Define location with sdk.dir in the local.properties file or with an ANDROID_HOME environment variable.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 0s

The plugin camera could not be built due to the issue above.

Flutter version : v1.12.13+hotfix.5.
Flutter channel : stable.
Compile SDK Version : 28.
Min SDK Version : 21.
Target SDK Version : 28.