text:
Q: How to only load/render custom rendered image when it comes into view (react-native-render-html) I am using react-native-render-html to render content that has images in it via a custom renderer. The issue I'm running into is some pages have dozens of images, and I would like to only download/render the ones I need that are in or near the viewport. The way the custom renderer is set up currently (via the documentation) it downloads all of them at once (How would I go about Implementing the logic into a more flatlist-like render system?
Here's the image renderer (if it helps):
const ImgRenderer = useCallback((props: any) => {
    console.log('imgRendererProps: ', props)
    const { Renderer, rendererProps } = useInternalRenderer('img', props);
    const uri = rendererProps.source.uri;
    const imgSource = {
      ...rendererProps.source,
      // You could change the uri here, for example to provide a thumbnail.
      uri: `https://home.website.com${uri?.split('about://')[1]}`
    };
    return (
      <TouchableWithoutFeedback onPress={() => setModalImage(uri?.split('about://')[1] ?? null)}>
        <Renderer {...rendererProps} source={imgSource} style={{resizeMode: 'contain'}} />
      </TouchableWithoutFeedback>
    );
  }, [props.tnode?.init.nodeIndex])


text:
Q: SQL query to get average per group in two tables I have two tables: students and results.
For students, the fields are student_id, name, grade
For results, the fields are student_id, score
grade is like pre-school, one, two, three.... Like in a school.
As you see, student_id is in both tables.
I want a SQL query that returns average score per grade, like
Pre-School => 50
Kindergarten => 26

etc.
I tried group by with left joins but nothing works.
The query I've been working on is as follows:
SELECT
    cat.grade,
    dog.score
FROM (SELECT * FROM students GROUP BY grade) AS cat, results AS dog
GROUP BY cat.grade

But this just gives me one result per grade, so AVG() does not give the right answer here.

A: It should be as simple as joining the two table together, grouping on grade and selecting the average of all the scores.
SELECT grade,
       Avg(score)
FROM   students
       JOIN results using (student_id)
GROUP  BY grade

A: select id, avg(salary) avg_salary from Employee join results group by id order by avg(salary) desc;

  ID                 AVG_SALARY
 ---- ------------------------
 07                    7897.78
 02                    6661.78
 03                    6544.78
 06                    4322.78
 04                    2344.78
 05                    2334.78
 01                    1234.56
 08                    1232.78

redpajama_set_name: RedPajamaStackExchange


text:
Q: Split php function I want to split the following code.
<?php echo $currencySymbol." ".str_replace(",","",$custom_area1['mrp']); ?>

Currently it shows at $ 100 for example
The $ I understand is coming from     <?php echo $currencySymbol." ".
While the amount is coming from     str_replace(",","",$custom_area1['mrp'])
How do I split it up so there is a function for $ and a function for the amount.

A: public function getCurrencySymbol(){
  return $currencySymbol;
}
public function getAmount(){
  $amount = str_replace(",","",$custom_area1['mrp']);
  return $amount;
}

A: This worked for me
<?php echo $currencySymbol;?>
<?php echo str_replace(",","",$custom_area1['mrp']); ?>/>


text:
Q: Make WordPress Search Block only show results of child pages I have added in a my WordPress website a search block like this:
<!-- wp:search {"label":"","placeholder":"Find in Help Center","buttonText":"Search"} /-->

When the user uses it, it searches all the pages on my website. However, I would like it to be so that the search results only show results from child pages.
E.g.
If I add the search block on the page .../help-center/, I only want it to search the child pages of help-center.
I have added this to my searchform.php
<input type="hidden" value="<?php
    global $post;
    $ancestors2 = $post->ancestors;
    if ($ancestors2) {
        echo end($ancestors2);
    } else {
        echo $post->ID;
    } ?>" name="post_parent" />

and this to functions.php
function SearchFilter($query) {
        if (is_search() && !empty($_GET['s']) && !empty($_GET['post_parent'])) {
            $parent_page_id = intval($_GET['post_parent']);
            $query->set('post_parent', $parent_page_id );
        }
        return $query;
    }
    add_filter('pre_get_posts','SearchFilter');

This makes it only to search child pages, but only works for my main search bar on the page.
Instead, I would want my main search bar to search the whole page as it is by default, but my wp:search block to only search child pages.
How would I achieve this?

A: see if inserting the following function to your functions.php file and blocking adult pages works
// Remove pages from search results
function exclude_pages_from_search($query) {
    if ( $query->is_main_query() && is_search() ) {
        $query->set( 'post_type', 'post' );
 {
     return $query;
}
add_filter( 'pre_get_posts','exclude_pages_from_search' );


text:
Q: Proper way to create custom JS animations in angular 1.3+ with ng-animate I want to use velocity.js in combination with ng-animate to create custom js-animations for my app. I've searched the web and found a lot of answers and tutorials which all refer to old versions of ng-animate, which apparently has changed the API a lot over time.
So right now, this is how my animation looks:
app.animation('.lb-fade', function () {
    return {
        addClass: function (element, className) {
            element.velocity({
                opacity: 1
            },{
                duration: 900,
                easing: 'easeInSine'
            });
        }
    };
});

I'm using it like this:
$animate.addClass(backdrop, 'lb-fade').then(console.log('promise resolved'));

This kind of works, but I have two problems:

*

*The promise sometimes get's resolved to early (before the animation is finished). It looks like it is happening randomly.

*How can I pass arguments to the animation? For example i want some of my lb-fade animations to use velocitys delay option. I could either create multiple animations (!DRY) or access the elements scope inside the animation (which seems really hacky to me). Is there a right way to do it?

Does it even make sense to use ng-animate alongside with velocity or should I just create my own functions to hold the animation code?

A: Maybe this is more like a workaround, but I wrote my own animator service now instead of using ngAnimate now. It uses angulars $q for implementing promises. Basically, this is just how ngAnimate does it, but somehow I think it doesn't know when velocity finished animating.
This is my service:
.service('animator', function animator($q) {

    this.flyOutRight = function($element) {
        return $q(function(resolve) {
            $element.velocity({
                //css properties to get animated
            }, {
                duration: 200,
                complete: function () {
                    $element.remove();
                    resolve();
                }
            });
        });
    };

    //some more animations

});

Usage:
animator.flyOutRight($oldImage).then(function(){
    changeImageMutex = false;
});

A: It looks like you found a great workaround for your problem!
I think your original code didn't work since you didn't use the built-in done function. it's actually a wrapper for the default promise that ngAnimate returns at the end of an animation.
you used the function with the 2nd parameter className: function (element, className)
I used angular's ngAnimate as follows:
app.animation('.lb-fade', function () {
return {
    addClass: function (element, doneFn) {
        element.velocity({
        opacity: 1
      },{
        duration: 900,
        complete: doneFn
      });
    }
  };
});

This works great for me.
It looks like the doneFn is still part of the api for ngAnimate.
Also, if you still want to use className (even though it looks like you didn't use it), you can use the function with it like so:
function(element, className, doneFn) {}


text:
Q: How to exit a while loop (continue) I have been trying to fix a simple issue with my coding (I am new at C++).
Basically I am trying to exit a while loop using
continue
or
break

but it doesn't work. The issue is that the
cout << "it worked!";

part doesn't get executed.
#include <iostream>
#include <string>
using namespace std;

int main() {
    int userChoice=0;
    cout<<"1 for addiction and 2 for subtraction\n";
    do{
        if(cin >> userChoice){
            switch (userChoice) {
                case 1:
                    continue;
                case 2:
                    continue;
                default:
                    cout<<"Please select 1 for addiction or 2 for subtraction.\n";
                    break;
            }
        }
    }while(userChoice!=1 || userChoice!=2);

    cout<<"it worked!";
}

int addiction(int a,int b){
    return a+b;
}

int subtraction(int a,int b){
    return a-b;
}

A: It is impossible to leave your loop, because whatever userChoice is it is always either "not 1" or "not 2" (it can never be both!).
So since the continue will just always go to another iteration, and since the break jumps you out of the switch (not the loop), your loop can never end and the cout will never be executed.
It seems to me that you want to iterate for only as long as userChoice is not 1 and it's also not 2:
while(userChoice!=1 && userChoice!=2);

This is sometimes confusing to beginners who take English shortcuts like "userChoice is not 1 or 2" when they really mean "userChoice is neither 1 nor 2" and don't realise that C++ doesn't have a "neither/nor" construct at all so end up writing "userChoice is not 1 or userChoice is not 2" by mistake without thinking it through.
Since positives are more intuitive than negatives, one way to clarify it to yourself is to apply De Morgan's law; your fixed code is equivalent to:
while(!(userChoice == 1 || userChoice == 2));

i.e. "loop while it's not the case that userChoice is either 1 or 2". It's arguably worse code, but it can help your understanding to briefly write it out that way.


text:
Q: Remove custom attribute from all  element in dynamic HTML container How to remove index attribute from all  elements in the variable container.innerHTML.
Html is generated dynamically.
var container.innerHTML = test    testimage
        testimage
    these two images are not matching    testimage

A: An easy solution can be just replace with regular expression
`test    testimage
        testimage
    these two images are not matching    testimage  &nbsp`.replace(/index="[\d]+"/g, '')

Here replace is the string replace function for JavaScript it's generally accepts two parameter one search string or regex pattern & replace string. Here /index="[\d]+"/g is the pattern '' is the replace string. g is used to match all.

A: A Regex is the easiest way out of this. The search below uses index
let str = `test    testimage
   testimage
these two images are not matching    testimage  &nbsp`;

let re = /index="[^"]*"/gi;
let result = str.replace(re, "");
console.log(result);


text:
Q: pg_dump: [archiver (db)] query failed: ERROR: permission denied for relation abouts I'm trying to dump my pg db but got these errors please suggest
pg_dump: [archiver (db)] query failed: ERROR:  permission denied for relation abouts
pg_dump: [archiver (db)] query was: LOCK TABLE public.abouts IN ACCESS SHARE MODE

A: The user which you're performing your pg_dump as doesn't have permissions on the public schema.
Add permissions if allowed:
GRANT USAGE ON SCHEMA public TO <user>;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO <user>;

A: This can be a common error, when using a ROLE (user) that could not open the objects to dump them.
Like said before, you can grant to the specific schema that you want to dump, or even use a ROLE with SUPERUSER attribute.
Note that when you are dealing with some cloud database providers, like AWS/RDS you will not receive a user with the SUPERUSER attribute, so you will need to manage to make sure that the one used to dump will have all access needed.
https://www.postgresql.org/docs/current/static/sql-grant.html will show how give GRANT to many objects on your database, but also remember that when restoring you will need to create the database first. Only if you are using pg_dumpall that is not necessary, but you also need to dump the ROLES.

A: Change the permission to the user: login as sudo user by using following cmd
sudo -u postgres psql

Alter the user role
alter role <user-name> superuser;


text:
Q: How to set the number of retries for Azure DocumentDB output binding in Azure Function? Based on this question, it seems like writing to Azure DocDB output binding in Azure Function will be retried 10 times if throttled (HTTP 429). I haven't verified this myself though.
I would like to increase this limit on the number of retries. My data comes in big chunks in a small amount of time and then with a very long period of downtime, which means that getting 429 and waiting for a bit is okay for my purpose. I must guarantee though, that no data is dropped.
One way for me to solve this is to increase the RTU limit in Document DB to make sure I don't get 429 during the time big chunks of data come in, but it's already at about 2.5 times of what I need during downtime period. Is there anyway to make the retries run infinitely until it succeeds, or less ideally, increase the number of retries to something more than 10?

A: Why don't you change the approach and instead of inserting documents right away you can make use of service bus and implement a dead letter queue, here are some links:

*

*https://learn.microsoft.com/en-us/azure/service-bus-messaging/service-bus-dead-letter-queues

*https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-service-bus

*https://blog.jeroenmaes.eu/2017/01/process-service-bus-dead-letter-message-with-azure-functions/
The idea is having something like this:

*

*Current function instead of saving the data in DocumentDB, it will be sending it the the service bus (you just change the output binding)

*Another function will process every message of the service bus and if it failed (you can manage a timeout in the function and then move the message to a dead letter queue)

*Another function that will process any message in the dead letter queue

You just need to make a small change in the first function and create two more, might sound too complicated but you'll have strong consistency in the data. In all of the above links there's an example of what I mentioned here.


text:
Q: web3.exceptions.ContractLogicError: execution reverted Hello!
Help me please.
I have just created own
tokens on bsc testnet via PancakeFactory.
Then I created liquidity pool with these tokens.
I minted tokens and I want approve
this tokens to PancakeRouter
and add liquidity in this pool.
You see my code below:

def approves(w3, token_contract, router_contract, my_account, my_pk):
    allowance_value = token_contract.functions.allowance(
        my_account, router_contract.address).call()
    print('allowance_value: ', allowance_value)
    if allowance_value <= 1000000000000000:
        approve_est_gas = token_contract.functions.approve(
            router_contract.address,
            10000
        ).estimateGas(
            {
                'from': my_account,
                'nonce': w3.eth.get_transaction_count(my_account)
            }
        )

        approve_tx_builder = token_contract.functions.approve(
            router_contract.address,
            10000
        ).buildTransaction(
            {
                'from': my_account,
                'nonce': w3.eth.get_transaction_count(my_account),
                'gas': approve_est_gas
            }
        )

        signed_tx = w3.eth.account.sign_transaction(approve_tx_builder, my_pk)
        tx_hash = w3.eth.send_raw_transaction(signed_tx.rawTransaction)
        tx_receipt = w3.eth.wait_for_transaction_receipt(tx_hash)
        print('tx_hash: ', tx_receipt['transactionHash'].hex())
        print('tx_hash: ', tx_receipt['status'])

I always received this mistake:

raise ContractLogicError('execution reverted')
web3.exceptions.ContractLogicError: execution reverted


text:
Q: is it possible to send a HTML form that includes a submit button via JavaScript? I need to send a file via HTTP Post (a form) to more than one destination via a single click.
The form has a submit button
<input type="submit" id="button1" name="submit" value="upload file">

The action attribute and various different hidden fields that are needed, are set via JavaScript.
After button1 is clicked the file is sent to the first destination without problems.
It is impossible for me, to send the form a second time with different values because of the submit button.
I cannot use an external button like
<button id="button1">upload file</button>

This would make the problem easy to solve (I already tried it) but it is impossible here. The reason is that the message needs these lines at the end that are generated by a real submit button inside the HTML form:
Content-Disposition: form-data; name="submit"

upload file

My question: How can I send a form via JavaScript that includes a submit button? How can I "click" a submit button via JavaScript?
This is my Java Script file:
// If frame 1 is loaded, the function prepareUpload() will be executed
$("#frame1").ready(function() {
   prepareUpload();
});

function prepareUpload(){

     // click-handler is registered to button1
     $('#button1').click(function(){
            // if clicked...
            // "Please Wait" window
            $.blockUI({ css: {
                border: 'none',
                padding: '15px',
                backgroundColor: '#000',
                '-webkit-border-radius': '10px',
                '-moz-border-radius': '10px',
                opacity: .5,
                color: '#fff'
            } });

            //register load handler on iframe which triggers uploadData()
            $('#frame1').load(function(){
                // reload from iframe
                uploadData();
            });

            iTargetNumber = 0;
            // call function uploadData()
            uploadData();
            return true;
        });
}

function uploadData() {
    var dataSet = data[iTargetNumber];
    document.getElementById("statusbar").style.width = (iTargetNumber / data.length * 200) + "px";

    // if file is uploaded to all servers...
    if (iTargetNumber == data.length) {
       document.getElementById("statustext").innerHTML = "done";
       // Reload browser window
       document.location.reload();
       return;
    }

    // status message
    document.getElementById("statustext").innerHTML = "uploading to " + dataSet.sUrl;

    //set "action" attribute in HTML form
    $('#form1').attr('action', dataSet.sUrl);

    //set hidden fields in HTML form
    for (var key in dataSet){
        $('#' + key).attr('value', dataSet[key]);
    }

    // HERE IT HANGS after the first run is completed because of the submit button.

    //submit HTML form with correct values
    $('#form1').submit();

    // increment variable +1
    iTargetNumber++;
}

// initialize variable
var iTargetNumber = 0;

It hangs after the first form is send (because of the submit button).
Using
var myForm = document.forms.form1
var emptyForm = document.createElement('form');
emptyForm.submit.apply(myForm);

insted of
$('#form1').submit();

does not help too. The resulting message has no these lines included:
Content-Disposition: form-data; name="submit"

upload file

An additional hidden field like
<input type="hidden" id="submit" name="submit" value="submit">

that would create a Content-Disposition: form-data; name="submit" does not help too because it would be before the content of the file and there would be no upload file in the end.
================
The problem is solved. The solution is that the JavaScript funktion is called by a button
<button id="button1">upload file</button>

Inside the form is also a hidden submit button
<input type="submit" style="display:none" id="button2" name="submit" value="upload file">

The JavaScript funktion calls this hidden submit button. Now, it is working without problems.

A: Getting a submit method from another form should do the trick.
var myForm = document.forms.id_of_form;
var emptyForm = document.createElement('form');
emptyForm.submit.apply(myForm);


text:
Q: Xamarin MediaElement: setDataSource failed on URL The following works ok:
using Plugin.FilePicker;
using Plugin.FilePicker.Abstractions;
using Xamarin.CommunityToolkit.Core;`
...
    private void btnPlaySource_Clicked(object sender, EventArgs e)
    {
        FileData fileData = await CrossFilePicker.Current.PickFile();
        if (fileData == null)
            return; // user canceled file picking
        mediaElement.Source = MediaSource.FromFile(fileData.FilePath);
        mediaElement.Play();
    }

But these lines throw an exception with a delay of ~7 secs (it's not immediately thrown):
    private void btnPlayURL_Clicked(object sender, EventArgs e)
    {
        //http://docs.google.com/uc?export=open&id=XXXXXXXXXXXXXXXXXX
        var fileURL = GetGDriveFileURL();
        mediaElement.Source = MediaSource.FromUri(fileURL);
        mediaElement.Play();
    }

Java.Lang.RuntimeException: 'setDataSource failed: status = 0x80000000'
What could be the reason of the exception? The URL is 100% working, I tested it on a WPF application's MediaElement and it played fine. I also build the application for Android with Android API level 29 SDK.
<Grid><xct:MediaElement x:Name="mediaElement" Grid.Row="0" AutoPlay="False" ShowsPlaybackControls="True"/>

A: Some of the problems were solved using Xamarin.Essentials.FilePicker. It allows picking audio from Google Drive if it's connected to the Android device. Although, the problem with URL still remains.
//var fileResult = await App.PickAndShow(Xamarin.Essentials.PickOptions.Default);
//if (fileResult == null) return false;
public static async Task<string> PickAndShow(Xamarin.Essentials.PickOptions options)
{
    try {
        Xamarin.Essentials.FileResult result =
        await Xamarin.Essentials.FilePicker.PickAsync(options);
        if (result != null) {
            // For certain types of files, like ".mp3"
            if (result.FileName.EndsWith("mp3", StringComparison.OrdinalIgnoreCase) ||
                result.FileName.EndsWith("wav", StringComparison.OrdinalIgnoreCase))
            {
                // for debug purposes
                bool exists = File.Exists(result.FullPath);
            }
        }
        return result.FullPath;
    } catch (Exception ex) {
        // The user canceled or something went wrong
    }
    return null;
}


text:
Q: how to control the response to a pre-flight request My browser is sending a buffer of data to my server. Unfortunately I have set the requestHeader to  xhr.setRequestHeader("Content-type", 'application/json') with a POST. This is because I am using this var json = JSON.stringify(myArray) in my browser code to create a json buffer. So I am pretty much stuck sending a pre-flight request (due to my use of application/json). Now I am get an error back in my Extensions window:
Access to XMLHttpRequest at
'https://www.xxxubstantiation.com/xxx_crud/xxxit_backend/register' from
origin 'chrome-extension://xxxgnodlhfmhghjhbkkkaaammfocdpib' has been
blocked by CORS policy: Request header field content-type is not allowed by
Access-Control-Allow-Headers in preflight response.

So I figure that I need to clean up the preflight response but I have no idea where that is coming from. My support at Bitnami told me that I can put the following line into the https.conf file:
Header set Access-Control-Allow-Origin "*"
But I already have that  and I don't see that I am setting any content type in the preflight response. Where is the preflight response being setup and how can I either remove it or fix it? Is there any document on how (aka where) to configure a pre-flight response?

A: The server needs to respond with the following in the Header:
Access-Control-Allow-Headers: content-type
Access-Control-Allow-Method: POST
Access-Control-Allow-Origin: *

And the response should be an HTTP 200.
The first header is the one which corresponds to the error message you got and should then disappear ...
--- EXTENDED ANSWER ---
Check Headers of OPTIONS response:
I guess you need to check if the OPTIONS request really sends back all required headers to successfully handle the preflight. So to see the headers of the OPTION request, you could simulate it:
curl  -i \
  -H "Origin: http://your-calling-domain.com/" \
  -H "Access-Control-Request-Method: GET" \
  -H "Access-Control-Request-Headers: X-Requested-With" \
  -X OPTIONS \
  https://the-api-endpoint-you-want-to-call/... \

Here an example for the github api:
curl  -i \
  -H "Origin: http://your-calling-domain.com/" \
  -H "Access-Control-Request-Method: GET" \
  -H "Access-Control-Request-Headers: X-Requested-With" \
  -X OPTIONS \
  https://api.github.com/users/sebhildebrandt/org \

Your OPTION REQUEST need to match with the RESPONSE headers ... more specifically:

*

*Access-Control-Request-Method need to match (be one of) Access-Control-Allow-Method

*Access-Control-Request-Headers need to match with (be one of) Access-Control-Allow-Headers

*Origin need to match with Access-Control-Allow-Origin
Only when all three are fine, the preflight is successful and your POST request will be fired to the server.
Enable CORS Headers on Apache:
In your config file (for your site) or in .htaccess you need to add
Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Headers "Accept,Authorization,Content-Type,Origin"
Header set Access-Control-Allow-Methods "GET, POST, PATCH, PUT, DELETE"
Header set Access-Control-Max-Age: 86400

In this case, the preflight would be valid for one day (86400 seconds)
Then you need to be sure, to enable headers on apache (linux based systems):
sudo a2enmod headers

For Windows you would need:

*

*open httpd.conf at your _apache_folder_/conf

*uncomment #LoadModule headers_module modules/mod_headers.so
Restart Apache
sudo service apache2 restart

This should do the trick ...


text:
Q: Error in mysql part I am new to android development. I have a website already setup which uses a mysql             database. I want to know how can I connect my app to that database. What I have tried shows  an invalid Ip address error in the php part.
here is my code.
Main Activity.java
package com.example.testactivity;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;enter code here
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {

    String id;
    String name;
    InputStream is=null;
    String result=null;
    String line=null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final EditText e_id=(EditText) findViewById(R.id.editText1);
        Button select=(Button) findViewById(R.id.button1);
        select.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            id=e_id.getText().toString();
            select();
        }
    });
    }

    public void select()
    {
        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

    nameValuePairs.add(new BasicNameValuePair("id",id));

        try
        {
        HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://192.168.1.5/select.php");
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();
            Log.e("pass 1", "connection success ");
    }
        catch(Exception e)
    {
            Log.e("Fail 1", e.toString());
            Toast.makeText(getApplicationContext(), "Invalid IP Address",
            Toast.LENGTH_LONG).show();
    }

        try
        {
            BufferedReader reader = new BufferedReader
                (new InputStreamReader(is,"iso-8859-1"),8);
                StringBuilder sb = new StringBuilder();
                while ((line = reader.readLine()) != null)
        {
                sb.append(line + "\n");
            }
                is.close();
                result = sb.toString();
            Log.e("pass 2", "connection success ");
    }
        catch(Exception e)
        {
        Log.e("Fail 2", e.toString());
    }

    try
        {
            JSONObject json_data = new JSONObject(result);
            name=(json_data.getString("name"));
        Toast.makeText(getBaseContext(), "Name : "+name,
            Toast.LENGTH_SHORT).show();
        }
        catch(Exception e)
        {
            Log.e("Fail 3", e.toString());
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
}

activity_main.Xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="39dp"
        android:padding="11dp"
        android:hint="Id"
        android:ems="10"
        android:inputType="number" >

        <requestFocus />
    </EditText>

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/editText1"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="24dp"
        android:padding="11dp"
        android:text="Select" />

</RelativeLayout>

Select.php
<?php
    $host='localhost';
    $uname='root';
    $pwd='';
    $db="android";

    $con = mysql_connect($host,$uname,$pwd) or die("connection failed");
    mysql_select_db($db,$con) or die("db selection failed");

    $id=$_REQUEST['id'];

    $r=mysql_query("select * from category where id='$id'",$con);

    while($row=mysql_fetch_array($r))
    {
        $flag[name]=$row[name];
    }

    print(json_encode($flag));
    mysql_close($con);
?>

A: Do you have android.permission.INTERNET permission in the manifest file?


text:
Q: Bootstrap 3: How to get two form inputs on one line and other inputs on individual lines? I trying to format my registration page with Bootstrap 3.1.1.  I would like the first two inputs to be on the same line while the other inputs are one there own line.  I have played around with the bootstrap classes "row", "form-inline", and "form-horizontal" to no avail.
Does anybody know how to do it?
Here is the Fiddle

<form name="registration_form" id='registration_form' class="form-inline">

            <input id="firstname" class="form-control input-group-lg reg_name" type="text" name="firstname"
                   title="Enter first name"
                   placeholder="First name"/>

            <input id="lastname" class="form-control input-group-lg reg_name" type="text" name="lastname"
                   title="Enter last name"
                   placeholder="Last name"/>

        <input id="username" class="form-control input-group-lg" type="text" autocapitalize='off' name="username"
               title="Enter username"
               placeholder="Username"/>

        <input id="password" class="form-control input-group-lg" type="password" name="password"
               title="Enter password"
               placeholder="Password"/>

 </form>

A: Use
 and

Here a fiddle :https://jsfiddle.net/core972/SMkZV/2/

A: You can wrap the inputs in col-* classes
<form name="registration_form" id="registration_form" class="form-horizontal">

             <input id="firstname" class="form-control input-group-lg reg_name" type="text" name="firstname" title="Enter first name" placeholder="First name">

             <input id="lastname" class="form-control input-group-lg reg_name" type="text" name="lastname" title="Enter last name" placeholder="Last name">

          <input id="username" class="form-control input-group-lg" type="text" autocapitalize="off" name="username" title="Enter username" placeholder="Username">

        <input id="password" class="form-control input-group-lg" type="password" name="password" title="Enter password" placeholder="Password">

 </form>

http://bootply.com/127825

A: You can code like two input box inside one div

            <input style="width:50% " class="form-control " placeholder="first name"  name="firstname" type="text" />
            <input style="width:50% " class="form-control " placeholder="lastname"  name="lastname" type="text" />

A: I resorted to creating 2 style cascades using inline-block for input that pretty much override the field:
.input-sm {
    height: 2.1em;
    display: inline-block;
}

and a series of fixed sizes as opposed to %
.input-10 {
    width: 10em;
}

.input-32 {
    width: 32em;
}


text:
Q: How to fix geocodeAddressString closure in for each I have task model in database (using realm), which consists of id, title, distance, longitude, latitude, customerAddress. I'm trying update my distance to task. I'm new to swift so I do not understand how should I fix geoCoder.geocodeAddressString closure, so that all tasks would update with their distance. (when task does not have latitude and longitude I check if task has customeradress by using geocodeAddressString
    func updateTasksDistance() {
        // get tasks for db
        guard let tasks = Task.getAllUserTasks() else { return }

        // last tracked location
        guard let lastLocation = lastLocation else { return }

        let myLocation = CLLocation(latitude: lastLocation.coordinate.latitude, longitude: lastLocation.coordinate.longitude)

        var distance = 0

        tasks.forEach({ (task) in
            // check if task has longitude and latitude
            if let lat = Double(task.latitude), let long = Double(task.longitude), lat != 0 && long != 0 {
                let taskLocation = CLLocation(latitude: lat, longitude: long)
                distance = Int(taskLocation.distance(from: myLocation))
            } else if !task.customerAddress.isEmpty { // check if task has address
                geoCoder.geocodeAddressString(task.customerAddress) { placemarks, _ in
                    if let placemark = placemarks?.first, let location = placemark.location  {
                        self.taskLocationCoordinate = CLLocation(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude )
                    }
                }
            }

            // check if we have closure location??
            if let taskLocation = taskLocationCoordinate {
                distance = Int(CLLocation(latitude: taskLocation.coordinate.latitude, longitude: taskLocation.coordinate.longitude).distance(from: myLocation))

                taskLocationCoordinate = nil
            }

            // update my distance to task
            updateTaskDistanceDb(task: task, with: distance)

            // reset distance
            distance = 0
        })
    }

// update task distance in db
    fileprivate func updateTaskDistanceDb(task: Task, with distance: Int) {
        let realm = try? Realm()

        if let realm = realm {
            do {
                try realm.write {
                    task.distance = distance
                }
            } catch {
                print("error")
            }
        }
    }

Current result: distance gets updated correctly where closure is not called, but when closure is getting called then I get out of order results
expected result: all tasks distance relative to mine updated correctly

A: Fixed this issue by using this code:
   fileprivate func geoCode(addresses: [String], results: [CLPlacemark] = [], completion: @escaping ([CLPlacemark]) -> Void ) {
        guard let address = addresses.first else {
            completion(results)
            return
        }

        let geoCoder = CLGeocoder()
        geoCoder.geocodeAddressString(address) { placemarks, _ in
            var updatedResults = results

            if let placemark = placemarks?.first {
                updatedResults.append(placemark)
            }

            let remainingAddresses = Array(addresses[1..<addresses.count])
            self.geoCode(addresses: remainingAddresses, results: updatedResults, completion: completion)
        }
    }

    func updateTasksDistance() {
        // get tasks for db
        guard let tasks = Task.getAllUserTasks() else { return }

        // last tracked location
        guard let lastLocation = lastLocation else { return }

        let myLocation = CLLocation(latitude: lastLocation.coordinate.latitude, longitude: lastLocation.coordinate.longitude)

        let dispatchGroup = DispatchGroup()
        for task in tasks where !task.customerAddress.isEmpty {

            let addresses = [task.customerAddress]

            dispatchGroup.enter()
            geoCode(addresses: addresses) { results in
                guard let customerAdress = results.first else { return }
                guard let customerLocatin = customerAdress.location else { return }

                let taskLocation = CLLocation(latitude: customerLocatin.coordinate.latitude,
                                              longitude: customerLocatin.coordinate.longitude )
                // do additional sutff
                dispatchGroup.leave()
            }
        }

        dispatchGroup.notify(queue: DispatchQueue.main, execute: {
               // got all the address
            }
        })
    }

Recursive geocode function helped to calculate all coordinates and dispatchGroup.notify is for waiting till all addresses are geocoded.


text:
Q: homotopy of a real projective plane By Seifert-Van Kampen theorem, $\pi_1(P) = \mathbb Z/2$. If $a$ is a generator of the group, this means that $aa = 1$. In terms of homotopy, this implies that $c_{x_0} \cong w*w$, where $w \in a$ is a loop. How can I visually construct homotopy between these two paths? i.e. make a square-like diagram, where the $x$-axis represents the space $P$ and $y$-axis represents time interval.

A: Let $q : D^2 \to P$ be the quotient map which identifies antipodal points of $S^1$.  We can regard $P$ as the adjunction space $D^2 \cup_\phi S^1$, where $\phi : S^1 \to S^1, \phi(z) = z^2$.
Let $u : [0,1] \to D^2, u(t) = e^{\pi it}$ and $v : [0,1] \to D^2, v(t) = -e^{\pi it}$. Then $q \circ u = q \circ v$. Let us denote this map by $w : [0,1] \to P$. It is a loop based at $q(1)$ representing the generator of $\pi_1(P,q(1))$. The path $\gamma = u * v$ is a loop in $D^2$ (it runs once counterclockwise around $S^1 \subset D^2$) based at $1 \in S^1$ and
$$H: [0,1] \times  [0,1] \to D^2, H(t,s) = (1-s)\gamma(t)+ s$$
is a path homotopy to the constant path based at $1$. Consider the homotopy $H' = q \circ H : [0,1] \times  [0,1] \to P$. This is a homotopy of paths in $P$. We have $H'(t,0) = q \circ (u * v) = (q \circ u) * (q \circ u) = w * w$ and $H'(t,1) = q(1)$.
This proves your claim.


text:
Q: How to test google analytics iOS app installs How can I test google mobile analytics to track iOS app installs without really publishing the app on iTunes?. The only way I find is waiting Apple to release it...

A: Google Analytics provides a campaign troubleshooting guide for iOS
https://developers.google.com/analytics/devguides/collection/ios/v3/campaigns#troubleshoot
The guide doesn't suggest how to test the app without iTunes but it seems that as long as your app had IDFA enabled and is correctly sending it with hits it should not matter if the app is installed from iTunes.

A: After integration of google analytics SDK, you can install your app in your phone. In real time section you can see active users and tracking of events, and if integration is ok you should see one active user.Consider that users installs and sessions are showing ofter couple of days in app overview section. Don't forget that:
The Google Analytics SDK for iOS provides a debug mode that will print useful information about what data is being sent to Google Analytics in your logs.
// Enable debug mode.
[GAI sharedInstance].debug = YES;


text:
Q: How to add more than two options in a drop down custom list radio button? This is my code, its basically a form having two radio buttons, which when chosen display a different list of options in the drop down.

var theForm = document.getElementById('theForm');
var rad = theForm.radios;

for (var i = 0; i < rad.length; i++) {
    rad[i].addEventListener('change', function() {
            theForm.classList.toggle('one');
            theForm.classList.toggle('two');
        });
}
.conditional1, .conditional2 {
    display: none;
}

.one .conditional1 { display: block; }
.two .conditional2 { display: block; }

fieldset { margin: 1rem; }
<form id="theForm" class="one">
<fieldset id="outer">
    <legend>Choices</legend>

        One
        <input type="radio" id="one" name="radios" value="one" checked>

    <fieldset class="conditional1">
            <legend>If One is set</legend>

                <input type="radio" id="aye1" name="condition1" value="aye" checked>
                Aye

                <input type="radio" id="nay1" name="condition1" value="nay">
                Nay

    </fieldset>

        Two
        <input type="radio" id="two" name="radios" value="two">

    <fieldset class="conditional2">
        <legend>If Two is set</legend>

            <input type="radio" id="aye2" name="condition2" value="aye" checked>
            Aye

            <input type="radio" id="nay2" name="condition2" value="nay">
            Nay

    </fieldset>
</fieldset>
</form>

It works well when you have two options but when you add third radio button it starts malfunctioning.
This is the code where I tried to add more radio buttons:

var theForm = document.getElementById('theForm');
var rad = theForm.radios;

for (var i = 0; i < rad.length; i++) {
    rad[i].addEventListener('change', function() {
            theForm.classList.toggle('one');
            theForm.classList.toggle('two');

        });
}
.conditional1, .conditional2, .conditional3, .conditional4 {
    display: none;
}

.one .conditional1 { display: block; }
.two .conditional2 { display: block; }
.three .conditional3 { display: block; }
.four .conditional4 { display: block; }

fieldset { margin: 1rem; }
<form id="theForm" class="one">
    <fieldset id="outer">

    <legend>Please Select File</legend>

        GST
        <input type="radio" id="one" name="radios" value="one">

            <fieldset class="conditional1">
                    <legend>GST</legend>

                        <input type="radio" id="aye1" name="condition1" value="aye">
                        Aye1

                        <input type="radio" id="nay1" name="condition1" value="nay">
                        Nay1

            </fieldset>

        Two
        <input type="radio" id="two" name="radios" value="two">

            <fieldset class="conditional2">
                <legend>If Two is set</legend>

                    <input type="radio" id="aye2" name="condition2" value="aye">
                    Aye2

                    <input type="radio" id="nay2" name="condition2" value="nay">
                    Nay2

            </fieldset>

        Three
        <input type="radio" id="three" name="radios" value="three">

            <fieldset class="conditional3">
                <legend>If Three is set</legend>

                    <input type="radio" id="aye3" name="condition3" value="aye">
                    Aye3

                    <input type="radio" id="nay3" name="condition3" value="nay">
                    Nay3

            </fieldset>

        Four
        <input type="radio" id="three" name="radios" value="four">

            <fieldset class="conditional4">
                <legend>If Four is set</legend>

                    <input type="radio" id="aye4" name="condition4" value="aye4">
                    Aye4

                    <input type="radio" id="nay4" name="condition4" value="nay4">
                    Nay3

            </fieldset>

</fieldset>
</form>

I'm a beginner, so any help is appreciated.

A: The problem is with the way you are changing the classes on your form.
You are using theForm.classList.toggle() which has a binary action - it either adds the class if it doesn't exist or removes it if it does. That is fine when you only have 2 options - its either going to be "one" or "two".
This doesn't work with more than two classes, so you can do this:

*

*Clear the existing class on the form

*Check what radio button has been clicked

*Get the id from that radio button

*Add the corresponding class to the form - your classes match the name of the radio button (e.g. when you click radio button with id "one", the class name to be added to the form is also "one") - this means you can simply use the id as the class name

You can do that in your for loop like this:
for (var i = 0; i < rad.length; i++) {
    rad[i].addEventListener('change', function() {
        theForm.className = "";    /* remove existing class from the form */
        /* "this" is the clicked radio button, so add it's id as the class */
        theForm.classList.add(this.id);
    });
}

Working example:

var theForm = document.getElementById('theForm');
var rad = theForm.radios;

for (var i = 0; i < rad.length; i++) {
    rad[i].addEventListener('change', function() {
        theForm.className = "";    /* remove existing class from the form */
        /* "this" is the clicked radio button, so add it's id as the class */
        theForm.classList.add(this.id);
    });
}
.conditional1, .conditional2, .conditional3, .conditional4 {
    display: none;
}

.one .conditional1 { display: block; }
.two .conditional2 { display: block; }
.three .conditional3 { display: block; }
.four .conditional4 { display: block; }

fieldset { margin: 1rem; }
<form id="theForm" class="">
    <fieldset id="outer">

    <legend>Please Select File</legend>

        GST
        <input type="radio" id="one" name="radios" value="one">

            <fieldset class="conditional1">
                    <legend>GST</legend>

                        <input type="radio" id="aye1" name="condition1" value="aye">
                        Aye1

                        <input type="radio" id="nay1" name="condition1" value="nay">
                        Nay1

            </fieldset>

        Two
        <input type="radio" id="two" name="radios" value="two">

            <fieldset class="conditional2">
                <legend>If Two is set</legend>

                    <input type="radio" id="aye2" name="condition2" value="aye">
                    Aye2

                    <input type="radio" id="nay2" name="condition2" value="nay">
                    Nay2

            </fieldset>

        Three
        <input type="radio" id="three" name="radios" value="three">

            <fieldset class="conditional3">
                <legend>If Three is set</legend>

                    <input type="radio" id="aye3" name="condition3" value="aye">
                    Aye3

                    <input type="radio" id="nay3" name="condition3" value="nay">
                    Nay3

            </fieldset>

        Four
        <input type="radio" id="four" name="radios" value="four">

            <fieldset class="conditional4">
                <legend>If Four is set</legend>

                    <input type="radio" id="aye4" name="condition4" value="aye4">
                    Aye4

                    <input type="radio" id="nay4" name="condition4" value="nay4">
                    Nay3

            </fieldset>

</fieldset>
</form>


text:
Q: how to obtain the post data in binary of PHP I want to post some binary data to PHP.
I know that I can use php://input or $HTTP_RAW_POST_DATA to read it.
But it only can post one binary data.
I want to post two key-value data which respective value is in binary.
How can we do this in PHP?

A: You can encode your binary data in Base64 using base64_encode() and base64_decode().

Base64 encoding schemes are commonly used when there is a need to
  encode binary data that needs to be stored and transferred over media
  that are designed to deal with textual data.

For example, you can post:
key1=eW91cmJpbmFyeWRhdGE=&key2=YmluYXJ5YWdhaW4=

And in your PHP:
$myBinaryData1 = base64_decode($_POST['key1']);
$myBinaryData2 = base64_decode($_POST['key2']);


text:
Q: Hibernate doesn't create dedicated tables in h2 for classes annotated with @Entity So, i have class, annotated with entity and when i start Spring boot application i expect Hibernate to create Table in h2, but i see nothing
h2
Spring application properties got only spring.h2.console.enabled=true
my class looks like
@Entity

public class Author {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

public Long getId() {
    return id;
}

public void setId(Long id) {
    this.id = id;
}

private String firstName;
private String lastName;

private Set<Book> books = new HashSet<>();

public Author() {
}

please Halp

A: JPA has features for DDL generation, and these can be set up to run on startup against the database. This is controlled through two external properties:
spring.jpa.generate-ddl (boolean) switches the feature on and off and is vendor independent.
spring.jpa.hibernate.ddl-auto (enum) is a Hibernate feature that controls the behavior in a more fine-grained way.
Your properties file should look something like this:
spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_ON_EXIT=FALSE
spring.datasource.username=sa
spring.datasource.password=
spring.datasource.driverClassName=org.h2.Driver
spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect


text:
Q: How to skip several lines of an Excel file in php? I have an Excel file (xlsx) with several pictures
And I have this php script that allows me to extract the photos contained in it, insert them in a folder and rename them according to the name of the cells in front of each photo.
The script works but I would like to start reading the lines from line 5. I tried with $i <= 3 to skip the first 4 lines but this causes a shift in the picture names. How can I solve my problem?
<?php

require_once 'PHPExcel/Classes/PHPExcel/IOFactory.php';
$path = 'C:/wamp64/www/Extract_pictures_Excel/imagetest.xlsx';
$objPHPExcel = PHPExcel_IOFactory::load($path);

$i = 0;

foreach ($objPHPExcel->getActiveSheet()->getDrawingCollection() as $drawing ) {
    $i++;

    if ($drawing instanceof PHPExcel_Worksheet_MemoryDrawing) {
        ob_start();
        call_user_func(
            $drawing->getRenderingFunction(),
            $drawing->getImageResource()
        );
        $imageContents = ob_get_contents();
        ob_end_clean();
        switch ($drawing->getMimeType()) {
            case PHPExcel_Worksheet_MemoryDrawing::MIMETYPE_PNG :
                    $extension = 'png'; break;
            case PHPExcel_Worksheet_MemoryDrawing::MIMETYPE_GIF:
                    $extension = 'gif'; break;
            case PHPExcel_Worksheet_MemoryDrawing::MIMETYPE_JPEG :
                    $extension = 'jpg'; break;
     }
    }

    else {
        $zipReader = fopen($drawing->getPath(),'r');
        $imageContents = '';
        while (!feof($zipReader)) {
            $imageContents .= fread($zipReader,1024);
        }
        fclose($zipReader);
        $extension = $drawing->getExtension();
        $chemin = 'C:/wamp64/www/Extract_pictures_Excel/images/';

    }

    $sheet = $objPHPExcel->getActiveSheet();
    foreach ($sheet->getDrawingCollection() as $drawing) {
    $row = (int)substr($drawing->getCoordinates(), 1);

  // retrieve the image data anyway you like

    $stylecode = $sheet->getCell('B'.$row)->getValue();
    $colorcode = $sheet->getCell('C'.$row)->getValue();
    $finalname = $stylecode.'_'.$colorcode;
    $myFileName = $chemin.$finalname.'.'.$extension;
    file_put_contents($myFileName,$imageContents);

  }
}
 ?>

A: I think getDrawingCollection() gives you a list of all the drawings on the active sheet, but this list is not directly related to cell coordinates. So skipping some items of this list is not the same as skipping rows.
Not sure how this goes with the old PHPExcel libs, but with current PhpOffice\PhpSpreadsheet, a Drawing or BaseDrawing objects should have their $coordinates property.
Example:
$sheet = $objPHPExcel->getActiveSheet();
foreach ($sheet->getDrawingCollection() as $drawing) {
  $row = (int)substr($drawing->getCoordinates(), 1);

  // retrieve the image data anyway you like

  $stylecode = $sheet->getCell('B'.$row)->getValue();
  $colorcode = $sheet->getCell('C'.$row)->getValue();
  $finalname = $stylecode.'_'.$colorcode;

  ...
}

You should parse the $drawing->coordinates in order to retrieve values of it's neighbouring cells.


text:
Q: Javascript the Good Parts Closure Syntax in the First Example The Closure section of chapter 4 has the following example.
var myObject = (function() {
    var value = 0;

    return {
        increment: function(inc) {
            value += typeof inc === 'number' ? inc : 1;
        },
        getValue: function() {
            return value;
        }
    }
}());

Why is the function wrapped in an extra set of parenthesis? I've tested it without the parenthesis and the behavior is the same. Am I missing something here, or am I taking this too literally?


text:
Q: Only update all duplicate keys in Mysql table and not add new entries I am trying to just update duplicate keys and NOT add new entries to the Urldup table.
Here is the query i am using but this also adds new entries.
INSERT INTO urldup (url, date, projectname)
Select url, date, projectname
From sample_temp s1
ON Duplicate key update date = now();

I want to just update the duplicate keys and not do an insert of any fresh data.
The url column is a unique key.

A: I have figured it out:
INSERT INTO urldup (url, date, projectname)
Select url, date, projectname
From sample_temp s1
Where url = s1.url
ON Duplicate key update date = now();

A: If you just want to do an update, then use update:
UPDATE urldup u
    SET date = now()
    WHERE exists (select 1 from sample_temp t where u.url = s.url);

This assumes that the duplication is based on the field url.  You can add more conditions in the where clause if other fields are involved.


text:
Q: Pandas repeated columns into new row I have data in a csv which has some columns duplicated, and I want to create multiple rows which repeats some of the columns. I'm trying to do this using pandas in Python.
Take the following as an MWE. I import my data using df = pandas.read_csv('my.csv'), and have something that looks like the following:
a  b  c  c.1  c.2
1  2  3   4    5
6  7  8   9    0

As can be seen columns a and b are unique but c has multiple values. I want to split up the c values into separate rows, duplicating a and b, i.e. achieve the following:
a  b  c
1  2  3
1  2  4
1  2  5
6  7  8
6  7  9
6  7  0

In the interest of not having to type too much I've left out a d column which is similarly duplicated but the solution should be versatile enough to accommodate this.

A: In [426]: pd.lreshape(df, {'c':df.columns[df.columns.str.match('^c\.?\d?')]})
Out[426]:
   a  b  c
0  1  2  3
1  6  7  8
2  1  2  4
3  6  7  9
4  1  2  5
5  6  7  0

A: Use melt:
pd.melt(df, id_vars=['a','b'], value_name='c').drop('variable',1)

Output:
   a  b  c
0  1  2  3
1  6  7  8
2  1  2  4
3  6  7  9
4  1  2  5
5  6  7  0

It's a little tricky to build a general case for multiple variables.  Here's a solution that's based on your case of having dupes for both c and d.  It still uses melt(), but then renames all the c variants to c and same for d.  Then it basically separates the c and d segments and merges them.  It's a little clunky.
df['d'] = df.c
df['d.1'] = df['c.1']
df['d.2'] = df['c.2']

df2 = pd.melt(df, id_vars=['a','b'])
df2.variable = df2.variable.str.replace('^(c|d).*', '\\1')
dupe_vars = ['c','d']

(df2.loc[df2.variable.eq('c')]
    .rename(columns={'value':'c'})
    .drop('variable',1)
    .reset_index(drop=True).merge(
        df2.loc[df2.variable.eq('d')]
           .rename(columns={'value':'d'})
           .drop('variable',1)
           .reset_index(drop=True),
        left_index=True, right_index=True, on=['a','b']))

   a  b  c  d
0  1  2  3  3
1  6  7  8  8
2  1  2  4  4
3  6  7  9  9
4  1  2  5  5
5  6  7  0  0

A: df.set_index(['a','b']).stack().reset_index().drop('level_2',1).rename(columns={0:'c'})
Out[754]:
   a  b  c
0  1  2  3
1  1  2  4
2  1  2  5
3  6  7  8
4  6  7  9
5  6  7  0


text:
Q: CommandSequence taking too long to download With both DKPy-SITL and our APM2 board, the wait_ready method is causing our program to raise an API Exception due to the command list (waypoints) taking too long to download. In the past (with droneapi) this wasn't an issue for me. Some waypoints are being downloaded, but the process takes about 10 seconds for each one, which leads me to believe something weird is going on.
Are there any ways to speed up the download process? I've posted the relevant code below.
self.vehicle = connect(connection_string, baud=baud_rate,
            status_printer=dronekit_printer, wait_ready=True)

and later in another asynchronous method
def commands(self):
    commands = self.vehicle.commands
    commands.download()
    commands.wait_ready()
    return commands

The error occurs on commands.wait_ready(). There has to be a faster way to download commands than sitting there for over 30 seconds on an i7 4790k processor, especially since I've run the same code off a slower computer in the past with droneapi. If need be, I can raise an issue on the dronekit github as well.

A: I had the same issue. First time download call always goes well (0 commands). Once you have uploaded some commands the second time you try to download it fails ('Timeout' exception).
What I did to solve this was calling clear without download after the first time.
Something like this:
            cmds = vehicle.commands
            if not cmds.count > 0:
                # Download
                cmds.download()
                # Wait until download is finished
                cmds.wait_ready()
            cmds.clear()
            # Add / Modify the commands here and then upload them


text:
Q: How do I target an image inside a specific span? I'm building a multiple-choice questionnaire, using jQuery to toggle radio buttons on hover. I have a span for each possible answer, and inside that I have the radio button that I would like to swap the source out on hover.
Now these are images that I made, not actual radio buttons. I have two images, checked and unchecked, and I'm swapping the src when the user hovers.
So when the user hovers over the radio button itself OR the actual text next to the radio button, the button shows a dot.
Here is my span that contains the radio button AND the text (keep in mind I have 5 of these).
A) Naked woman

So how would I use jQuery to target the radio button when the user hovers over the text?
EDIT:
Here is the jQuery I was using to toggle, but it only works when the user hovers over the image.
$('img.radioButton').hover(function () {
    this.src = 'images/radioChecked.png';
}, function () {
    this.src = 'images/radioUnchecked.png';
});

A: $('span.choice').hover(function() {
   $('img.radioButton', this).attr('src', 'images/radioChecked.png')
}, function() {
   $('img.radioButton', this).attr('src', 'images/radioUnchecked.png')
});

If you have more element with class choice then you can try following:
$('span.choice').has('img.radioButton').hover(function() {
   $('img.radioButton', this).attr('src', 'images/radioChecked.png')
}, function() {
   $('img.radioButton', this).attr('src', 'images/radioUnchecked.png')
});

$('span.choice').has('img.radioButton') will detect only span that contains img.radioButton.


text:
Q: Ceaser Cipher-Python, nested loops word = ((raw_input("please enter the letters  ")).upper())
word = word.replace(" ","")
word.decode('utf-8', 'ignore')
wordlist = list(word.strip())
numberlist = []
newlist = []
num = 0

while num <= 13:
    for i in wordlist:    #conversion from letters to numbers
        numberlist.append(ord(i))

    for i in numberlist:    #bigger than Z check
        numberlist[numberlist.index(i)] = i + num+1
        if i >= 90:
            numberlist[numberlist.index(i)] = (i - 90) + 65

    for i in numberlist :
        newlist.append(chr(i))

    print ''.join(newlist)
    num += 1
    del newlist[:]
    del numberlist[:]

I am having problems branching loops on my 'for i in list:' loop

A: I see two things wrong.
The 'list' variable isn't defined.
'for i in list:' won't run if it's not in your program.


text:
Q: Was Emil Blonksy a failure as a super-soldier? In The Incredible Hulk, Emil Blonksy receives a serum based on that from Project: REBIRTH that is intended to make him a stronger, faster soldier. Based on the events at the University confrontation with The Hulk, this was a success.
However as Erskine states in "Captain America: The First Avenger":

The serum amplifies everything that is inside, so good becomes great; bad becomes worse.

The only reason that Emil Blonksy became the Abomination was because he asked for more serum, and eventually pressured Samuel Sterns to give him further treatment.
Given Blonksy's pre-serum attitude, could the serum he received be considered a success (given that it made him 'worse')? Also if the treatment were used on someone good with the qualities of Steve Rogers could the actual success of Project REBIRTH be replicated?
Note: This is primarily about the Marvel Cinematic Universe, but if there are comic references that show that other people have the potential that Steve Rogers had under the influence of the super-soldier serum thats good too.


text:
Q: Acrobat Pro: Creating a tip/instruction message when a user clicks on a text field New to using Acrobat Pro for creating PDF forms. I am working on a page that has several text fields positioned and formatted correctly for a program so the user can click on any of the fields and type in their information.
That works fine, but I would like to have it so (for example), when a user clicks the text field to edit/type in it, a message would appear saying "Make sure the title you include also has the opus number". This would just be a tip and something that would disappear as soon as the user is done with that text field.
Is there a straightforward way to do this that doesn't require several action items (like creating a new text field?)
Thank you so much!

A: A somewhat kludgy, but simple way to accomplish would be to create another text field, making the help text to the default value, have the field read-only, and hidden per default.
Then you would add to the code in the onFocus event:
this.getField("help.myField").display = display.noPrint ;

and to the code in the onBlur event:
this.getField("help.myField").display = display.hidden ;

(assuming that the field with the help text for the field myField is named help.myField).
Instead of having an individual help text field for every data entry field, you could also have a general message field on the page. In this case, you would add the following to the onFocus event:
this.getField("myHelpText").value = "This is the explanation for myField" ;

and to the onBlur event:
this.getField("myHelpText").value = "" ;

And that should do it.
There is also the mousetip text, which appears when the mouse hovers over the field. You either add it in the field properties, or using JavaScript and the userName field object property.


text:
Q: Change CSS during an animation I have some buttons with their CSS style.
When an animation starts I would like to change their style for the duration of the animation.
Stuff like changing the color, changing the pointer, changing the hover; to make them look "disabled" basically.
I have a global var which is "true" while the animations runs, and turns "false" when the animation is not running.
In order to achieve this goal, I have tried many things, but none of them worked, I tried:

*

*changing the name of the class based on the var value, and create two different CSS styles -> didn't work because it didn't get updated with the change of the var

*changing the style within REACT inside the function when the animation is called and changing it back when it's over. Using: document.getElementById("firstOne").style =
The second option it's the only one that actually worked well. The problem I can't edit back the hover to where it was before.
The question:
Is there a way to change the hover from React? Something like:
document.getElementById("firstOne").style =  ;
If not, is there a way to just tell it "from now just follow the style written on the CSS file"?. To kind of setting the style back to before.
If not, any other ideas on how to achieve my goal?
Thank you


text:
Q: How to make Ctrl+V work in CLion I am having difficulty getting Ctrl+V to paste code in CLion (I am using version 1.1.1 for Windows). When I try to paste code copied using Ctrl+C from e.g. a website or another program, it only seems to work occasionally. Usually it pastes a piece of text that was not the most recently copied.
I use other JetBrains IDEs (IntelliJ IDEA, PyCharm) and have never had any problems with something so basic.
Has anybody else encountered this problem and found a solution to it?

A: I had the same problem and this is the way I fixed it:

*

*Ctrl+Shift+V (brings up the clipboard history)

*Delete all entries

*Recopy what you wanted to paste from outside CLion

*Try pasting again

Let me know if it didn't work for you so I can see if there is some step you are missing. Hope this helps!

A: I had the same problem and this is the way I fixed it:
Go to: Settings > plugins  and disable 'ideaVim' plugin


text:
Q: select quotes but NOT apostrophes in REGEX I would like to achieve this amazing result (I'm using Ruby):
input:  "Joe can't tell between 'large' and large."
output: "Joe can't tell between large and large."

getting rid of the quotes but not of the apostrophe
how can I do it in a simple way?
my failed overcomplicated attempt:
 entry = test[0].gsub(/[[']*1]/, "")

A: Here's a script to demo an answer:
x = "Joe can't tell between 'large' and large."
puts x.gsub(/'\s|\s'/, " ")
# Output: Joe can't tell between large and large.

To decode what this script does - the gsub / regex line is saying:

Find all (an apostrophe followed by a space '/s) or (a space
  followed by an apostrophe \s') and replace it with space.

This leaves apostrophes that aren't adjacent to spaces intact, which seems to remove only the apostrophes the OP is trying to remove.

A: Simplest one for your situation could be something like this.
Regex: /\s'|'\s/ and replace with a space.
Regex101 Demo

You can also go with /(['"])([A-Za-z]+)\1/ and replace with \2 i.e second captured group.
Regex101 Demo

A: Maybe this one?
entry = test[0].gsub(/[^']/, "")

But it should remove all '.

A: This does exactly what you are looking for, including ignoring the posted comments Students' example.
entry = test[0].gsub(/'([^\s]+)'/, '\1')
I don't have ruby set up, but i confirmed this works here: http://tryruby.org/levels/1/challenges/0
Here is an example on regex101:
https://regex101.com/r/aY8aJ3/1


text:
Q: Sending data into server using httpdelete I am new in android.Currently i am doing web service connection part in android.Here i am using httpdelete method.But i can't be able to send values into server.Here i attach my code.please give me a solution.The passing JSON object is given below.
JSONObject obj = {"encrypted_device_id":"c02c705e98588f724ca046ac59cafece65501e36","card_name":"disc"}

CODE
public String getWebDataDelete(String page,JSONObject obj)
        {

            String result=null;
            HttpParams myParams = new BasicHttpParams();
            HttpConnectionParams.setConnectionTimeout(myParams, 10000);
            HttpConnectionParams.setSoTimeout(myParams, 10000);
            HttpClient httpclient = new DefaultHttpClient(myParams);
            try
            {
                  HttpDelete httppost = new HttpDelete(Connector.URL+page);
                 httppost.setHeader("Content-type", "application/json");
                 httppost.setHeader("api_key", "123456");
                 StringEntity se = new StringEntity(obj.toString());
                 se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
                 httppost.setEntity(se);
                 HttpResponse response = httpclient.execute(httppost);
                 result = EntityUtils.toString(response.getEntity());

            }
            catch (ClientProtocolException e)
            {

            }
            catch (IOException e)
            {

            }
            return result;

 }

A:   Try this one, working for me

  DefaultHttpClient httpclient = new DefaultHttpClient();
        HttpPost request = new HttpPost(Url);
        StringEntity se = new StringEntity(JSONobject.toString(), "UTF-8");
        se.setContentType("application/json;charset=UTF-8");
        se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
                "application/json;charset=UTF-8"));
        request.setEntity(se);
        HttpResponse httpresponse = httpclient.execute(request);
        HttpEntity resultentity = httpresponse.getEntity();
        InputStream inputstream = resultentity.getContent();
        result = convertStreamToString(inputstream);

  private static String convertStreamToString(InputStream inputstream) {
    // TODO Auto-generated method stub
    String line = "";
    StringBuilder total = new StringBuilder();
    BufferedReader rd = new BufferedReader(new InputStreamReader(
            inputstream));
    try {
        while ((line = rd.readLine()) != null) {
            total.append(line);
        }
    } catch (Exception e) {
    }
    return total.toString();
}


text:
Q: I'm trying to publish a message of a Tizen based app on ros using rosbridge and i get an error as the title says, I'm trying to publish a message on ros using rosbridge, because my app is written in javascript. Basically i want to cast a stream of heart rate data on a pc running ros to so some elaboration. The app is running on a Tizen based smartwatch. If i try to publish geometry messages, like the device orientation, i have no problem and they are published on ros. I tried the sensor message type (channelfloat32 in particular) to cast the stream of the heart rate with no success. I investigated on the type of the data coming out from the sensor and i discovered that is a number type data of javascript.
So i used the standard message type (Float64 in particular because, as far as i know based on some searching, apparently javascript uses only this type for numbers) with no success again.
Maybe i could cast the variable or change its type, but i don't know if this could be a possible solution and i really don't know how to do it, maybe i only have to change the type of the ros message.
As you can see from my previous questions I'm very new to coding and I'm again on the same project.
Thank you in advance for your help!
Marco
The code is below:
document.addEventListener('tizenhwkey', function(e) {
    if(e.keyName === "back")
        window.webapis.motion.stop("HRM");
        tizen.application.getCurrentApplication().exit();
});

function Connect(){
var ip;
var connection=false;

if (document.getElementById("ip").value==="")
{
    ip="10.42.0.1";
}
else
{
    ip=document.getElementById("ip").value;
}

var ros = new ROSLIB.Ros({
    url : 'ws://' + ip +':9090'
    });

ros.on('connection', function() {
    connection=true;
    document.getElementById("Connection_status").setAttribute("color","green");
    document.getElementById("Connection_status").innerHTML = 'Connected';
    tizen.power.request("SCREEN", "SCREEN_DIM");
});

ros.on('error', function(error) {
    document.getElementById("Connection_status").setAttribute("color","orange");
    document.getElementById("Connection_status").innerHTML = 'Error';
});

ros.on('close', function() {
    document.getElementById("Connection_status").setAttribute("color","red");
    document.getElementById("Connection_status").innerHTML = 'Unconnected';
    connection=false;
    tizen.power.release("SCREEN");
});

var RatePub = new ROSLIB.Topic({
    ros : ros,
    name : '/HeartRateData',
    messageType : 'std_msgs/Float64'
});

window.webapis.motion.start("HRM", onchangedCB);

function onchangedCB(hrmInfo)
{
   var data = hrmInfo.heartRate;
   document.getElementById("mytext").innerHTML = 'Heart Rate= ' + data + ' bpm';

   var Float64 = new ROSLIB.Message({
            data:[data]
        });

        if(connection===true)
            {
            RatePub.publish(Float64);
            }
        else
        {
            document.getElementById("mytext").innerHTML = 'Heart Rate= 0 bpm';
        }

        }}

A: If you are reading HRM data from Tizen wearable device you may use tizen.humanactivitymonitor of Human Activity Monitor API Instead of using window.webapis.motion
Rather using
window.webapis.motion.start("HRM", onchangedCB);

function onchangedCB(hrmInfo) {
    var data = hrmInfo.heartRate;
    document.getElementById("mytext").innerHTML = 'Heart Rate= ' + data + ' bpm';
    ...
    ..
   }

You may try
var dataCount = 0;

function onsuccessCB(hrmInfo)
{
   console.log("Heart Rate: " + hrmInfo.heartRate);
   console.log("Peak-to-peak interval: " + hrmInfo.rRInterval + " milliseconds");
   dataCount++;

   ...
   ..

   if (dataCount > 10){
       /* Stop the sensor after detecting a few changes */
       tizen.humanactivitymonitor.stop("HRM");
   }
}

tizen.humanactivitymonitor.start("HRM", onsuccessCB);

And add the necessary privileges in config.xml file
<tizen:privilege name="http://tizen.org/privilege/healthinfo"/>
<tizen:privilege name="http://tizen.org/privilege/power"/>

According to the Tizen API reference datatype of the heartRate is long.
Please Check the Tizen Human Activity Monitor Guide and Tizen API reference for details implementation.


text:
Q: Textbox as integer? I have made a textbox which is only able to contain numbers. However, I want to multiply the number written in the textbox by 2, and then display it. For some reason the displayed number is always 0. I am using Visual Basic express edition 2008
Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
    Dim TextBox1 As Integer

    If Asc(e.KeyChar) < 48 Or Asc(e.KeyChar) > 57 Xor Asc(e.KeyChar) = 8 Xor Asc(e.KeyChar) = 44 Xor Asc(e.KeyChar) = 46 Then
        e.Handled = True
        MessageBox.Show(TextBox1 * 2)
    End If
End Sub

A: You created an int variable
Dim TextBox1 As Integer

Which defaults to 0.  Then you multiply it by 2.
MessageBox.Show(TextBox1 * 2)

0 * 2 = 0.
You need to get the Value from the TextBox, parse the text to an int (int.Parse), then multiply that value.

A: Try doing this:
Dim TextBox1 As Integer
TextBox1 = Convert.ToInt32(TextBox1.Text)

A: If It is a text box you are using, and not just a variable you've named textbox1 then simply use
'messageBox.show(CInt(TextBox1.Text) * 2))'

A: Maybe the example below will help...
Private Sub TextBox1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TextBox1.KeyPress

    Select Case Convert.ToInt16(e.KeyChar)

        Case 48 To 57 ' only allow numbers in this Case
            MessageBox.Show(CStr(CDec(e.KeyChar.ToString) * 2))

        Case Else ' handle everything else here
            e.Handled = True
    End Select
End Sub


text:
Q: Readability Scores for Multiple Text Files in R I am very new to R. I would be very thankful if you could share a code to help me with the following.
I want to calculate readability scores (such as: FOG Index, SMOG Index, Flesch–Kincaid Score etc.) using R for several independent text files (.txt) present in a folder.
I also want one output file (.csv) which includes readability scores of the text files.
Many thanks in advance.
Warm Regards,
Farhan


text:
Q: Upload images to server in android? In my android application, i am uploading images to the server(C#) via http post and its successfully uploaded to the server.
Hear is the code for image upload:
public static String uploadImagePost(String url, String imagePath) throws Exception  {

        HttpClient  httpClient      =   new DefaultHttpClient();
        HttpContext localContext    =   new BasicHttpContext();
        HttpPost    httpPost        =   new HttpPost(url);
        // add header
        httpPost.addHeader("FileName",      "android"+System.currentTimeMillis()+".jpg");
        httpPost.setHeader("User-Agent",    "android_client");
        httpPost.addHeader("accept",        "application/json");

        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        /* example for setting a HttpMultipartMode */
        builder.setMode(HttpMultipartMode.RFC6532);
        /* example for adding an image part */
        builder.addPart("image/jpeg", new FileBody(new File (imagePath)));
        httpPost.setEntity(builder.build());

        HttpResponse response = httpClient.execute(httpPost, localContext);
        System.out.println("Response Code : "   + response.getStatusLine().getStatusCode());
        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

        StringBuffer result = new StringBuffer();
        String line = "";
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }
        return result.toString();
 }

So my problem is the image witch i have uploaded is not readable.
then i have check the source of the image using editor so i have noticed following text lines are included in the image source.
Header:
--5VkWFM_KqrrWu4l-DOUIyJabHz5tZ5_jp
Content-Disposition: form-data; name="image/jpeg"; filename="tempimage.jpg"
Content-Type: application/octet-stream

Footer:
 --5VkWFM_KqrrWu4l-DOUIyJabHz5tZ5_jp

After removing of above header and footer and save the image so image is now readable.So the problem is header and footer. How can i fixed this issue?

A: Image decoding
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                BitmapDrawable drawable = (BitmapDrawable) userPhoto.getDrawable();
                yourSelectedImage= drawable.getBitmap();
                yourSelectedImage.compress(Bitmap.CompressFormat.PNG,100,baos);
                imageData = baos.toByteArray();

Send image using Httppost
  public static HttpResponse sendImage(byte[] image) {
    HttpResponse responsePOST = null;
    try {
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(postURL);
        post.setHeader("Accept", "application/json");
        ByteArrayBody bab = new ByteArrayBody(image, firstname+".png");
        MultipartEntity reqEntity = new MultipartEntity(
                HttpMultipartMode.BROWSER_COMPATIBLE);
        reqEntity.addPart("user_profile[image_attributes[attachment]]", bab);
        post.setEntity(reqEntity);
        responsePOST = client.execute(post);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return responsePOST;
}


text:
Q: Local sequence cannot be used in LINQ to SQL implementation of query operators except the Contains() operator I am using LINQ in my project and my code is:
var SE = from c in Shop.Sections
                    join c1 in obj.SectionObjects on c.SectionId equals c1.SectionId
                    select c;

 dataGridView1.DataSource = SE;

but I face this error in line dataGridView1.DataSource = SE;
error message is:

Local sequence cannot be used in LINQ to SQL implementation of query operators except the Contains() operator.

A: You can't use a Join between a SQL source and a local source.  You'll need to bring the SQL data into memory before you can join them.  In this case, you're not really doing a join since you only take the elements from the first collection, what you want is a select...where...selectid in query, which you can get using the Contains method.
 var SE = Shop.Sections.Where( s => obj.SectionObjects
                                       .Select( so => so.SectionId )
                                       .Contains( s.SectionId ))
                       .ToList();

Translates to
select * from Sections where sectionId in (...)

where the values for the in clause come from the list of ids in the collection of local objects.

A: You can't join local source to SQL source,
but you CAN join SQL source to local, v.v.
var SE = from c1 in obj.SectionObjects
              join c in Shop.Sections on c1.SectionId equals c.SectionId
              select c;

In other words, local source must come first

A: This should work and be done on the database side (using IN), rather than in memory:
var SE = from c in Shop.Sections
        where obj.SectionObjects.Select(z => z.SectionId).Contains(c.SectionId)
        select c;

L2S Profiler is very helpful for these kinds of things - you can compare the different SQL being generated by my solution and other solutions.

A: var SE = from c in Shop.Sections.AsEnumerable().ToList()
                    join c1 in obj.SectionObjects.AsEnumerable().ToList() on c.SectionId equals c1.SectionId
                    select c;
dataGridView1.DataSource = SE;


text:
Q: Unable to SSH to server unless a VNC connection is first established I have recently set up an Ubuntu 10.10 (32bit) server on a VPS host. Following the Ubuntu installer I added OpenSSH. Very little else has been installed and it's the default OpenSSH configuration.
For some reason I cannot SSH to the box unless I first open a TightVNC connection through the hosts administration console. As soon as the attempt to VNC to the box is made I'm able to SSH directly to the box (eg. with PuTTY). Closing TightVNC doesn't matter - I can continue to use the open SSH connection and create new sessions.
Any ideas what the issue is and how I go about fixing it?

A: Thanks for the helpful comments - it assisted me to find the actual issue.
The VPS service is wheresmyserver.co.nz - according to this documentation:

Any time you access a server via the WMS control panel, your IP address is transparently and automatically permitted temporary access to all ports on that specific server. When you leave the control panel, those ports are automatically closed behind you.

In reality this takes effect on connecting to the VNC session and this explained why I was getting access temporarily.
The actual issue was that the firewall was configured to only allow http, https and ping inbound. Adding port 22 the firewall inbound rules fixed the issue. Head, meet desk.
Thanks again!


text:
Q: Is there a badge for soldiering on? I just had a question that was thrown into review for two weeks, lots of comments, and about three manual resubmits to get it put up. I don't want to be a karma (rep?) whore by linking to it here, but let's just say that while my original question wasn't totally in-line with Stack Overflow policy, it wasn't much different than out-of-date versions I was trying to replace.
In general, it felt like I was under assault by the tyranny of the crowd as I think most voters just skimmed it instead offering an edit or telling me how it differed from the prior examples.
I tried to stay humble and eventually the excellent @Brad Larson swooped in, did great rewrite, and cleared all the downvotes. I waited a week and then through 50 rep points on a bounty for the question before I finally got an answer to a question a few people had asked previously.
Anyway, is there a badge that rewards persistence like this? Because after such an arduous review process, I kind of feel like I deserve one :p

A: The question in question: How do you programmatically access the ambient light sensor on Mac OS X 10.5+?
The original question:

(As others have been marked as dupes please note that this is NOT a
  duplicate of 1 nor 2: those solutions are broken as of OS X 10.5 and
  above!)
Does anyone know of the private API and any related libraries for
  accessing the ambient light sensor data?

Revision History
If anyone deserves a badge it's Brad Larson, for taking the time to perform the salvage operation...


text:
Q: Releasing UIImage's Crashes the App My app loops through array of image paths and merges all those images into one. The code is below. However, the app crashes when I release the image with (gdb) printed out in my console. If I remove image release line, then it works fine but this may probably lead to memory leaks. Please look at this code and explain why this happens and what can be improved. Thank you.
UIGraphicsBeginImageContextWithOptions(CGSizeMake(width*len+padding*len+padding,
                                                  height+padding*2),
                                       YES, 0.0);
do{

        //draw image
        path = (NSString*)[_imageData objectAtIndex:i];
        UIImage * img = [[[UIImage alloc] initWithContentsOfFile:path]
                           cropCenterAndScaleImageToSize:CGSizeMake(width, height)];
        [img drawAtPoint: CGPointMake(width*i+padding*i+padding,padding) blendMode:kCGBlendModeNormal alpha:1];
        [img release]; //APP CRASHES HERE BUT WORKS IF THIS LINE REMOVED
        i++;
    }while (i<len);
    UIImage *result = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    UIImageWriteToSavedPhotosAlbum(result, self,
                                   @selector(image:didFinishSavingWithError:contextInfo:),
                                   nil);

A: The problem is that you are not releasing the allocated image. You are releasing the autoreleased cropped image and leaking the allocated image.
Change this:
UIImage * img = [[[UIImage alloc] initWithContentsOfFile:path]
                   cropCenterAndScaleImageToSize:CGSizeMake(width, height)];
[img drawAtPoint: CGPointMake(width*i+padding*i+padding,padding) blendMode:kCGBlendModeNormal alpha:1];
[img release];

to:
UIImage *original = [[UIImage alloc] initWithContentsOfFile:path];
UIImage *cropped = [original cropCenterAndScaleImageToSize:CGSizeMake(width, height)];
[cropped drawAtPoint:CGPointMake(width * i + padding * i + padding, padding) blendMode:kCGBlendModeNormal alpha:1];
[original release];

I'm assuming the cropCenterAndScaleImageToSize: is some category method that returns an autoreleased UIImage reference.


text:
Q: How to handle pop up window in appium with webdriver I unable to click Open button and getting an exception as "No such element exception". I tried all XPath and id but same exception I am getting. I have tried getContextHandles() and it returns size as one. it means control cannot switch. Kindly help me to click the "Open" button.
Below are the xPath i tried.
By.name("Open");
By.xpath("//android.widget.Button[@index='1']");
By.xpath("//android.widget.Button[@resource-id='org.hola:id/btn_open']");
By.xpath("//android.widget.Button[@resource-id='org.hola:id/btn_open' and @index='1' and @text='Open']");

A: If this popup is coming after launching any app then you have to set the "appActivity" and "appPackage" capability in your code.

A: Try MobileBy instead of By
MobileBy.name("Open");
MobileBy.xpath("//android.widget.Button[@index='1']");
MobileBy.xpath("//android.widget.Button[@resource-id='org.hola:id/btn_open']");
MobileBy.xpath("//android.widget.Button[@resource-id='org.hola:id/btn_open' and @index='1' and @text='Open']");

A: Locator can be identified by using UIAutomator viewer tool. Following code setup use to handles the pop-up window in Appium
WebDriver driver;
@BeforeTest
static void setup() throws MalformedURLException{
    DesiredCapabilities cap = new DesiredCapabilities();
    cap.setCapability(CapabilityType.PLATFORM, "Android");
    cap.setCapability(CapabilityType.VERSION, "Android-version");
    cap.setCapability("deviceName", "connected device name");
    cap.setCapability("appPackage", "App package name");
    cap.setCapability("appActivity", "App activity");
    driver = new RemoteWebDriver(new URL("http://127.0.0.1:4723/wd/hub"), cap);
}
@Test
static void Selendroid() throws InterruptedException{
    Thread.sleep(2000);
    driver.findElement(By.name("Locator")).click();
    System.out.println(driver.findElementById("android:id/message").getText());
    driver.findElement(By.name("Locator")).click();
}

For Browser alerts use driver.switchTo().alert() method to Handle


text:
Q: How can a initialize sw-precache with all site pages I would like to make an app available completely offline.  ie user clicks a button (or not, this could happen automatically) while online and every page, including all dynamic pages, and assets on the site could be cached.
I understand I would need to generate a list of all assets, is there a tool that can do this, or any way built into sw-precache?
Also, how large can the cache be, and how long is it available?  I assume it can be any size and available unless user specifically clears their browser cache.

A: If you have a local directory full of static files (HTML, JS, CSS, etc.), sw-precache can be configured to automatically precache all of them (or some subset of them) based on the patterns you pass in to the staticFileGlobs option. The previously precached entries in users' browsers will be kept up to date as you make local changes, regenerate your service-worker.js, and redeploy.
In general, there aren't hard upper limits on the maximum amount of data that can be stored using the Cache Storage API. It depends on the amount of space that's currently free (potentially along with other heuristics).
You should be considerate when determining what files get precached and ensure that they're actually files that your users are likely to find useful. For example, if the very first time a user visits your (hypothetical) documentation site, they end up downloading and storing thousands of individual HTML documents, that's a waste of bandwidth for both your servers and your users—in addition to taking up space on users' devices.
If you have a large trove of resources that are optional or not likely to be needed by all visitors, that using a precaching strategy for the crucial resources, along with a runtime caching strategy for the optional resources, is your best bet. You can combine the runtime caching strategy with a maximum cache size or maximum age, and the underlying sw-toolbox library will take care of deleting old entries for you.


text:
Q: How to DROP a table or stream in KSQL when topic was dropped first Using KSQL (Confluent: Version: 5.0.1) I'm able to drop a table / stream normally (using DROP [TABLE|STREAM]) <NAME> when the linked topic exist and when it is registered (Registered=true).
However, if the topic is dropped first (Registered=false) then the associated stream or table can't be dropped with KSQL pointing out that "No topic with name Foo was registered".
The problem is that the stream / table still shows in the list and no new stream / table can be added using the same name.
Is there any way to delete them after the topic was dropped?

A: From the official documentation, I would do it like this:
SHOW QUERIES;

Write down the QueryID;
TERMINATE <QueryID>;

DROP TABLE <tablename>;

[See documentation...]

*

*https://docs.ksqldb.io/en/latest/developer-guide/create-a-table/#delete-a-ksqldb-table

*https://docs.ksqldb.io/en/latest/developer-guide/ksqldb-reference/terminate/

A: I think I found an answer, or at least in the right direction.
You need to re-register the topic with the stream.  After a bit of hacking around, I managed to reattach my topics to streams, the drop the streams.
REGISTER TOPIC <ksql_topic_name> WITH (KAFKA_TOPIC='<kafka_topic_name>', VALUE_FORMAT='<format>');

Then,
DROP STREAM <stream_name>;

I don't know if this works in all cases, but it got me back to where I want to be.  If anyone else can iterate on this and find a more robust solution I would like to hear about it.

A: I've been wrestling with these type issues for a while.  Here's where I'm at, from my notes:
Having trouble deleting streams/tables/topics?  Delete them in zookeeper:

*

*Shut down any producers or consumers associated with topics you'll be deleting

*Attempt to drop your tables and streams from KSQL CLI

*Shut down KSQL server

*Delete topics with 'kafka-topic' CLI

*Delete in zookeeper like this:
zookeeper-shell localhost:2181
ls /brokers/topics
_confluent-controlcenter-5-0-0-1-TriggerEventsStore-changelog, _confluent-controlcenter-5-0-0-1-error-topic, ...
rmr /brokers/topics/yourTopicName
Now do a " kafka-topics --list --zookeeper localhost:2181' and they should be gone for good.
OR, for the ABSOLUTE NUCLEAR OPTION:

*

*Attempt to drop your tables and streams from KSQL CLI

*Shut down KSQL server

*Shut down your brokers and zookeepers

*Delete eveything in the kafka logs dir on each broker node (location of dir is defined in your properties file).

*Start up your zookeepers again and delete the /brokers/topics from zookeeper CLI

Start everything back up and it should all be gone.  But be careful, you'll lose
everything, all your data.

A: You would have to terminate any running queries first.
SHOW QUERIES;  --> that will show you the active queries (COPY QUERY ID)

Then:
TERMINATE [QUERY ID];

Then:
    DROP [TABLE OR STREAM];


text:
Q: Using an arbitrary plugin in Jenins 2 Pipeline scripts Using the Snippet Generator tool in Jenkins 2, I can setup a plugin like I would within a job, and then it will generate me the Groovy I can use in my Pipeline script.

But what if the plugin I am interested in instrumenting isn't listed in the "Sample Step" drop down in the Snippet Generator? How do I determine how to create a script block to instrument the plugin I want to use?
In my case, I would like to use the "Flexible Publish" plugin within my Pipeline script.

A: You can't use plugins which are not compatible with pipeline generally.
Plugins need to be modified more or less to be compatible.
See https://github.com/jenkinsci/pipeline-plugin/blob/master/COMPATIBILITY.md

A: To be complete you need to know that snippet generator only shows compatible plugins that declare a specific help page in plugin's code. If we take the example of docker-workflow plugin, you can see in the code that it defines a help page for DockerDSL, which means that a Snippet Generator will be available for DockerDSL step.
Therefore you should always check Jenkins plugins compatibility page (as arasio mentionned it) and not what you see in Snippet Generator.


text:
Q: USB3 does not work in fresh Ubuntu install I have a new computer with an Asus P8Z68-V LE + Intel  i2500 + 8GB of RAM.
I installed Ubuntu without any issue, but the USB3 (from the motherboard - on the back of the computer) doesn't work.
I plug a USB stick -- nothing, I plug my USB3 external drive -- nothing, when I plug them into the USB2 and everything works perfectly.
Also, I ran all updates and everything is up to date.
What am I missing?

A: Yes, it's a hardware problem. I'm having the same problem on the same type board (Asus p8z77-i) I'm currently building, and I know why; USB 3 won't work on anything but Windows 7 and up (the manual will tell you this in another way as well). It's not the fault of ASUS, it's most motherboards at this point. Look up Linux compatible USB 3 cards because it's worth it (this is true of PCI-E cards for USB 3 functions as well. On New Egg, I found 4 usable cards and 2 were sold out (which should tell you how in demand non-windows USB 3 cards are for us).
But they're less then 40 dollars and USB 3 is 5x faster so it'll save you alot of wait time and frustration. I hope this helps!

A: 12.04 should be released any day. I would try that before building a custom kernel. I have
an add-in USB card with a NEC controller that works with 11.10. My lspci -nn for that card looks like this
02:00.0 USB Controller [0c03]: NEC Corporation uPD720200 USB 3.0 Host Controller [1033:0194] (rev 03)

The driver module is xhci_hcd
$ ls -l /sys/bus/pci/devices/0000\:02\:00.0/driver
lrwxrwxrwx 1 root root 0 2012-04-24 17:31 /sys/bus/pci/devices/0000:02:00.0/driver -> ../../../../bus/pci/drivers/xhci_hcd

It is not impossible that the only thing that is needed is a mapping from your pci id
to driver, and the kernel developers are usually quick to add that. Then it might take some
time to get into the released distributions.


text:
Q: How to specify putting zip into jfrog artifactory? I have directory like /tmp/some-js/(a lot of folders)
I added it into zip /tmp/some-js.zip
I have structure in artifactory like /npm-dev/some-js/*
I put into artifactory this zip with command
curl -u user:api-key -k -X PUT https://xxx.xx.xx.xx:8081/artifactory/npm_dev/some-js/ -T /tmp/some-js.zip
And I have got directory in artifactory /npm-dev/some-js/some-js.zip/*
There is a way to specify unpacking some-js.zip contents into /npm-dev/some-js ?

A: Uploading an archive file (such as a zip file) to Artifactory and extracting its content to a specific directory is done by:
PUT https://<jfrog-platform>/artifactory/the-repo/path/to/dir/file.zip
X-Explode-Archive: true

<file-content>

The content of file.zip will be extracted and deployed under the-repo/path/to/dir/, preserving the relative directory structure in the zip file. So if file.zip has the following structure:
foo/
  |- bar.txt
  |- baz.txt

The following files will be created in Artifactory:
the-repo/path/to/dir/foo/bar.txt
the-repo/path/to/dir/foo/baz.txt

Using curl and the details in the question:
curl -u user:api-key \
     -k \
     -X PUT \
     https://xxx.xx.xx.xx:8081/artifactory/npm_dev/some-js/some-js.zip \
     -T /tmp/some-js.zip
     -H "X-Explode-Archive: true"

For more information, see the documentation on Deploy Artifacts from Archive