text:
Q: Do I need Apple MFi certification to write an app that communicates with a Made for iPod car radio over USB? My car radio is Made for iPod and displays track info, can skip forward and backward, pause, play etc.
iTunes Match content does not appear when the radio takes control. Can I build an app that can transmit this info to the radio without being certified with MFi? I'm not sure of the correlation between ExternalAccessory.framework and the MFi program requirements.
For what it's worth, Pandora's iOS app sends track information over USB to my car radio, but other iOS music apps do not.  I am trying to figure out if it's a developer shortcoming or if Pandora is MFi certified.
Any ideas?

A: According to what I read at MFi Program Enrollment: Frequently Asked Questions the answer appears to be no, you don't need to join MFi:

I want to develop an iOS app that communicates with an MFi accessory.
  Do I need to join the MFi Program?
No. iOS app developers do not need to join the MFi program. Everything
  app developers need is in the External Accessory Framework, which is
  provided in the iOS SDK. To access the iOS SDK, please join the iOS
  Developer Program: https://developer.apple.com/programs/ios/.

Now getting the specs of your car radio in order to develop a matching App would be another thing altogether.


text:
Q: .tif and .tfw to GeoTIFF I have a .tiff and a .tfw file that I want to change into a GeoTIFF. When I try to open the file in ArcMap and ENVI 5.0, it is successful. However, in Google Earth it is not.
Is there anyway to create the GeoTiff in ArcMap or ENVI?

A: Install qgis, it uses gdal and the user interface it isn't so different from Esri sw

A: I like the QGIS answer, that's one way to get GDAL, and probably the least confusing.
The question was for ArcGis or ENVI, I can't comment on ENVI but in ArcGis use the Raster to Other Format tool which is available from ArcCatalog by selecting the rasters, right clicking, and selecting Raster to Other Format (multiple) from the popup menu. Select the output as TIFF and specify the output folder which will read and write the images from world tif to GeoTiff and as an added bonus, depending on your geoprocessing environments, will build pyramids and calculate statistics.
Don't forget to set the spatial reference for the images, either using Batch Define Spatial Reference or individually.

redpajama_set_name: RedPajamaStackExchange


text:
Q: getElementsByTagName, Retrieving Specific nodeValue from nodeValue with more than one Value My XML file looks like this:
<Charge ID="01010101">

    <Type>SHIPPING</Type>

    <Description>Shipping</Description>

    <Amount>8.9500</Amount>

</Charge>

<Charge ID="10101010">

    <Type>TAX</Type>

    <Description>Sales Tax</Description>

    <Amount>0.0000</Amount>

</Charge>

I can make an array out of this
$getcharge = $doc->getElementsByTagName("Charge");

$array = array();
foreach ($getcharge as $node) {
$array[] = $node;
}

Using print_r I can see the nodeValue is constructed like this
[nodeValue] =>

    SHIPPING

    Shipping

    8.9500

Along the same lines, I can make an array from these nodeValues using
foreach ($doc->getElementsByTagName("Charge") as $values) { {
    $result[] = $values->nodeValue;
}
}

Output is
Array
(
    [0] =>

        SHIPPING

        Shipping

        8.9500

    [1] =>

        TAX

        Sales Tax

        0.0000

)

These child nodes are confusing me because they are not in individual nodeValue's, as seen in the array. They are in fact all one nodeValue.
All I am trying to do is loop over Charge and get the <Type></Type> and <Amount></Amount> into variables.
How do I get the single instance of Type and Amount amidst a nodeValue with multiple attributes?

A: To get those batches of type, amount, description in each of those charges, you can already use $values as your context, you can also use the method ->getElementsByTagName again. Example:
foreach ($doc->getElementsByTagName("Charge") as $values) {
    // $values as each `Charge`
    $result[] = array(
        'id' => $values->getAttribute('ID'),
        'type' => $values->getElementsByTagName('Type')->item(0)->nodeValue,
        'description' => $values->getElementsByTagName('Description')->item(0)->nodeValue,
        'amount' => $values->getElementsByTagName('Amount')->item(0)->nodeValue,
    );
}


text: Q: Android native keyboard open(but the text written in white color in lenovo tab2 model) using unity3D for android Application This is screen shot in which the whole text is highlighted by selecting but I want this text in color black when I open the keyboard from my unity Application.check Image


text:
Q: Converting 2D integer matrix to binary tree I have a 2D integer matrix and I have to convert it into a tree, to perform matrix multiplication. Is there any way to do that.
Matrix:
   [[1 2 1]
   [2 1 2]
   [2 2 2]]

The matrix can square or rectangular.
I am trying to design an algorithm for getting the result of matrix multiplication, with better time complexity. Since most of the operations in binary tree are of 0(h).


text:
Q: How to draw multiple Imageview on Canvas with clicklistener I want to draw multiple Imageview on Canvas with clicklistener and set image view position using coordinate.
When I clicked on Imageview it's get image from folder and set.

A: get the uri of image,Set Imagematrix to imageview for set image at specific co-ordinates,For draw on canvas get drawable from imageview and draw it on canvas.
Alternate solution for get image from all imageview is set all imageview  under one parent view and get the drawable from parent view.


text:
Q: How to copy keys of another linux user being root Let's suppose we have 2 server. The server A and server B
The server A and B contain the following linux users 'carlos' and 'peter'
The linux user peter has its .ssh folder with id_rsa, id_rsa.pub and known_host files on server A.
After that, I logged in by putty with user carlos and I scaled to root user by sudo su.
So I wish to copy peter's key(s) from peter@A to peter@B using ssh-copy-id being root. Just in case, I don't know the peter's password on both servers.
Is there any way to copy these keys using ssh-copy-id or another linux command?

A: Just copy the file with scp, rsync, or any other program you are familiar with. There is nothing special with those files.
The ssh-copy-id program is a special tool for a special task, it doesn't fit your requirements.


text:
Q: Is it helpful to think of git syntax as being backwards? (at least for push) I was reading through this answer to a question. I've always worked with only one repository until now so I never thought much about the git syntax but this answer made me realize that git's syntax might be backwards to what's conventional. (at least for the push command)
As I understand it, in the accepted answer, @jweyrich makes a new repository called all which acts as a repository except it actually represents two repositories in his example. At the end he writes that we can push what we want to commit to the remote repository with git push all master.
If I'm understanding this correctly, git is the only api I know of where you specify <command> <dest> <source> as opposed to <command> <source> <dest>. Copying files, moving files, etc... Is all done with the latter syntax. Even AWS s3 buckets use the syntax <command> <source> <dest>.
Why does git seem to have backwards syntax? Am I one of the few that for whom this wasn't obvious when starting with git?

A: That's because you very often know what <source> is. 99% of the time, it's the current branch. So:
git push <destination>

is much easier to do than
git push <destination> <current_known_source>

I think git rebase presents a stronger case, though. To rebase <source> onto <destination>, I am almost always rebasing the current branch onto <destination>. Thus, I save the pain of specifying <source> each time:
git rebase <destination>


text:
Q: Apply a CSS or SASS rule to an element only if it has a specific child element I have a some HTML like so

i want the .parent to have a width of 300px only if it has a .child2 element.
Therefore the second .parent above would not have a width of 300px because it doesn't have a child with a .child2 class.
In CSS or SASS. i have no idea on how to approach this. And in my particular case, javascript is not an option


text:
Q: axios GET request returns undefined and not able to set value I am trying to set data received from a GET request from an API using axios. But the value which is getting set is undefined even though console.log gives me the correct output.
const[movie, setMovie] = useState({});

  useEffect(()=>{
   const baseURL = `https://api.themoviedb.org/3/movie/${id}?api_key=${API_KEY}`;
        async function getData(){
          try{
            const response = await axios.get(baseURL);
            console.log(response.data); //returns correct value
            setMovie(response.data); //sets undefined to the state movie
          }
          catch(error){
            console.error(error);
          }
        }
        getData();
        console.log(movie);//logs undefined
  },[]);

The API request returns an object when tested in POSTMAN as well as console.log(), but I am not able set that to the state.

A: In this scenario setMovie is asynchronous, So the console.log will return the value before the updates. In your case, it will return undefined. This is because the component is not re-rendering.
More info here

A: Here is what I did to set my state with the data received from the API request.

const[movie, setMovie] = useState({
    ImgPath: '',
    Title: '',
    ReleaseDate: '',
    Rating: '',
    Description: ''
  });

  useEffect(()=>{
   const baseURL = `https://api.themoviedb.org/3/movie/${id}?api_key=${API_KEY}`;
        axios.get(baseURL)
        .then(res => {
          console.log(res.data);
          let movieData = res.data;
          setMovie({
            ImgPath: movieData.poster_path,
            Title: movieData.title,
            ReleaseDate: movieData.release_date,
            Rating: movieData.vote_average.toString(),
            Description: movieData.overview
          })
        })
        .catch(err => console.error(err))
  }, []);


text:
Q: Maximize Scene with FXML - JavaFX2 I'm looking for a way to maximize a scene with FXML.
An equivalent to JFrame.setExtendedState(). The code primaryStage.setFullScreen(true)behaves differently.
    Screen screen = Screen.getPrimary();
    Rectangle2D bounds = screen.getVisualBounds();
    primaryStage.setX(bounds.getMinX());
    primaryStage.setY(bounds.getMinY());
    primaryStage.setWidth(bounds.getWidth());
    primaryStage.setHeight(bounds.getHeight());

This seems to do what I want , but I'd like to set the size with FXML. To keep GUI code separated from the logic! Thank you in advance, have a nice day!

A: I'm not sure if this is what you are looking, but you could try with
primaryStage.setMaximized(true);


text:
Q: Handling and printing exceptions with SML I have a code that looks quite like:
ignore
  (f ())
  handle
    AssertionError msg         => (print ("assertion error: " ^ msg ^ "\n"); ())
    | _ (* other exceptions *) => (print ("exception raised\n"); ())

But I need to print the generic exception message (with exnMessage?).
How do I catch the _ exception in order to get and print its message?

A: Match the exception with a name instead of _ and use exnMessage:
- (hd ([]: string list)) handle e => exnMessage e;
val it = "Empty" : string


text:
Q: as3 Cannot create same SimpleButton at the same time I make a tile-matching game, and the operation is picking three numbers of 3x3 grid that show 1~9, and if the sum of the three numbers are as same as the goal of target number( usually 6~24, 6=1+2+3, and 24=7+8+9), then the three numbers will disappear. While the three numbers disappear, three new random numbers will show up.
In my LIBRARY, I create 9 SimpleButton called btnO1~O9 as SimpleButton class respectively, and another 9 SimpleButton called btnC1~C9 as another class.
My idea to fulfill my game is:
In the initial of the game, there are 18 SimpleButton be created in the screen, half parts  are btnO1~btnO9, and another half parts are btnC1~btnC9, and I let btnC1~btnC9 be hidden. So it is like that:

When user press the button, it will turn to green color to let people know they pick up the number, like this:

Then just click one more time to cancel your option.
If the three number be picked up can match the goal showed above, then the three numbers will disappear, and your score will be added 500 points each time:

So far my game be made just like what I want, however, if I try to create new three numbers to take place the three disappeared numbers, I find that it will either show nothing be added or only one or two numbers be added......
While trying the reason of causing the problem, I found that if the numbers are same SimpleButton, then it cannot be create.
For example, if I have created btnO1 in the scene, then if I try to create another btnO1, even I set the different name of btnO1( the SimpleButton), to actionscript( I not sure whether it only occur in 3 or both 2 and 3), that will cause error or exception not show in debug window.
Is anyone know what's the problem of create same customized SimpleButton at the same time or is it can be soved?
My code is:
var goal:int=6+Math.random()*19;                // match number, 6~24 usually
txGoal.text=""+goal;
var numArr:Array=new Array(1,2,3,4,5,6,7,8,9);  // original 1~9 number
var pickArr:Array=new Array(0,0,0);             // array to find the position be clicked
var pickNum:Array=new Array(0,0,0);             // array to find the number be clicked
var count:int=0;                                // index for above array
var sum:int=0;                                  // check with goal
var score:int=0;
var canClick:Boolean=true;                      // can click only after anime stop
initNum();                                      // first round is 1~9, after first round will random
function initNum()
{
    for(var i:int=0;i<numArr.length;i++)
    {
        origin(numArr[i],i);
        clicked(numArr[i],i); // the trick for if number be clicked will show green one
    }
}

var bub:int=0;
var bubbleT:Timer = new Timer(25);
var newW:int=0;
var newH:int=0;
// Timer to do animation of disappear
bubbleT.addEventListener(TimerEvent.TIMER, bubbleoutHandler);
function bubbleoutHandler(event:TimerEvent):void
{
    bub++;
    for(var i:int=0;i<pickArr.length;i++)
    {
        var nam:String=pickArr[i]+"_"+pickNum[i];
        if(bub==1)
        {
            getChildByName("c"+nam).removeEventListener(MouseEvent.CLICK,cHandler); // remove the event of the three numbers
            removeChild(getChildByName("c"+nam)); // remove the three numbers
            getChildByName("o"+nam).visible=true; // show original number that do animation of disappear
            newW=getChildByName("o"+nam).width;
            newH=getChildByName("o"+nam).height;
            getChildByName("o"+nam).width=newW*(0.8); // change bubble's size smaller at first
            getChildByName("o"+nam).height=newH*(0.8);
        }
        else
        {
            var scale:Number=1+(bub*0.05);
            getChildByName("o"+nam).width=newW*scale; // change bubble's size bigger gradually as bubble will blow up
            getChildByName("o"+nam).height=newH*scale;
        }

        if(bub==4)
        {
            getChildByName("o"+nam).removeEventListener(MouseEvent.CLICK,oHandler); // remove event of origin numbers
            removeChild(getChildByName("o"+nam)); // remove numbers as it disappeared
        }
    }
    if(bub==4)
    {
        count=0;
        sum=0;
        bub=0;
        bubbleT.stop(); // the three numbers disappeared
        newT.start(); // try to new three numbers
    }
}
var bnew:int=0;
// timer to do animation of create new numbers
var newT:Timer = new Timer(100);
newT.addEventListener(TimerEvent.TIMER, bubblenewHandler);
function bubblenewHandler(event:TimerEvent):void
{
    bnew++;
    for(var i:int=0;i<pickArr.length;i++)
    {
        var newnum:int=Math.random()*9+1; // random number from 1~9
        var newpos=parseInt(pickArr[i]); // the new number should appear at original place
        origin(newnum,newpos);
        clicked(newnum,newpos);
    }
    // Originally do animation of adding new numbers, just change bubble size
        //var nam:String=pickArr[i]+"_"+pickNum[i];
        //var scale:Number=(bnew*0.2);
        //getChildByName("o"+nam).width=newW*scale;
        //getChildByName("o"+nam).height=newH*scale;

    if(bnew>=2)
    {
        canClick=true;
        bnew=0;
        newT.stop();
    }
}
// the function of create numbers( SimpleButton)
function origin(n:int,i:int)
{
    var o:SimpleButton;
    if(n==1)
        o=new btnO1();
    else if(n==2)
        o=new btnO2();
    else if(n==3)
        o=new btnO3();
    else if(n==4)
        o=new btnO4();
    else if(n==5)
        o=new btnO5();
    else if(n==6)
        o=new btnO6();
    else if(n==7)
        o=new btnO7();
    else if(n==8)
        o=new btnO8();
    else
        o=new btnO9();
    o.name="o"+i+"_"+n;
    o.x=numX(n);
    o.y=numY(n);
    o.tabEnabled=false;
    o.visible=true;
    o.addEventListener(MouseEvent.CLICK,oHandler);
    addChild(o);
}
// if press the number, the number turn to green, that means, origin number will hedden, and clicked number show up
function oHandler(e:Event):void{
    if(canClick==true)
    {
        e.currentTarget.visible=false;
        var nam:String=e.currentTarget.name.substr(1);
        getChildByName("c"+nam).visible=true;
        var val:int=parseInt(e.currentTarget.name.substr(3));
        var pos:int=parseInt(e.currentTarget.name.substr(1,1));
            // to record which three numbers be pressed
        pickNum[count]=val;
            // to record where the three numbers be pressed, then the new three numbers be created should take place the number in the same place.
        pickArr[count]=pos;
        count++;
        sum+=val;
            // if pressed three number that match the goal, do animation of disappear
        if(count==3)
        {
            if(sum==goal)
            {
                score+=500;
                txScore.text=""+score;
                canClick=false;
                bubbleT.start();
            }
        }
    }
}
// function of create green numbers, show up when user click origin numbers
function clicked(n:int,i:int)
{
    var c:SimpleButton;
    if(n==1)
        c=new btnC1();
    else if(n==2)
        c=new btnC2();
    else if(n==3)
        c=new btnC3();
    else if(n==4)
        c=new btnC4();
    else if(n==5)
        c=new btnC5();
    else if(n==6)
        c=new btnC6();
    else if(n==7)
        c=new btnC7();
    else if(n==8)
        c=new btnC8();
    else
        c=new btnC9();
    c.x=numX(n);
    c.y=numY(n);
    c.name="c"+i+"_"+n;
    c.tabEnabled=false;
    c.visible=false;
    c.addEventListener(MouseEvent.CLICK,cHandler);
    addChild(c);
}
// if user click the green number( SimpleButton) again, then cancel their option
function cHandler(e:Event):void{
    e.currentTarget.visible=false;
    var nam:String=e.currentTarget.name.substr(1);
    getChildByName("o"+nam).visible=true;
    var num:int=parseInt(e.currentTarget.name.substr(1,1));
    popout(num);
}
// pop out the numbers that user cancelled their option of the recording array
function popout(num:int)
{
    for(var i in pickArr)
    {
        if(pickArr[i]==num)
        {
            sum-=pickNum[i];
            pickNum[i]=0;
            pickArr[i]=0;
            count--;
            break;
        }
    }
}
// fix position of numbers
function numX(n:int)
{
    if(n==1||n==4||n==7)
        return 109.3;
    else if(n==2||n==5||n==8)
        return 274.3;
    else
        return 440.3;
}
function numY(n:int)
{
    if(n==1||n==2||n==3)
        return 161;
    else if(n==4||n==5||n==6)
        return 245;
    else
        return 330;
}
stop();

The code is in first frame, so I add stop() at final, I also remove event before I remove the old SimpleSutton.
The game link so far is:
The bubble of numbers
I'll add introduction page to thanks who help me in the game, thanks in advance!

A: What would happen if you defined the newT Timer in the code before you said: newT.start()?

A: I arrange my code again, and found that I was misunderstand!
The buttons are all correct be created, but they are overlapped.
Now I fix it, thanks to you, Craig!


text:
Q: OpenAM + two LDAP servers I'm a newbie in the LDAP + Liferay + OpenAM world, so I wonder if someone could point me in the right direction in a problem I have. In a real life environment, there are 2 LDAP servers, a OpenAM server and a Liferay application. What the customer needs is to authenticate users in Liferay against OpenAM, and OpenAM should use the LDAP servers. Problem is, the user exists only in one of the LDAP servers (it will be moved from one to the other in one point of the future). What the customer wants is:

*

*Users must be able to authenticate independently of what LDAP contains the user.

*The obtained token must be valid for both LDAP servers, as it will be used in a different service (I have no control over it) against only one of them to validate authentication.

As I said, I'm new to this world so, if the answer is too complex (I'm afraid it will be for me), maybe you could point me to books or docs that could resolve this scenario.
Thanks

A: You should configure LifeRay to use OpenAM for all authentications and you can configure OpenAM to use both LDAP servers (use different realms).
Details for OpenAM configuration will be in the OpenAM documentation.

A: As the previous answer states you should route all your authentication requests to the OpenAM server and let it validate the credentials against the right LDAP server. Using two different realms (one for each LDAP server) won't work in your case since that will require LifeRay to know where to find the user before hand. Also, sessions are linked to a specific realm.
There are multiple solutions to your problem. Here are just a couple:
Option 1
If you have control over the authentication flow. That is, if your application uses a custom UI and communicates with OpenAM via REST, you could create two different authentication module instances under a single realm (let's say two instances of the DataStore authentication module) each one pointing to a different LDAP server.
Let's call this module instances DataStore1 and DataStore2. Your application can collect the user credentials (username and password) and submit them to DataStore1. If authentication succeeds the user is already logged in. If it fails, the application can try with DataStore2.
Of course this is not ideal since you'll be making two authentication requests per login instead of just one.
Option 2
A better option (though more complicated to implement) would be creating a custom authentication module. This module can try authenticating the user against LDAP Server 1 and then try with LDAP Server 2 if the first authentication failed. Notice that with this option you don't need custom logic on the application side since it will only send a single authentication request to the OpenAM server. In fact, you can protect your application with an OpenAM Policy Agent.
Another advantage of this approach over Option 1 is that you can migrate your users behind the scenes assuming that the end goal is to migrate users from LDAP Server 1 to LDAP Server 2. If the first authentication succeeds your custom code could read the user entry from LDAP Server 1 and copy it over to LDAP Server 2.
Hope this helps you solve the problem.


text:
Q: Add sub tag into XML_VAR using FOR XML PATH resultset I try with a unique query to get a @xml_var with sub tag..but I've never done for a resulset of this king. Can someone give me some tip to get the right results?
Thnaks ALEN, Italy
FROM
 DECLARE @xml_var XML
    SET @xml_var =  (
                SELECT
                    nRiga as LineNumber,
                    nRiga as BuyersOrderLineReference,
                    skuFornitore as SuppliersProductCode,
                    '' as BuyersProductCode,
                    FR.quantita as Amount
                FROM Testate FT
                JOIN Righe FR
                       ON (FT.idOrdine = FR.idOrdine AND FR.idStato <> 'A')
                --WHERE FT.idOrdine = @idOrdine
                WHERE ft.idOrdine = 'XXXXXXXXXXXXXX'
                Order by fr.nRiga
                FOR XML PATH('OrderLine')
                )
    SELECT @xml_var

my result is like...
<OrderLine>
<LineNumber>1</LineNumber>
<BuyersOrderLineReference>1</BuyersOrderLineReference>
<SuppliersProductCode>PTN-9050</SuppliersProductCode>
<BuyersProductCode />
<Amount>2</Amount>
</OrderLine>

I need something like...
<OrderLine>
    <LineNumber Preserve="true">1</LineNumber>
    <OrderLineReferences>
        <BuyersOrderLineReference Preserve="true">1</BuyersOrderLineReference>
    </OrderLineReferences>
    <Product>
        <SuppliersProductCode>PTN-9050</SuppliersProductCode>
        <BuyersProductCode></BuyersProductCode>
    </Product>
    <Quantity>
        <Amount>2</Amount>
    </Quantity>
</OrderLine>

A: The following hard coded example returns the XML you seem to need:
It should be rather easy to get the values out of your tables instead.
Things might be different, if there is 1:n-data where I assume 1:1 data...
SELECT 'true' AS [LineNumber/@Preserve]
      ,1 AS LineNumber
      ,(
        --I assume this is 1:n
        SELECT 'true' AS [BuyersOrderLineReference/@Preserve]
              ,1 AS BuyersOrderLineReference
        FOR XML PATH('OrderLineReferences'),TYPE
       )
       ,'PT-9050' AS [Product/SuppliersProductCode]
       ,'' AS [Product/BuyersProductCode]
       ,2 AS [Quantity/Amount]
FOR XML PATH('OrderLine');

The result
<OrderLine>
  <LineNumber Preserve="true">1</LineNumber>
  <OrderLineReferences>
    <BuyersOrderLineReference Preserve="true">1</BuyersOrderLineReference>
  </OrderLineReferences>
  <Product>
    <SuppliersProductCode>PT-9050</SuppliersProductCode>
    <BuyersProductCode></BuyersProductCode>
  </Product>
  <Quantity>
    <Amount>2</Amount>
  </Quantity>
</OrderLine>


text:
Q: JSON web services issue when Invalid Login I have JSON web services, node name of web services is change when valid and invalid login.
I have written code of valid web services. Now when invalid login at that time node name change , SO How to identify valid and invalid authentication ?
valid login
{
root: [
{
Login: {
uid: "1",
uname: "aaa",
email: "aaa@far.com",
}
}
]
}

invalid login
{
root: [
{
Result: {
Result: "Login failed"
}
}
]
}

Code is working when valid login , my problem is that when invalid login at that how to check ?
Becuase node name is change from "Login" to "Result"
        Toast.makeText(getApplicationContext(), result,
          Toast.LENGTH_LONG).show();

        Log.e("log_tag", "root :" + result.toString());

        JSONObject json_data = new JSONObject(result);

        String root = json_data.getString("root");

        Toast.makeText(getApplicationContext(), root, Toast.LENGTH_LONG).show();

        JSONArray json_array = new JSONArray(root);

        json_data = json_array.getJSONObject(0);

        String Login = json_data.getString("Login");

        Toast.makeText(getApplicationContext(), Login, Toast.LENGTH_LONG).show();

        json_data = new JSONObject(Login);

        String email = json_data.getString("email");

        Toast.makeText(getApplicationContext(), email, Toast.LENGTH_LONG).show()

A: Parse and read the result this way:
JSONObject json_data = new JSONObject(result);
JSONObject root = json_data.getJSONArray("root").getJSONObject(0);
if (root.has("Result")) {
    JSONObject loginRes = root.getJSONObject("Result");
    if (loginRes.has("Result")) {
         String status = loginRes.getString("Result");
         if (status.equalsIgnoreCase("Login failed")) {
             // LOGIN FAILED!
         }
    }
}

Note: your JSON seems poorly (logically) formatted, and contains some unnecessary items. You may want to simplify it.


text:
Q: How can I find out where a file is physically located on the disk (block numbers)? This is an obscure question, I know.  I'm trying to do some performance testing of some disks on a Linux box.  I'm getting some inconsistent results, running the same test on the same disk.  I know that disks have different performance depending on which part of the disk is being accessed.  In particular, reads and writes to the outside of the disk have much higher throughput than reads and writes to the inside part of the disk, due to near-constant data density and constant rotational speed.
I'd like to see if my inconsistencies can be attributed to this geometry-induced variance in throughput.  Is it possible, using existing tools, to find out where on the disk a file has been placed?
If not, I suppose I can write something to directly seek, read, and write to the device file itself, bypassing (and destroying) the filesystem, but I'm hoping to avoid that.  I'm currently using ext4 on a 3.0 kernel (Arch Linux, if it matters), but I'm interested in techniques for other filesystems as well.

A: You could use debugfs for this:
debugfs -R "stat ~/myfile" /dev/hda1

Change the hard/partition drive accordingly and make sure the drive is unmounted.
You will get a list with all the blocks used:
BLOCKS:
(0):1643532
TOTAL: 1

A: This thread may give you some insight into ext4 file placement algorithm.
debugfs has a bmap function, which seems to give the data you want. You should be able to give it consecutive blocks of a file and get the physical block numbers.

A: The question is rather old, but there is another answer that could be useful for those finding this on Google: filefrag (in Debian it is inside package e2fsprogs).
# filefrag -eX /usr/bin/aptitude
Filesystem type is: ef53
File size of /usr/bin/aptitude is 4261400 (1041 blocks of 4096 bytes)
 ext:     logical_offset:        physical_offset: length:   expected: flags:
   0:        0..     1fa:    15bd805..   15bd9ff:    1fb:
   1:      1fb..     3f2:    15c6608..   15c67ff:    1f8:    15bda00:
   2:      3f3..     410:    15c8680..   15c869d:     1e:    15c6800: last,eof
/usr/bin/aptitude: 3 extents found

It has the advantage that it works also for other filesystems (I used it for UDF), which do not appear to be supported by other tools described here.
The offset presented in the output are meant to be in multiple of the block size written in the second line (4096 here). Beware that logical offsets might not be contiguous, as a file can have holes in it (when supported by the filesystem).

A: You can use the FIBMAP ioctl, as exemplified here, or using hdparm:
/ $ sudo /sbin/hdparm --fibmap /etc/X11/xorg.conf

/etc/X11/xorg.conf:
 filesystem blocksize 4096, begins at LBA 0; assuming 512 byte sectors.
 byte_offset  begin_LBA    end_LBA    sectors
           0    1579088    1579095          8


text:
Q: How does a cpumask affect scheduling of other processes in the linux kernel? I'm using a linux 2.6.x kernel on my machine which has ubuntu installed (Ubuntu is just mentioned in case this changes anything). The kernel runs on a machine that has 8 cores. The machine also runs openvz but I don't think this does change the context of the question.
I have a software installed that allows only the usage of two CPUs and it sets a hard CPU affinity on the first both CPUs (cpumask 3). I'm asking myself how the scheduling of the other processes is affected by this. I think I read something about it but I assume for now that processes are likely to be attached to the first CPUs. And the kernel tries to keep the processes on the same CPU always to avoid cache invalidation.
On the machine there are quite a few processes running. How does the kernel handle this situation? Can it be the hard CPU affinity proceses are running slower because they are affected while being bound to a crowded zone? How does the kernel care about the hard affinity.

A: What will happen in the long run is that the load balancing code of the scheduler will move more of the unbound tasks to the rest of the CPUs to account for this task being bound to the first two.
The way it works is that each task starts on the CPU where it was created and at the micro level the Linux task scheduler does scheduling decisions on each CPU without regard for the others. But then there is the more macro level process migration load balancing code that will step up and say: "the run queue (list of processes waiting to be scheduled) on this cpu is longer than that cpu, let's move some over to balance the loads".
Of course, since your specific task is bound to the first two cpus the load balance will pick other tasks to move - so your bound task will in the long run will "push out" enough of the other non bound tasks to the other cpus and balance will be preserved.


text:
Q: Date format to match the Date format in Phone Settings I have a string which returns the date and time as 2012-11-08 12:45:30 . I need to get the date and time in separate strings and then the date has to be shown in the format which is there in the Phone's Date and Time settings.
Here is the code which I have tried so far:
date value from db is 2012-11-08
I am getting the date format in phone's settings as
String datefrmt = Settings.System.getString(
                context.getContentResolver(), Settings.System.DATE_FORMAT);

the code to apply this format to the obtained date from db is:
SimpleDateFormat sdf = new SimpleDateFormat(datefrmt);
java.util.Date date_1 = sdf.parse("2012-11-08");
String s = sdf.format(date_1);

I am getting the month and day properly but the year its returning something randomly and thats not a correct value. Can anyone please guide me where am I going wrong. Thanks

A: you can use the simpleDateFormat as:
 SimpleDateFormat simpDate = new SimpleDateFormat(datefrmt,
                    Locale.ENGLISH);
  String s = simpDate.format(new Date());

for reference, you can refer to developer site:
for more information refer this link

A: Since your DB date is in yyyy-MM-dd, don't use the dynamic format to get the date, otherwise it will crash(throw parse exception), instead use the static format as below to get the date. You may use the dynamic format to convert the string as below:
   //use static format to convert into date from static formatted data in db
   SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
   java.util.Date date_1 = sdf1.parse("2012-11-08");//got the date

   //use the dynamic format to convert into string
   SimpleDateFormat sdf2 = new SimpleDateFormat(datefrmt);
   String s = sdf2.format(date_1);

A: If you have  2012-11-08 12:45:30 string and you want to parse it to Date object and change its format to another (system format for example or 2012-11-08 format):
try {
        String yourString="2012-11-08 12:45:30";

        //first we parse input date string and create Date object
        String inputDateString ="yyyy-dd-MM hh:mm:ss";
        SimpleDateFormat inputDateFormat = new SimpleDateFormat(inputDateString);
        java.util.Date  date = inputDateFormat.parse(yourString);

        //log
        Log.e(getClass().getName(), inputDateFormat.format(date));

        //create system date format
        String dateformt = Settings.System.getString( this.getContentResolver(), Settings.System.DATE_FORMAT);
        //if its for some reason==null let it be "yyyy-dd-MM"
        if(dateformt==null){
            dateformt="yyyy-dd-MM";
        }
        SimpleDateFormat systemDateFormat = new SimpleDateFormat(dateformt);
        String outputString = systemDateFormat.format(date);

        //log
        Log.e(getClass().getName(), outputString);
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

A: Since final String format = Settings.System.getString(getActivity().getContentResolver(), Settings.System.DATE_FORMAT);//may be NULL
So I customized my function as below for general purposes
@SuppressLint("SimpleDateFormat")
public String getCurrentShortDateFormat() {
    final String[] SFs = new String [] {
            "MM/dd/yyyy",
            "dd/MM/yyyy",
            "yyyy/MM/dd"
    };

    final Date date = new Date(24638400000L);//24638400000=Oct/13/1970; 0==Jan/1/1970
    java.text.DateFormat shortDateFormat = android.text.format.DateFormat.getDateFormat(getActivity().getApplicationContext());
    String current = shortDateFormat.format(date);
    SimpleDateFormat which = new SimpleDateFormat();
    for (int i = 0; i < SFs.length; i++) {
        which.applyPattern(SFs[i]);
        if (which.format(date).compareTo(current)==0)
            return SFs[i];
    }
    return null;
}

@Override
public void onResume() {
    super.onResume();
    Log.d(LOG_TAG, "----- onResume.CurrentShortDateFormat-----" + getCurrentShortDateFormat());
}


text:
Q: Text under a widget added with QToolbar.addWidget() I have a QToolbar with toolButtonStyle set to Qt::ToolButtonTextUnderIcon in which I add a QLineEdit through addWidget(). I'd like to have descriptive text under that widget like I do with other buttons, but I don't know how to do it or if it's even possible. I tried:
lineEdit = QLineEdit()
action = self.toolBar.addWidget(lineEdit)
action.setText("Some Text")

But it doesn't work. Is it possible at all? If not, are there special techniques I don't know about to put text under that widget in a way that it's aligned with the other labels regardless of the style?

A: toolButtonStyle refers to buttons' label position only, while you're adding a QLineEdit.
To put a label under your line edit try arranging a layout, a QVBoxLayout for example


text:
Q: I want convert 'content://0@media/external/file/147' to file:///storage/sdcard0/files/X.pdf` in android? Uri fileUri = getIntent().getData();
        if (!fileUri.getPath().contains("external") && fileUri.getScheme().equals("content")) {
            Cursor cursor = getContentResolver().query(fileUri, null, null, null, null);
            try {
                if (cursor != null && cursor.moveToFirst()) {
                    fileName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
                }
            } finally {
                cursor.close();
            }
        }if (!fileUri.getPath().contains("external") && fileUri.getScheme().equals("file")) {
            List<String> pathSegments = fileUri.getPathSegments();
            if (pathSegments.size() > 0) {
                fileName = pathSegments.get(pathSegments.size() - 1);
            }
        }


text:
Q: Question about poles of the Lerch Transcendent The Lerch Transcendent is defined as the analytic continutation of the sum
$$
\Phi(z,s,a)=\sum_{k=0}^\infty(k+a)^{-s}z^k.
$$
According to Wolfram functions, for fixed $s$, $a$, the function $\Phi(z,s,a)$ has no poles or essential singularities. But consider,
$$
\Phi(z,-1,1)=\frac{1}{(1-z)^2},
$$
which clearly has a pole at $z=1$.  Is the information on the Wolfram functions site incorrect or am I missing something?

A: According to Maple documentation:

*

*If $v$ and $a$ are positive integers, $\Phi(z, a, v)$ has a branch cut in the $z$-plane along the real axis to the right of $z=1$, with a branch point at $z=1$.

*If $a$ is a non-positive integer, $\Phi(z, a, v)$ is a rational function of $z$ with a pole of order $1−a$ at $z=1$.

It doesn't say what happens for non-integer $a$, but I suspect a branch point at $z=1$.


text:
Q: How to open the current file at the current line in a text editor from GDB? Doing l and l - all the time is inconvenient, and misses feature like syntax highlight and jumping to definitions.
How to I run an external command that opens an editor (possibly a CLI editor like Vim) on the current file, at the current line?
I already know about editor plugins integrations as mentioned at: https://vi.stackexchange.com/questions/2046/how-can-i-integrate-gdb-with-vim or Eclipse, but opening the editor from GDB has the advantage that it should work with any editor, and is more lightweight, and therefore less likely to break. The cost is worse integration, e.g. can't set breakpoints from editor, but I'm fine with that.

A: The edit command, with no arguments, will do what you want.

A: Method that automatically centers lines
This Python GDB script is like edit, but it also centers Vim on the current line:
class Vim(gdb.Command):
    """
Open current file in vim at a the current line.
"""
    def __init__(self):
        super().__init__('vim', gdb.COMMAND_FILES)
    def invoke(self, argument, from_tty):
        sal = gdb.selected_frame().find_sal()
        call(['vim', sal.symtab.fullname(), '+{}'.format(sal.line), '+normal! zz'])
Vim()

The Vim CLI arguments are explained at: How can I open vim with a particular line number at the top?
The sal GDB Python object is documented at: https://sourceware.org/gdb/onlinedocs/gdb/Symbol-Tables-In-Python.html#Symbol-Tables-In-Python
Unfortunately I could not use vim --remote properly because I could not pass the current line: How to send commands to gvim when using --remote?


text:
Q: Curious loss in a CNN in my CNN for image classification, I get a curious loss and I don't know what's wrong. I'm lucky, if you help me to find the failure.
Here is a cutout of my print output and at the end there is my code:
Train Epoch: 1 [0/2048 (0%)]    Loss: 0.654869
Train Epoch: 1 [64/2048 (3%)]   Loss: 0.271722
Train Epoch: 1 [128/2048 (6%)]  Loss: 0.001958
Train Epoch: 1 [192/2048 (9%)]  Loss: 0.003399
Train Epoch: 1 [256/2048 (12%)] Loss: 0.000000
Train Epoch: 1 [320/2048 (16%)] Loss: 0.006664
Train Epoch: 1 [384/2048 (19%)] Loss: 0.000000
Train Epoch: 1 [448/2048 (22%)] Loss: 0.000000
Train Epoch: 1 [512/2048 (25%)] Loss: 0.000000
Train Epoch: 1 [576/2048 (28%)] Loss: 0.000000

Train Epoch: 2 [0/2048 (0%)]    Loss: 173505.656250
Train Epoch: 2 [64/2048 (3%)]   Loss: 0.000000
Train Epoch: 2 [128/2048 (6%)]  Loss: 0.000000
Train Epoch: 2 [192/2048 (9%)]  Loss: 33394.285156
Train Epoch: 2 [256/2048 (12%)] Loss: 0.000000
Train Epoch: 2 [320/2048 (16%)] Loss: 0.000000

Train Epoch: 2 [960/2048 (47%)] Loss: 0.000000
Train Epoch: 2 [1024/2048 (50%)]        Loss: 636908.437500
Train Epoch: 2 [1088/2048 (53%)]        Loss: 32862667387437056.000000
Train Epoch: 2 [1152/2048 (56%)]        Loss: 15723443952412777718762887446528.000000
Train Epoch: 2 [1216/2048 (59%)]        Loss: nan
Train Epoch: 2 [1280/2048 (62%)]        Loss: nan
Train Epoch: 2 [1344/2048 (66%)]        Loss: nan
Train Epoch: 2 [1408/2048 (69%)]        Loss: nan

Here, you see code for the training.
def trainM(epoch):
    model.train()
    for batch_id, (data, target) in enumerate(net.train_data):
        target = torch.LongTensor(target[64*batch_id:64*(batch_id+1)])
        data = Variable(data)
        target = Variable(target)
        optimizer.zero_grad()

        out = model(data)
        criterion = F.nll_loss

        loss = criterion(out,target)
        loss.backward()
        optimizer.step()

        print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(epoch,batch_id*len(data), len(net.train_data)*64, 100*batch_id/len(net.train_data), loss.item()))

for item in range(1,10):
    trainM(item)

That's the code for neural network and the end there is the dataPrep method for data preparation.
train_data = []
target_list = []
class Netz(nn.Module):
    def __init__(self):
        super(Netz, self).__init__()
        self.conv1 = nn.Conv2d(1, 10,kernel_size=5)
        self.conv2 = nn.Conv2d(10,20, kernel_size = 5)
        self.conv_dropout = nn.Dropout2d()
        self.fc1 = nn.Linear(1050,60)
        self.fc2 = nn.Linear(60,2)
        self.fce = nn.Linear(20,1)

    def forward(self,x):
        x = self.conv1(x)
        x = F.max_pool2d(x, 2)
        x = F.relu(x)
        x = self.conv2(x)
        x = self.conv_dropout(x)
        x = F.max_pool2d(x,2)
        x = F.relu(x)
        x = x.reshape(x.shape[0], x.shape[1], -1)
        x = F.relu(self.fc1(x))
        x = self.fc2(x)
        x = self.fce(x.permute(0,2,1)).squeeze(-1)
        return F.log_softmax(x, -1)

def dataPrep(list_of_data, data_path, category, quantity):
    global train_data
    global target_list
    train_data_list = []

    transform = transforms.Compose([
    transforms.ToTensor(),
        ])

    len_data = len(train_data)
    for item in list_of_data:
        f = random.choice(list_of_data)
        list_of_data.remove(f)
        try:
            img = Image.open(data_path +f)
        except:
            continue
        img_crop = img.crop((310,60,425,240))
        img_tensor = transform(img_crop)
        train_data_list.append(img_tensor)

        if category == True:
            target = 1
        else:
            target = 0
        target_list.append(target)

        if len(train_data_list) >=64:
            train_data.append((torch.stack(train_data_list), target_list))
            train_data_list = []

        if (len_data*64 + quantity) <= len(train_data)*64:
            break
    return list_of_data

A: I might also suggest that the network needs to be initialized with random parameters for the convolutional layer weights. By default these weights are 0, which probably means that you end up predicting all one class. This might explain the very low (0) or very high losses (based on the makeup of the particular batch).

A: You can try multiples approach to solve that.

*

*Try to reduce the learning rate, try between 1e-03 to 1e-04

*Clip the gradient, modify your code with something like:

def trainM(epoch):

    ...

    # Backward
    loss.backward()
    torch.nn.utils.clip_grad_norm_(self.net.parameters(), max_norm=1)
    self.optim.step()

    ...

*Change data normalization, try both min-max and Z-Score normalization

Other than that, I can see that your model reaches convergence very fast (the loss goes to zero pretty soon), and your task might be too easy. You can then reduce the number of iterations.


text:
Q: Как добавить свою кнопку в Contact Form 7?

       отправить

При добавлении классов кнопки в шорткод, подхватывает их, но не корректно. Скорее всего из-за псевдоклассов after и befor, могу ошибаться. Какие ещё могут быть варианты, ну кроме создания своей формы, чтобы кнопка работала в созданной форме Contact Form 7?


text:
Q: Django tabular inline display Is it possible to change the display of inlines in order to change it to this? I was thinking of changing the admin template file "tabular.html", is it going to be possible or should I change something else?
Update
Ok, I've been trying to edit the tabular.html but my experience with Django isn't enough to understand how/where to make the necessary changes... Any clue of where I should start?
Shouldn't I be changing the CSS also?
I guess that {{ field.field }} automatically renders the dropdown menu (Django admin default) if I'm understand this correctly...
Update 2
I was able to change the second column to the functionality that I wanted but I think that for the first one it's going to be trickier... Current status
Update 3
One hack that I think would work is to display on each of the inlines only one of the options of the first field and then deactivate the "add another option". How can I iterate on the options in "tabular.html" ?
Update 4
I guess the trick should be done here... How can I iterate on the field choices in order to display only one choice per line?
{% for fieldset in inline_admin_form %}
          {% for line in fieldset %}
            {% for field in line %}
            {{ field.get_choices_display }}

              {% if field.is_readonly %}

{{ field.contents }}

              {% else %}
                  {{ field.field.errors.as_ul }}
                  {{ field.field }}
              {% endif %}

            {% endfor %}
          {% endfor %}
        {% endfor %}

A: Yes, you could change template of your InlineModelAdmin instance to your customized template, for example customized_inline.html. Simply copy django/django/contrib/admin/templates/admin/edit_inline/tabular.html to customized_inline.html in your template path as starting.
edit
Perhaps I was misunderstanding. If you want to change the rendering style of a form field, the normal way is to change its widget. In Django ModelAdmin and InlineModelAdmin, the main ways of customizing a field widget goes around BaseModelAdmin.formfield_for_dbfield method inside django/contrib/admin/options.py, reading the code and the doc when you want to change the widget of a form field.
For field having choices, you could simply set radio_fields in ModelAdmin/InlineModelAdmin instance to render the field as radio select instead of dropdown.
Furthermore, use OneToOneField instead of ForeignKey, or set extra and max_num in your InlineModelAdmin instance to prevent admin from rendering multiple rows of inline, like:
class SomeInlineAdmin(admin.TabularInline):
    model = Foo
    extra = 1
    max_num = 1

I cannot open your second link, you could post things in the question instead of using a external link.


text:
Q: RecordCont returns the pointer to current record and not the number frecords I'm working on access 2003.
In a routine called by a click in Form button , i tried to retrive the result of a query
an make some operation with them.
In every place ( also MS online documentation) is explained that to
retrive the number of record in a recordset u must use RecordCount metod on recordset instance.
I wonder why executing the following code I obtain the number of the current position of the cursor;
also, why the record set is not filtered ?
Dim db As DAO.Database
Dim rs As DAO.Recordset
Set db = CurrentDb()
Set rs = db.OpenRecordset("Query42")
Dim IdImp As Integer
Dim x As Integer

x = rs.RecordCount 'x= 1 (rs pints to the first record)

rs.Filter = "[IdImp]= 125 "

' I move to first and then to last
' to understend what happens in the recordset and to make some test on RecordCount
 rs.MoveFirst
 x = rs.RecordCount 'x= 1 (rs points to the first record)
 rs.MoveLast
 x = rs.RecordCount 'x= 1234 (rs points to the last record)
 ' so to have recordCount= number of records i must first execute move.last...?

I don't work vary much on vbasic , but somtimes i'd like to use acces for simple and rapid develop personal database, but oftne it  lokks to make lose a lot of time...
Tankyyou for any help..

A: RecordCount returns the number of records accessed so far.  Use the MoveLast method before calling RecordCount to ensure all the records are loaded before you count.
For the filter, either set it before opening the recordset, or reopen the recordset after setting the filter:
rs.Filter = "[IdImp] = 125"
Set rs = db.OpenRecordset("Query42")

or
rs.Filter = "[IdImp] = 125"
rs.OpenRecordset


text:
Q: C# thread locking and using a lock object; what should the correct scope be for the lock object? Is there a difference between using a lock object that is declared as a field of a class as opposed to local scope?
For example:  Is there a difference between using lockObject1 or lockObject2 in the below example?
public class Test()
{
   private Object lockObject1 = new Object();

   public void FooBar()
   {
       lock(lockObject1)
       {
          //Thread safe area 1
       }

       var lockObject2 = new Object();
       lock(lockObject2)
       {
           //Thread safe area 2
       }
   }
}

It seems like most examples always seem to glaze over the importance of scoping of the chosen lock object.

A: The local lock object will not really be providing any thread safety since multiple threads running FooBar will each have their own object rather than sharing a single object for locking. (Sadly, I have seen this very thing in code headed toward production before I raised the issue and got it corrected in time.)

A: You should always use a private static member variable if you want to lock all instances of an object. Use a non-static private member if you want to lock a specific instance.
Never use a publicly visible member, or 'this', as you never know when someone else is going to use it for their own lock, and possibly cause deadlocks.
public class Test()
{
   private static Object lockObjectAll = new Object();
   private Object lockObjectInstance = new Object();

   public void FooBar()
   {
       lock (lockObjectAll)
       {
          // Thread safe for all instances
       }

       lock (lockObjectInstance)
       {
          // Thread safe for 'this' instance
       }
   }
}

A: your lockObject2 won't protect anything since, it's not going to be locked anywhere else. Do note that multiple calls to FooBar by different threads will not be protected since it's a new instance each time FooBar is called. Also, do note that lockObject1 isn't much better. It allows locking between calls on the same instance. This is good if it's only member variables being accessed. But if some global resource is being accessed, lockObject1 won't protect fully since each instance of the class has its own instance. As suggested by @Haoest, making lockObject1 static should fix this problem.

A: Make lockObject1 static and you should be alright.
lockObject2 should also be static field to be effective.


text:
Q: Handling PagerTitleStrip click in compatibiliy Fragment-based ViewPager I have a compatibility ViewPager with an embedded PagerTitleStrip element and it works fine but clicks on the PagerTitleStrip do not switch to the corresponding view as expected. I have looked through the docs but the widget does not have any built-in methods for attaching onClickListeners to the PagerTitleStrip object. This seems a bit weird since that is probably what most people would expect.
So the question is how would I make the title strip clickable?
I am also trying to figure out if there is a way to show a thick underline under the selected title strip without adding a TabHost if at all possible.
Here is the code:
Main layout view_pager.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <android.support.v4.view.ViewPager
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/my_view_pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >

        <android.support.v4.view.PagerTitleStrip
            android:id="@+id/pager_title_strip"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="top"
            android:background="#ccc"
            android:textColor="#fff" />
    </android.support.v4.view.ViewPager>

</LinearLayout>

The two fragment layouts that go into the ViewPager:
fragment_connect.xml (the second is identical so not included)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/text_view_connect"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="connect"
        android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>

The main activity class StandardViewPagerActivity.java:
package com.example.standardviewpager;

import java.util.List;
import java.util.Vector;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.PagerTitleStrip;
import android.support.v4.view.ViewPager;
import android.view.Menu;

public class StandardViewPagerActivity extends FragmentActivity {

    private MyPagerAdapter pagerAdapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.view_pager);
        ViewPager myPager = (ViewPager) findViewById(R.id.my_view_pager);
        PagerTitleStrip pagerStrip = (PagerTitleStrip) findViewById(R.id.pager_title_strip);
        // TODO: add underline for selected title strip
        myPager.setAdapter(pagerAdapter);
        myPager.setCurrentItem(0);
        initialisePaging();
    }

    private void initialisePaging() {

        List<Fragment> fragments = new Vector<Fragment>();
        fragments.add(Fragment.instantiate(this, ConnectFragment.class.getName()));
        fragments.add(Fragment.instantiate(this, ProfilesFragment.class.getName()));
        this.pagerAdapter = new MyPagerAdapter(super.getSupportFragmentManager(), fragments);
        ViewPager pager = (ViewPager) super.findViewById(R.id.my_view_pager);
        pager.setAdapter(this.pagerAdapter);
    }
}

The adapter class MyPagerAdapter.java:
package com.example.standardviewpager;

import java.util.List;

import android.os.Parcelable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;

public class MyPagerAdapter extends FragmentPagerAdapter {

    private List<Fragment> fragments;

    public MyPagerAdapter(FragmentManager supportFragmentManager, List<Fragment> fragments) {
        super(supportFragmentManager);
        this.fragments = fragments;
    }

    @Override
    public int getCount() {
        return this.fragments.size();
    }

    @Override
    public void destroyItem(View arg0, int arg1, Object arg2) {
        ((ViewPager) arg0).removeView((View) arg2);
    }

    @Override
    public Parcelable saveState() {
        return null;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return String.format("Title %d", position);
    }

    @Override
    public Fragment getItem(int position) {
            return this.fragments.get(position);
    }
}

And, finally, the two identical Fragment implementations, including only the first - ConnectFragment.java.
package com.example.standardviewpager;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

public class ConnectFragment extends Fragment {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.fragment_connect, container, false);
        TextView textView = (TextView) layout.findViewById(R.id.text_view_connect);
        textView.setText("onCreateView() Connect");
        return (View)layout;
        }
}

A: I suppose this is way too late and the OP must have moved on,but for those who just came here searching for a tiny widget ,please find my fork here

A:
So the question is how would I make the title strip clickable?

You fork it and make your own implementation that is clickable. Or, you switch to PagerTabStrip, which is clickable. Or, you switch to one of the ViewPagerIndicator indicators, one that happens to be clickable and has a look that you like.
Quoting the documentation for PagerTitleStrip:

PagerTitleStrip is a non-interactive indicator of the current, next, and previous pages of a ViewPager... For an interactive indicator, see PagerTabStrip.

A: I would also add a note for others (like me) who came here wanting to make the PagerTitleStrip clickable for other reasons. You can indeed make it clickable. To do so you make it clickable in the xml and add an "onClick" xml line that points to a function (just like you would with a normal button).
The key from that point is that you'll then want to know what page you're on based on that click because the behavior will probably change. In that case the following line will get you the current item for use in your subsequent code (displaying a Toast message in my case).
    int CurrentItem = this.mViewPager.getCurrentItem();


text:
Q: Perceptron Classifier in MATLAB Im trying to figure out perceptron classifier algorithm.So as i research i create random problem like this.I want  to see the result on matlab.
For example i have  the energy values (1st feature) and zero-crossing numbers (2nd feature) for two classes
of sounds namely:
Class-1: Voiced sounds and
Class-2: Unvoiced sounds.
Voiced Sound Vectors:
 [16 4] , [11 6] , [13 8] , [21 7] , [16 6] , [19 9] , [21 5] , [26 6] , [22 10] , [24 8]

Unvoiced Sound Vectors:
[11 15] , [12 16] , [10 14] , [9 17] , [13 11] , [8 12] , [14 10] , [12 12] , [11 14] , [10 13]

And also weight vector is 1x20 vector
[1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1]

So how im gonna do this.
I´ve tried this which is close my problem but icant get it.
X=[0 0; 0 1; 1 1]
Y=[1 0; 2 1]
w=[1 1 1]
Result = perceptron( X, Y, w )

??? Error using ==> mtimes
Inner matrix dimensions must agree.

Error in ==> perceptron at 15
            if sign(w'*X(:,ii)) ~= Y(ii)

    Result = perceptron( X, Y, w' )

??? Error using ==> ne
Matrix dimensions must agree.

Error in ==> perceptron at 19
        sum(sign(w'*X)~=Y) / size(X,2);


text:
Q: What is model driven development good for? Microsoft, of Cairo fame, is working on Oslo, a new modeling platform. Bob Muglia, Senior Vice President of Microsoft Server & Tools Business, states that the benefits of modeling have always been clear.
In simple, practical terms, what are the clear benefits that Oslo bestows upon its users?

A: I think modeling is just about the next abstraction level. Once it is established it will lead to higher productivity.
MDSD Today - mostly in form of code generation - saves time. Duplicating working patterns for different parts of your software and only writing real business code manually boosts productivity a little bit, but most likely leads to better software quality and more clean architecture.

A: I think the short answer is research projects!
A good place to start though If you're keen to look into it more is Doug Purdy's PDC talk "A lap around Oslo" which you can see here.  He explains how Oslo "captures the essence of the code without the ceremony",..whatever that means.
HTH.

A: In theory, there are a few benefits:

*

*The people with the business knowledge can create the software models so you're less likely to lose anything in translation.

*When non-technical shareholders create models, it forces them to "think like a developer". They see that what they considered obvious and easy is actually difficult when you formalize it.

*It's more efficient. Business people have business knowledge and technical people have technical knowledge so, why not let each group design a system in their area of expertise? No more games of telephone as business experts re-explain what they mean to a developer. Developers are no longer distracted by cryptic business needs. They can focus on the interaction between highly technical systems.

In practice, it's a lot trickier:

*

*Models are hard and that's that. Just because you push model creation to a different group doesn't mean you get foolproof models. Software development is all about modeling so developers are used to it. You may actually lose efficiency as a second group comes to grips with formalizing their understanding of a business need.

*Model driven dev is tightly linked to OO concepts. OO is good for a lot of things, but not everything. What happens if what you really need falls outside the abilities of your modeling tool?

*In my experience, the division between business and technical people is artificial. The most effective people are technical-minded business people or business-minded technical people. They make things happen. If you separate business tasks from technical tasks, you ruin the opportunity for cross-training and cross-thinking.


text:
Q: Better to draw two times the same sprite or one double-sized sprite? I'm working on a parallax background and I would like to know which method is the best to draw a scrolling background :
Should I write two sprites one just next to the second and update the position of both or write a single sprite with two times the same pic stick on each other ?
(I'm looking for the best perfs)
Thanks

A: Usually the best way to answer this is to test it yourself however there is this in the FAQ for SFML:
https://www.sfml-dev.org/faq.php#graphics-xsprite
One of the fastest way to draw in SFML is to switch your implementation to use it's VertexArray as this is only 1 draw call to draw many objects.
SFML has an example how to use a VertexArray here:
https://www.sfml-dev.org/tutorials/2.4/graphics-vertex-array.php
A quick look at the way a sprite is drawn, a Sprite in SFML has 4 verts, each vert has to be transformed by the vertex shader in OpenGL.  So if you are drawing the same sprite you are transforming 8 vertex's, where if you double the size, you are drawing 4 verts.  The cost on the fragment shader should be relatively the same.
One last note, Get it working now optimize later.


text:
Q: How to auto-generate simple HTML with model fields? With a simple model:
class Card(models.Model):
    name = models.CharField(max_length=25)
    rate = models.IntegerField(default=0)
    good = models.BooleanField(default=False)

it is possible to generate a form with:
class CardForm(ModelForm):
    class Meta:
        model = Card
        fields = '__all__'

which then includes all the model fields through a simple template with major part as:

  {{ form.as_table }}

But when showing through a ListView subclass as:
class CardShow(ListView):
    model = Card
    template_name = 'myapp/show.html'

it still requires a template where all the model fields are explicitly named as:

  {% for card in object_list %}

{{ card.name }}, {{ card.rate }}, {{ card.good }}

  {% endfor %}

Is there any way to auto-generate HTML code for view (show), just like the form has form.as_table, form.as_p, and form.as_ul?


text:
Q: Binary Protocols to/from .NET (C# syntax) I would like to hear how you would solve this sort of programming task!?
Each type (OPER = 1 type) corresponds to a specific information.
This is just one of about 10 specifications with same structure. A generic way to create those "converters" (protocol) is preferred.

A: If you are reading/writing this, I would simply translate it at the Stream level, somthing like:
int b = source.ReadByte();
if (b < 0) throw new EndOfStreamException();
int operx = b & 15;
int oper = (b >> 4) & 15;
b = source.ReadByte();
if (b < 0) throw new EndOfStreamException();
int prefix = b & 7;
int reg = (b >> 3) & 31;
b = source.ReadByte();
if (b < 0) throw new EndOfStreamException();
int period = b & 7;
int fas = (b >> 3) & 3;
int tar = (b >> 5) & 7;

If you are doing lots of it, you could wrap it up into something more elegant, perhaps using attributes to specify the offsets - but for 10? meh... not worth it. Writing a robust generic converter is lots of hard work.

A: If you don't want to mask and shift the bits then you could use the BitVector32 structure.  Its CreateSection() method lets you split up to 4 bytes into groups of bits, the indexer then lets you read and write the bit values.


text:
Q: how to choose tombstone_failure_threshold value if I want to delete billions of entries? I have a table having approx 15 billions entries and I want to delete approx 13 billions entries from it. I cannot write 13 billion tombstones in one go since there is a disk space crunch.
I am planning to delete data in chunks so I will be creating 400 millions tombstones in one go.
Now, I have 2 questions:

*

*What is the optimal value of the tombstone_failure_threshold for the above scenario?

*What is the best way to delete 13 billions entries in my case ?

[EDIT]
Adding schema & queries
CREATE TABLE Coupons (
    key text PRIMARY KEY,
    code text
) WITH COMPACT STORAGE
    AND bloom_filter_fp_chance = 0.01
    AND caching = {'keys': 'ALL', 'rows_per_partition': 'NONE'}
    AND comment = ''
    AND compaction = {'class': 'org.apache.cassandra.db.compaction.SizeTieredCompactionStrategy', 'max_threshold': '32', 'min_threshold': '4', 'tombstone_compaction_interval': '604800', 'unchecked_tombstone_compaction': 'true'}
    AND compression = {'chunk_length_in_kb': '64', 'class': 'org.apache.cassandra.io.compress.LZ4Compressor'}
    AND crc_check_chance = 1.0
    AND dclocal_read_repair_chance = 0.0
    AND default_time_to_live = 0
    AND gc_grace_seconds = 864000
    AND max_index_interval = 2048
    AND memtable_flush_period_in_ms = 0
    AND min_index_interval = 128
    AND read_repair_chance = 0.0
    AND speculative_retry = '99PERCENTILE';

*

*Read query : reading using partition key

*Delete query : deleting using partition key

A: If you're reading only by using partition key, and not using something that is doing full table scan, like, Spark, then you can just delete the data and don't modify tombstone_failure_threshold.
The reason for that is that Cassandra counts tombstones when they are read, for example, if you have partition with multiple rows inside.  But in your case you have one row per partition, so when you read by partition key, you can read at most one tombstone - for given partition.
But the situation is different when you use Spark, DSBulk or custom code that reads many partitions at once - then there are multiple tombstones read, and they are counted against that threshold.


text:
Q: $\int \frac{x^4-1}{x^2\sqrt{x^4+x^2+1}}dx$ $$\int \frac{x^4-1}{x^2\sqrt{x^4+x^2+1}}\,dx$$
My attempt,
I changed it to $\int \frac{x^2}{\sqrt{x^4+x^2+1}} \, dx-\int \frac 1 {x^2\sqrt{x^4+x^2+1}} \, dx$, but I stuck here.
Any method to solve this integral? Thanks in advance.

A: For $x>0,$
$$I=\int \frac{x^4-1}{x^2\sqrt{x^4+x^2+1}}\,dx=\int\dfrac{x^3\left(2x-\dfrac2{x^3}\right)\ dx}{2x^3\sqrt{x^2+\dfrac1{x^2}+1}}$$
Set $x^2+\dfrac1{x^2}+1=y$

A: Everytime I see an integrand that look sort of "symmetric" under $x \to x^{-1}$,
I will try to see whether it can be reexpressed in terms of $x \pm x^{-1}$.
One useful identity to remember is
$$\frac{dx}{x} = \frac{d(x+x^{-1})}{x - x^{-1}} = \frac{d(x-x^{-1})}{x + x^{-1}}$$
This trick does work for the integral at hand.
$$\begin{align}
\int \frac{x^4-1}{x^2\sqrt{x^4+x^2+1}} dx &= \int \frac{x^2-x^{-2}}{\sqrt{x^2+x^{-2}+1}} \frac{dx}{x} \\
&= \int \frac{x^2-x^{-2}}{\sqrt{x^2+x^{-2}+1}} \frac{d(x-x^{-1})}{x+x^{-1}} \\
&= \int \frac{(x-x^{-1}) \, d(x - x^{-1})}{\sqrt{(x-x^{-1})^2+3}} \\
&= \int d\sqrt{(x-x^{-1})^2+3} \\
&= \sqrt{x^2+x^{-2}+1} + \text{const.}
\end{align}$$


text:
Q: multiple file upload to bigquery I am trying to do multiple file upload simultaneously to google big-query using command line tool. I got following error :
BigQuery error in load operation: Could not connect with BigQuery server.
Http response status: 503
Http response content:
Service Unavailable
Any way to workaround this problem ?
How do I upload multiple files simultaneously to google big-query using command line tool.

A: Multiple file upload should work (and we use it every day). If you're getting a 503, that indicates something is wrong with the service. One thing you might want to make sure of is that if you're using a * in your command line that you have it quoted so that the shell doesn't expand it automatically before it gets passed to bq.
If you're getting a 503 error, can you retry the command the flag --apilog=- (this needs to be one of the first params) which will dump the interaction with the server to stdout. The problem may be obvious from that log, but if it isn't can you update your question with the relevant portions of the log? If you're not comfortable posting that information on a public forum, can you e-mail it to me at tigani at google dot com?


text:
Q: Declaration Merging in Script file vs in Module Results in Different Outcome I am trying to add properties to req.session object from express-session via SessionData interface.
I am using declaration merging to do so, but i get some behavior which i don't understand.
I have done the following:
declare module 'express-session' {
  interface SessionData{
    myProperty: myProperty_t
  }
}

What i don't understand is that this only works if the file is a module (i.e. has top level import/export) and not if it is a script file.
I would have thought it would be the other way around, since i would want this change to be global (which is essentially my understanding of scripts vs modules).
I have very limited Typescript experience and I cant seem to find (or maybe understand) any resources regarding this.
Can someone please explain the difference here?

A: Module augmentation using script file(one without export/import at the top level) is treated as ambient module, i.e kind of module augmentation which assume that there's no existing type definition so it's the only one and it override any existing module types. Ambient modules are how the DefinitelyTypes are written.
If you want to augment existing module types then the augmentation file must be in module scope(with export/import at the top) to enable the actual augmentation(it assume there's existing module types or will not try to shadow/override the existing types)


text:
Q: MariaSQL LIKE returns no results I have a query with LIKE '%query%' ,with query being the exact value that is in the table, that doesn't return a result. When I try the exact same query with q it does return results.
Is this normal?


text:
Q: tensorflow-gpu installed but not used for calculation I have a fresh install of windows 10 and installed tensorflow-gpu (i think i should have done successfully) as i run the sample code, i see the gpu0 is used as follow:
>>> import tensorflow as tf
>>> # Creates a graph.
... a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3], name='a')
>>> b = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[3, 2], name='b')
>>> c = tf.matmul(a, b)
>>> # Creates a session with log_device_placement set to True.
... sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))
2017-05-08 02:10:35.354149: W c:\tf_jenkins\home\workspace\release-win\device\gpu\os\windows\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE instructions, but these are available on your machine and could speed up CPU computations.
2017-05-08 02:10:35.354283: W c:\tf_jenkins\home\workspace\release-win\device\gpu\os\windows\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE2 instructions, but these are available on your machine and could speed up CPU computations.
2017-05-08 02:10:35.355376: W c:\tf_jenkins\home\workspace\release-win\device\gpu\os\windows\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE3 instructions, but these are available on your machine and could speed up CPU computations.
2017-05-08 02:10:35.355835: W c:\tf_jenkins\home\workspace\release-win\device\gpu\os\windows\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.1 instructions, but these are available on your machine and could speed up CPU computations.
2017-05-08 02:10:35.356245: W c:\tf_jenkins\home\workspace\release-win\device\gpu\os\windows\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.2 instructions, but these are available on your machine and could speed up CPU computations.
2017-05-08 02:10:35.356629: W c:\tf_jenkins\home\workspace\release-win\device\gpu\os\windows\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use AVX instructions, but these are available on your machine and could speed up CPU computations.
2017-05-08 02:10:35.356977: W c:\tf_jenkins\home\workspace\release-win\device\gpu\os\windows\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use AVX2 instructions, but these are available on your machine and could speed up CPU computations.
2017-05-08 02:10:35.357376: W c:\tf_jenkins\home\workspace\release-win\device\gpu\os\windows\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use FMA instructions, but these are available on your machine and could speed up CPU computations.
2017-05-08 02:10:35.765058: I c:\tf_jenkins\home\workspace\release-win\device\gpu\os\windows\tensorflow\core\common_runtime\gpu\gpu_device.cc:887] Found device 0 with properties:
name: GeForce GTX 1080 Ti
major: 6 minor: 1 memoryClockRate (GHz) 1.607
pciBusID 0000:01:00.0
Total memory: 11.00GiB
Free memory: 9.12GiB
2017-05-08 02:10:35.765151: I c:\tf_jenkins\home\workspace\release-win\device\gpu\os\windows\tensorflow\core\common_runtime\gpu\gpu_device.cc:908] DMA: 0
2017-05-08 02:10:35.765851: I c:\tf_jenkins\home\workspace\release-win\device\gpu\os\windows\tensorflow\core\common_runtime\gpu\gpu_device.cc:918] 0:   Y
2017-05-08 02:10:35.780335: I c:\tf_jenkins\home\workspace\release-win\device\gpu\os\windows\tensorflow\core\common_runtime\gpu\gpu_device.cc:977] Creating TensorFlow device (/gpu:0) -> (device: 0, name: GeForce GTX 1080 Ti, pci bus id: 0000:01:00.0)
Device mapping:
/job:localhost/replica:0/task:0/gpu:0 -> device: 0, name: GeForce GTX 1080 Ti, pci bus id: 0000:01:00.0
2017-05-08 02:10:36.157808: I c:\tf_jenkins\home\workspace\release-win\device\gpu\os\windows\tensorflow\core\common_runtime\direct_session.cc:257] Device mapping:
/job:localhost/replica:0/task:0/gpu:0 -> device: 0, name: GeForce GTX 1080 Ti, pci bus id: 0000:01:00.0

>>> # Runs the op.
... print(sess.run(c))
MatMul: (MatMul): /job:localhost/replica:0/task:0/gpu:0
2017-05-08 02:10:46.297244: I c:\tf_jenkins\home\workspace\release-win\device\gpu\os\windows\tensorflow\core\common_runtime\simple_placer.cc:841] MatMul: (MatMul)/job:localhost/replica:0/task:0/gpu:0
b: (Const): /job:localhost/replica:0/task:0/gpu:0
2017-05-08 02:10:46.299024: I c:\tf_jenkins\home\workspace\release-win\device\gpu\os\windows\tensorflow\core\common_runtime\simple_placer.cc:841] b: (Const)/job:localhost/replica:0/task:0/gpu:0
a: (Const): /job:localhost/replica:0/task:0/gpu:0
2017-05-08 02:10:46.302386: I c:\tf_jenkins\home\workspace\release-win\device\gpu\os\windows\tensorflow\core\common_runtime\simple_placer.cc:841] a: (Const)/job:localhost/replica:0/task:0/gpu:0
[[ 22.  28.]
 [ 49.  64.]]

But when i run the code for deep-learning, the gpu-memory is all used but the gpu-loading is almost 0. the cpu-loading is around 20% (before install tensorflow-gpu, the cpu-loading is 100%), the time for learning is a bit faster than using cpu.
what may be the cause? Please give me some advance, thank you so much

A: The line gpu:0 -> device: 0, name: GeForce GTX 1080 Ti, pci bus id: 0000:01:00.0
shows that the computation is being done on the gpu.
The reason the useage isn't too high is probably because there isn't too much processing to do relative to the power of your GPU.


text:
Q: How to go to the last edit location across all buffers in vim? It is easy to go to the last edit location in the current buffer.
See How to go back to lines edited before the last one in Vim?
The changelist is buffer local, each buffer has it's own changelist.
However it is very common that I navigate away from that recently edited buffer to an other buffer, and it would be nice to somehow get back to the last edit location in the original buffer. Is there a way to go back to the place where the last insert or modify has happened?

A: You can put the following in your vimrc
autocmd InsertLeave * execute 'normal! mI'

and press `-I to jump back to the position where you left your Insert mode. Since I is an uppercase, it works across buffers.

Addendum (after the comment)
After reading @Garbor Marton's comment,
I wrote a function myself
let g:detect_mod_reg_state = -1
function! DetectRegChangeAndUpdateMark()
    let current_small_register = getreg('"-')
    let current_mod_register = getreg('""')
    if g:detect_mod_reg_state != current_small_register ||
                \ g:detect_mod_reg_state != current_mod_register
        normal! mM
        let g:detect_mod_reg_state = current_small_register
    endif
endfunction

" Mark I at the position where the last Insert mode occured across the buffer
autocmd InsertLeave * execute 'normal! mI'

" Mark M at the position when any modification happened in the Normal or Insert mode
autocmd CursorMoved * call DetectRegChangeAndUpdateMark()
autocmd InsertLeave * execute 'normal! mM'

I liked using the original I register specifically for the insert mode change, so here I use a M register for any modification including r,x,d,y AND last insert mode.

A: You could do :windo normal`.
That said, I usually just use C-o (repeatedly).
If I "feel" that I will likely want to return to some point, I'll just hit mA (which records a cross-file/buffer mark) so I can just do `A from anywhere (even after restarting the editor).

Slightly off-topic, I love :Obsession (by Tim Pope) for really long-lived sessions that do a lot of cross-reference navigation.

A: Try doing ctrl-` (or ctrl-6).


text:
Q: Referencing a slot in an array of objects that is initialized to null I'm trying to check to see if an array's slot is equal to null, for the purposes of iterating through a hash table. I'm getting a NullPointerException, however. Is there any way to get around this?
Thanks!
Here's the next() method (and its class) that are causing the problem.
 public K next() throws NoSuchElementException{
      int tempStore = -1;
      MapHashCellList tempCells = null;
      System.out.println("Got here! 1");
      System.out.println(mapCells);
      if(mapCells.length==0) {throw new NoSuchElementException();}
      if (mapCells[arrayPointer]!=null && listCounter<=mapCells[arrayPointer].size()-2){
              System.out.println("Got here! 2");
        tempCells = mapCells[arrayPointer];
        tempStore = listCounter;
        listCounter++;
      }
      else{
        arrayPointer++;
              System.out.println("Got here! 3");
        while (mapCells[arrayPointer]==null){
          arrayPointer++;
          listCounter=0;
                System.out.println("Got here! 4");
          if(mapCells[arrayPointer]!=null){
            tempCells = mapCells[arrayPointer];
            tempStore = listCounter;
            listCounter++;
          }
          System.out.println("ListCounter: " + listCounter);
          System.out.println("Array: " + arrayPointer);
        }
      }
      return (K)tempCells.get(tempStore).getKey();
    }

Per one of the user's questions, here is the entire class' code:
import java.util.*;

public class ProjectMap<K,V> implements MapInterface<K,V>{

  public MapHashCellList[] mapCells;
  public int size;

  public ProjectMap(){
    mapCells = new MapHashCellList[11];
    size = 0;
  }

  public boolean containsKey( K key ){
    if(key==null){return false;}
    if(isEmpty()){return false;}
    if(mapCells[hashValue(key)]!=null){
      MapHashCellList temp = (MapHashCellList)mapCells[hashValue(key)];
      for (int g =0; g<temp.size(); g++){
        if (temp.get(g).getKey().equals(key)){
          return true;
        }
      }
    }
    return false;
  }

  public boolean isEmpty(){
    if(size==0){return true;}
    else return false;
  }

  public int hashValue(K key){
    return (int)(Math.abs(key.hashCode()%10));
  }

  public MapHashCellList get(int index){
    return (MapHashCellList)mapCells[index];
  }

  public V get( K key ){
    if(mapCells[hashValue(key)]!=null){
      MapHashCellList temp = (MapHashCellList)mapCells[hashValue(key)];
      for (int q =0; q<temp.size(); q++){
        if (temp.get(q).getKey().equals(key)){
          return (V)temp.get(q).getValue();
        }
      }

    }
    return null;
  }

  //Key = docID, V = documentNumber
  public V put( K key, V value ){
    //If cell isn't empty and Key exists, replace existing Value since duplicate
    if(mapCells[hashValue(key)]!=null){
      MapHashCellList temp = (MapHashCellList)mapCells[hashValue(key)];
      for (int q =0; q<temp.size(); q++){
        if (temp.get(q).getKey().equals(key)){
          V temp1 = (V)temp.get(q).getValue();
          temp.get(q).setValue(value);
          return temp1;
        }
      }
    }

    //Otherwise add to end of linkedlist
    if(mapCells[hashValue(key)]!=null){
      MapHashCellList temp = (MapHashCellList)mapCells[hashValue(key)];
      MapHashCell newCell = new MapHashCell(key,value);
      temp.add(newCell);
      size++;
      return null;
    }

    //Index doesn't exist yet, so make new LinkedList and add to correct index position
    MapHashCellList newCell = new MapHashCellList(key,value);
    mapCells[hashValue(key)] = newCell;
    size++;
    return null;
  }

  public V remove( K key ){
    if(mapCells[hashValue(key)]!=null){
      MapHashCellList temp = (MapHashCellList)mapCells[hashValue(key)];
      for (int q =0; q<temp.size(); q++){
        if (temp.get(q).getKey().equals(key)){
          V temp1 = (V)temp.get(q).getValue();
          temp.remove(q);
          size--;
          return temp1;
        }
      }
    }
    return null;
  }

  public int size(){
    return size;
  }

  public Iterator<K> iterator(){
    Iterator<K> temp = new KIterator();
    return temp;
  }

  private class KIterator implements Iterator<K>{
    int arrayPointer=0;
    int listCounter=0;

    KIterator(){
    }

    public K next() throws NoSuchElementException{
      int tempStore = -1;
      MapHashCellList tempCells = null;
      System.out.println("Got here! 1");
      System.out.println(mapCells);
      if(mapCells.length==0) {throw new NoSuchElementException();}
      if (mapCells[arrayPointer]!=null && listCounter<=mapCells[arrayPointer].size()-2){
              System.out.println("Got here! 2");
        tempCells = mapCells[arrayPointer];
        tempStore = listCounter;
        listCounter++;
      }
      else{
        arrayPointer++;
              System.out.println("Got here! 3");
        while (mapCells[arrayPointer]==null){
          arrayPointer++;
          listCounter=0;
                System.out.println("Got here! 4");
          if(mapCells[arrayPointer]!=null){
            tempCells = mapCells[arrayPointer];
            tempStore = listCounter;
            listCounter++;
          }
          System.out.println("ListCounter: " + listCounter);
          System.out.println("Array: " + arrayPointer);
        }
      }
      return (K)tempCells.get(tempStore).getKey();
    }

    public boolean hasNext(){
      if(isEmpty()) {return false;}
      for(int d=arrayPointer; d<mapCells.length; d++){
        if (mapCells[d]!=null){
          try{
            if(mapCells[d].get(listCounter+1)!=null){
              return true;
            }
          }
          catch(IndexOutOfBoundsException e){
            for(int l=arrayPointer; l<mapCells.length; l++){
              if (mapCells[l]!=null){
                return true;
              }
              else{
                return false;
              }
            }
          }
        }
      }
      return false;
    }

    //Removes last element
    public void remove(){
      mapCells[arrayPointer].remove(listCounter-1);
    }
  }
}

A: At least one of the problems is with your public K next method:
public K next() throws NoSuchElementException{
  int tempStore = -1;
  MapHashCellList tempCells = null;
  System.out.println("Got here! 1");
  System.out.println(mapCells);
  if(mapCells.length==0) {throw new NoSuchElementException();}
  if (mapCells[arrayPointer]!=null && listCounter<=mapCells[arrayPointer].size()-2){
          System.out.println("Got here! 2");
    tempCells = mapCells[arrayPointer];
    tempStore = listCounter;
    listCounter++;
  }
  else{
    arrayPointer++;
          System.out.println("Got here! 3");
    while (mapCells[arrayPointer]==null){
      arrayPointer++;
      listCounter=0;
            System.out.println("Got here! 4");
      if(mapCells[arrayPointer]!=null){
        tempCells = mapCells[arrayPointer];
        tempStore = listCounter;
        listCounter++;
      }
      System.out.println("ListCounter: " + listCounter);
      System.out.println("Array: " + arrayPointer);
    }
  }
  return (K)tempCells.get(tempStore).getKey();
}

In the beginning:
MapHashCellList tempCells = null;

Then look at the else part.  You have the following loop:
while (mapCells[arrayPointer]==null){

Inside this loop you have this:
if(mapCells[arrayPointer]!=null){
        tempCells = mapCells[arrayPointer];
        tempStore = listCounter;
        ..................

Since the program would never get inside this if (your while condition guarantees it), tempCells remains null.
And then, at the very end you have the following:
return (K)tempCells.get(tempStore).getKey();

which has to produce NullPointerException.


text:
Q: Java Socket reading large data encounters intermittent error I am developing an application to communicate with a third party application through socket. Basically, my application needs to send some requests to the server, and the server returns some data. When the server sends me back small amount of data, everything works well. But, when I request large amount data from server, my application sometimes doesn't receive complete data and it happens intermittently.
I've done some research on internet and followed the socket programming examples that I found but still, I couldn't solve the issue. Below is my current implementation.
     BufferedInputStream is = new BufferedInputStream(socket.getInputStream());

    //I know the size of data that I am expecting from the server
    byte[] buffer = new byte[length];

    int count = 0;
    int current = 0;

    while(count < length) {
        current = is.read(buffer, count, length - count);

        if(current == -1) {
            break;
        } else {
            count += current;
        }
    }

I know the size of data that I am expecting from the server. When the problem occurs, read() method returns -1 before the data is fully received from the server. I don't have any access to the server side implementation. Please advise me if I miss out anything in my code or if there is any better way to do it.

A: If the read method returns -1 the server has closed the socket after sending whatever it sent. Period. If you were expecting more data you were mistaken.
Possibly the server is incorrectly coded, e.g. closes its socket instead of its outermost output stream, thereby losing data. Or possibly your end is incorrect, for example by creating multiple BufferedInputStreams per socket, instead of one for the life of the socket.
Your code just replicates DataInputStream.readFully(). However what you should really be doing is processing every buffer load as received, not trying to create an arbitrarily large buffer in memory. That just wastes space and adds latency.

A: Your code looks basically sound.  (Using a BufferedInputStream does not improve the performance in this case.  If anything, it makes it slower.  However, this is unlikely to cause this problem.)
It is also possible that buffering huge amounts of stuff in memory on the client side is causing the client side to go unresponsive for long enough to cause a socket timeout.  But if your file size is only a few megabytes, you can probably discount this possibility.
However, I suspect that the real problem is a socket timeout that is too small on either the client or server end.  But it is very difficult to diagnose this if you have no way of accessing the server-side configs and logs.

A: There are some serious problems within your code:
Assuming length = 8GB
You will get a lot of problems creating a byte[] of this size.
int count
int current

this should be
long count
long current

but if you do this, the code won't compile anymore. So you have a Maximum filesize of Integer.MAX_VALUE. if you store your download to a bytearray. (Thanks to  EJP)
You have to write that data to a file ore some other memory than RAM. With a 32bit JVM, you'll never create a byte[] lager than ~1,3 GB.


text:
Q: Is it possible to use a recurring fee for a Windows Store App I plan to publish an Windows Universal application to the Window Store. Do you think it's possible to create a recurring fee for this app ?
This way, the users will pay a small fee each month versus a one time fee at purchase time.
Thanks,
Julien

A: you can sell Consumable IAP, check each time user by it (once a month ?) and active features accordingly.

A: If you adding licensing in your application you are using
LicenseInformation class
This class has ExpirationDate property - that means date when app license expired
Usualy it is used for making Trial period, but you can try to combine it with app purchase anf licence will be sold every time for some period only


text:
Q: How to update Julia in ssh clusters I'm working as a PhD student in a lab with ssh clusters, I have the access to connect to each one of them (there's no queue system, as it is a small lab, hence, as long as someone is not using a lot of cores in each computer I can run my programs on them).
Currently the lab doesn't have a cluster administrator so its maintenance is in the hands of two researchers with computer knowledge. Currently, the clusters have a very old version of Julia (0.5.1) and I need an update in order to work; however, one of the two researchers in charge told me that it will require a very large amount of time and stopping all current process in order to update Julia, so he is unwilling to make the update on the clusters.
Is there a way that I can update the Julia version on the clusters all by myself? Without interrupting nor canceling any of the current processes?
I believe non of the current processes are being run with Julia, as I am the only one in the lab who works with it. The languages being used for these processes are C, C++ and Fortran.

A: Julia does not need to be installed system-wide to be used. In fact on all OSes - Linux, Mac and Windows - the Julia distribution is portable and self-contained.
So, the easiest way to get this is to use juliaup to install julia on all the nodes, and use it to manage all the julia versions you need.


text:
Q: Conditional ng-include together with ng-controller in AngularJS I have a conditional ng-include directive with a ng-controller associated, but it seems the controller isn't run when the condition is true.
The target is to include the template only when the condition is met and avoid the TypeError: Cannot call method 'insertBefore' of null issue.
For example:
<div ng-include src="myContent.imgList ? 'ui/image-list.html' : null" ng-controller="ImgListSubCtrl">
</div>

When myContent.imgList is filled with data, I expect the image-list.html template to be appended to the DOM and ImgListSubCtrl to be run, but it isn't.
Is this the expected behavior?. I'm using Ionic Framework with Angular 1.2.17.
Thank you.

A: I already found an explanation, though further comments are welcome.
The following Codepen shows the mentioned behavior and the solution (in Ionic Framework 1.0.0-beta12): http://codepen.io/anon/pen/FnojD?editors=101
The first include doesn't display any count, though the second one displays it correctly.
It seems that when using ng-include along with ng-controller, the controller is only run once, even when the ng-include src expression evaluates to null.
To run it when the template is actually included (when ng-include src isn't null), a solution is to avoid the conditional ng-include and wrap it in a ng-if block, so the whole element is re-created dynamically, as shown in the Codepen above.
In the example from the question:
<div ng-if="myContent.imgList">
    <div ng-include src="'ui/image-list.html'" ng-controller="ImgListSubCtrl">
    </div>
</div>

I hope it helps.