text:
Q: SQL select and display all values in a group that contains at least one value maybe someone has already answered this, but I'll try it here.
Say I have three columns  :
 **NAME**    **TEST SCORE**   **DATE**
  Chloé          67             Jan 8th
  Dennis         98             Jan 8th
  Zakary         45             Jan 8th
  Chloé          75             July 1st
  Dennis         91             July 1st
  Zakary         76             July 1st

And I would like to not only get the names, but also all the test results and dates of students having had at least one grade below 50%, so as to get something like :
 Zakary 45 Jan8th
 Zakary 76 July1st

What order could I use? I have tried having, but it doesn't seem to work

A: With EXISTS:
select t.* from tablename t
where exists (
  select 1 from tablename
  where name = t.name and score < 50
)

or:
select * from tablename
where name in (select name from tablename where score < 50)

A: I don't know which DB you are using, but you should try some statement like:
SELECT NAME, TEST_SCORE, DATE
  FROM STUDENTS
 WHERE NAME IN
    (SELECT DISTINCT NAME FROM STUDENTS WHERE TEST_SCORE < 50)

Hope it helps.
Enjoy!

A: Using join.
select a.*
from tablename a
join (select distinct name from tablename where score<50) b on a.name=b.name


text:
Q: Communication with exe file using Java directly? There are few methods in a executable(c#) file which are entry points to the application, I want to access this methods directly from java, Is there any way I will be able to do that?, I don't want use JNI layer in between.Previously I created a .NET client to access exe and used JNI4NET to connect from java to .net, This layer I have to completely remove and make a connection to exe directly from java and Can I use proxygen against exe to create java native interfaces?

A: Run a new program with ProcessBuilder. You cannot modify arguments in any already running program, so terminate them first.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Changing value of interface implemented by superclass from subclass affects all instances Consider the following program:
SomeClass.java:
package somepackage;

import java.util.List;

public class SomeClass implements SomeInterface {

    public SomeClass(boolean add){}

    public static void main(String[] args){
        SomeSubclass sub1 = new SomeSubclass(false);
        for (String s : sub1.getList())
            System.out.println("before: " + s);
        SomeSubclass sub2 = new SomeSubclass(true);
        for (String s : sub1.getList())
            System.out.println("after: " + s);
    }

    @Override
    public void addToList(String s) {
        someList.add(s);
    }

    @Override
    public List<String> getList() {
        return someList;
    }

}

SomeSubclass.java:
package somepackage;

public class SomeSubclass extends SomeClass {

    public SomeSubclass(boolean add){
        super(add);
        if (add)
            this.addToList("a");
    }

}

SomeInterface.java:
package somepackage;

import java.util.ArrayList;
import java.util.List;

public interface SomeInterface {

    List<String> someList = new ArrayList<String>();

    public void addToList(String s);

    public List<String> getList();

}

The program, when run, outputs the following:
after: a
The first debug message is not sent, because the list of the first instance of SomeSubclass is empty. However, once an element is added to the list of the second instance, the first instance also has the element added. This occurs when compiled and run with JDK 1.8 and Java SE 8, respectively. From what I understand, it shouldn't be happening. Is it intentional, and if so, what is the proper way of accomplishing this task?
I also feel as though I should mention the practical implementation of this simplified code. An API I'm maintaining has a class in it which implements an interface called Metadatable, which stores a map of metadata of its instances. This class in recent snapshots may be overridden by the program using the API via a method, and when this is done, metadata effectively becomes static. Needless to say, this breaks the entire metadata portion of the API when it happens.

A: The problem here is that someList is implicitly static (and final) because it's defined in an interface.
Section 9.3 of the JLS states:

Every field declaration in the body of an interface is implicitly public, static, and final. It is permitted to redundantly specify any or all of these modifiers for such fields.

There is only one instance of someList for the entire interface, so all implementing classes and subclasses are operating on the same list.
You can do one of two things:

*

*Change your interface into an abstract class, so that someList isn't implicitly static.

*Move the declaration of someList into SomeClass so it's not implicitly static.


text:
Q: Classlist toggle doesn't add/toggle class name for a div My goal is to display a list everytime the button is pressed kind of like a dropdown list, so I made a sort of test html,css and js files and somehow it doesn't work, the log function in my js code outputs the word 'year' on the console but the class list toggle doesn't seem to change/add the "active" on the divs' class.
Below is my js.
function btnFunction(identifier){
console.log(identifier)
var element = document.getElementById(identifier);
element.classList.toggle("active");}

Below is my html.

  <button onclick="btnFunction('year')" class="drop-btn">sample</button>

0 Year

1 Year

Below is my css.
#year{
  display: none;
}
.active{
  display: block;
}

A: The css selctor based on id is prioritized over one based on class. So the id year will always be display: none even if it has the class active. The best solution is to not use ids for css selectors because of this.
A better solution would be
.select{
  display: none;
}
.select.active{
  display: block;
}

You can read more about selector specificity here.
Ill include a snippet that shows this under here:

function btnFunction(identifier){
    console.log(identifier)
    var element = document.getElementById(identifier);
    element.classList.toggle("active");
}
.select{
  display: none;
}
.select.active{
  display: block;
}

  <button onclick="btnFunction('year')" class="drop-btn">sample</button>

0 Year

1 Year

A: you need to add !important in your css

function btnFunction(identifier) {
  console.log(identifier)
  var element = document.getElementById(identifier);
  element.classList.toggle("active");
}
#year{
  display: none;
}
.active{
  display: block !important;
}

  <button onclick="btnFunction('year')" class="drop-btn">sample</button>

0 Year

1 Year


text:
Q: seekbar interval I am integrating the Android seekbar widget as a distance bar going from 1-100 KM. Currently, the bar moves in a fixed interval 1,2,3,4,5,6,7 etc. I want the interval to be flexible and go from 1,2,5,10,15,25,50,75,100.
I have been told that this is not possible. Any suggestions on this?


text:
Q: Find $Aut(\mathbb{C}*)$ Find $Aut(\mathbb{C}*)$ , the group of automorphisms of field of complex numbers without zero.
I try studing the Laurent series, I know $a z$ and $\frac{a}{z}$ are in $Aut(\mathbb{C}*)$.
But I dont know how to continue.

A: Any  $f\in Aut(\mathbb C^*)$ will either have pole at $0$ or at $\infty.$
If it has pole only at $\infty$ then it has to be a simple pole as near $\infty$ $f$ behaves like $n$ to $1$ function. Now, $f$ being entire then $f$ has to be a linear polynomial, again $f$ takes the value $0$ at $0.$ So, $f$ takes the form $f(z)=az(a\ne 0).$
Again, if $f$ has pole at 0, then similarly it's a simple pole.
Now, $\frac{1}{f}\in Aut(\mathbb C^*)$ such that, it has pole only at $\infty.$Therefore, $\frac{1}{f(z)}=az$ i.e. $f(z)=\frac{1}{az}(a\ne 0)$


text:
Q: Cloud IAM conditions - How to limit instanceAdmin to a specific instance name only I have a project with three VMs.
I'm trying to create a condition at the project level that should limit instanceAdmin role to a single instance only, based on its name.

*

*I previously tried to to grant the policy at the instance level, but nothing happened; the granted user can see neither the instance, nor the project.

*Therefore I tried to grant the policy at the project level, with the condition that limits the role to only the required instance (based on its name)
As far as I can read on the docs, resource name has to be declared following the name attribute format (projects/project-id/zones/zone-id/instances/instance-id): if I choose start with, and I stop at the project id (eg. projects/project-id/), then the user will see all instances from the console, which is fine.
If I write the full resource name (I tried using both ID or instance name), user does not see anything.

I can't figure out how to make it happen: I'm following this guide , but it does not work on my side.
Am I missing something?
Moreover, why can't I simply apply the instanceAdmin role directly to the instance? Do I need some other privileges in order to list the instance on the console?

A: Your first try is the right one. Grant the user to be InstanceAdmin on the instance. Your problem is that the user doesn't see the compute in the project. Why? Because, he hasn't role on the compute at the project level.
For this, grant the user with the role Compute Viewer and now he will be able to see all the compute, but not to perform action, except on the instance where he is InstanceAdmin.


text:
Q: Probability of selection of three key to unlock the houses. A real estate man has eight master keys to open several new houses. Only one master key will open a given house. If 40% of these houses are usually unlocked,the probability that the real estate man can get into a specific house,if he selects three master keys at random,is?
My approach:
Let the 3 keys (A,B and C) have selected among 8 keys with each having probability 1/8.
If key A has successfully unlocked then there is no need to unlock the house by B and C .
If key A become unsuccessful but by key B if house is Unlocked then there is no need to unlock by key C.
If key A and B have unsuccessful then by key C we can unlocked the house.
P(get into house by three key)= (4/10) + (6/10)(1/8) + (6/10)(7/8)(1/8) + (6/10)(7/8)(7/8)(1/8).
Is my approach correct?


text:
Q: What requests method should i use in this scenario in python? can someone tell me which requests method should i use if i want to do this in a mysql database.
This is the execute method that i want to do. It works fine locally but i want to make it into an API so i am using the requests method to do that.
texts = message.text.split('@')

produk_id = texts[1]
id_pembeli = texts[2]

sql.execute("SELECT p.* , b.* , t.* FROM produk p, pembeli b, transaksi t WHERE p.produk_id='{produk_id}' AND b.pembeli_id='{pembeli_id}' AND t.pembeli_id='{pembeli_id}'".format(produk_id=str(produk_id), pembeli_id=str(id_pembeli)))

hasil_sql = sql.fetchall()

So the code above will first get the input that the user inputted(produk_id and pembeli_id) and then i want to select 3 table where the produk_id and pembeli_id. So which requests method should i use?


text:
Q: REDIPS get results as array from function and pass it to ajax Im using REDIPS library so i can drag and drop some elements in a table. Following the provided examples by the library, I want to get the save_content() result as an array so I can insert those values inside my DB. This is my approach, but it doesn't work. Right now I get the value in an input displayed as text
            save_content = function (tbl) {
                    var query = '',     // define query parameter
                    tbl_start,      // table loop starts from tbl_start parameter
                    tbl_end,        // table loop ends on tbl_end parameter
                    tbl_rows,       // number of table rows
                    cells,          // number of cells in the current row
                    tbl_cell,       // reference to the table cell
                    t, r, c, d;     // variables used in for loops
                    // first sort tables array to it's original order
                    tables.sort(function (a, b) {
                        return a.idx - b.idx;
                    });
                    // if input parameter is undefined, then method will return content from all tables
                    if (tbl === undefined) {
                        tbl_start = 0;
                        tbl_end = tables.length - 1;
                    }
                    // if input parameter is out of range then method will return content from first table
                    else if (tbl < 0 || tbl > tables.length - 1) {
                        tbl_start = tbl_end = 0;
                    }
                    // else return content from specified table
                    else {
                        tbl_start = tbl_end = tbl;
                    }
                    // iterate through tables
                    for (t = tbl_start; t <= tbl_end; t++) {
                        // define number of table rows
                        tbl_rows = tables[t].rows.length;
                        // iterate through each table row
                        for (r = 0; r < tbl_rows; r++) {
                            // set the number of cells in the current row
                            cells = tables[t].rows[r].cells.length;
                            // iterate through each table cell
                            for (c = 0; c < cells; c++) {
                                // set reference to the table cell
                                tbl_cell = tables[t].rows[r].cells[c];
                                // if cells isn't empty (no matter is it allowed or denied table cell)
                                if (tbl_cell.childNodes.length > 0) {
                                    // cell can contain many DIV elements
                                    for (d = 0; d < tbl_cell.childNodes.length; d++) {
                                        // childNodes should be DIVs, not \n childs
                                        if (tbl_cell.childNodes[d].tagName === 'DIV') { // and yes, it should be uppercase
                                            var value = $(tbl_cell).find("input").val();

                                            query += 'p[]=' + tbl_cell.childNodes[d].id //obj id
                                            + '_' + value + '_' + r + '_' + c + '&';
                                        }
                                    }
                                }
                            }
                        }
                    }
                    // cut last '&'
                    query = query.substring(0, query.length - 1);
                    // return prepared parameters (if tables are empty, returned value could be empty too)
                    return query;
                };

I would like to get the query value as an array so i can insert the values into the database without using $_REQUEST
  function save() {
$('#moverCita').modal('toggle');
var content = REDIPS.drag.save_content();
document.getElementById("moverCitaRow").value = content;

}
I get the value as text inside the input
update.php
if (isset($_POST['submit'])){
 if(isset($_POST['moverCitaRow'])){
  if (!empty($_POST['moverCitaRow'])) {

  $content = $_POST['moverCitaRow'];

  $content = @$_REQUEST['p'];

  if(is_array($content)) {
    foreach ($content as $c) {
      list($job_id, $job_bay_id, $row, $col) = explode('_', $c);

      try {
        update_calendar($job_id, $job_bay_id, $row, $col);

      } catch (Exception $ex) {
        $_SESSION["errorMsg"] = $ex->getMessage();
        $_SESSION["errorType"] = "danger";
      }
    }
  }

}

else {
  echo 'Llenar todos los campos
    requeridos
';
}

}
}


text:
Q: Edges of image curves on canvas get distorted on android As shown in the image, when I create a image out of curvy path(using PorterDuffXfermode) it looks distorted. The black outline is drawn with the same path but the image peaks out of the edges creating distorted look. I have listed my code below (android:hardwareAccelerated="true" has been set as well). How can I remove the distortion and align image behind the black outline.

********************* create image ******************************
// translatedFigure is the curvy figure
// sourcePicture is the image drawn as curvy figure

Canvas gfx = new Canvas(image);
gfx.drawPath(translatedFigure, fillStrokePaint);

// use new PorterDuffXfermode(android.graphics.PorterDuff.Mode.SRC_IN)

gfx.drawBitmap(sourcePicture, 100, 100, porterDuffPaint);

gfx.drawBitmap(image, 0, 0,embossPaint); // emboss

gfx.drawPath(translatedFigure, outlinePen); // draw black outline

****************************Draw image on Canvas****************************
    canvasPaint.setFlags(Paint.FILTER_BITMAP_FLAG | Paint.ANTI_ALIAS_FLAG);

    canvas.scale(mScaleFactor, mScaleFactor);
    canvas.translate(mPosX, mPosY);

    super.onDraw(canvas);
    canvas.drawBitmap(bigImageSizeOfScreen, mPosX, mPosY, canvasPaint);
    canvas.restore();
********************************************************

public void createPaint() {
        // for outline
        outlinePen = new Paint(Color.BLACK);
        outlinePen.setFlags(Paint.ANTI_ALIAS_FLAG | Paint.DITHER_FLAG);
        outlinePen.setStyle(Paint.Style.STROKE);
        outlinePen.setAntiAlias(true);
        outlinePen.setDither(true);
        outlinePen.setStrokeJoin(Paint.Join.ROUND);
        outlinePen.setStrokeCap(Paint.Cap.ROUND);
        outlinePen.setStrokeWidth(1);

        fillStrokePaint = new Paint(Color.WHITE);
        fillStrokePaint.setFlags(Paint.ANTI_ALIAS_FLAG | Paint.DITHER_FLAG);
        fillStrokePaint.setAntiAlias(true);
        fillStrokePaint.setDither(true);
        fillStrokePaint.setStrokeJoin(Paint.Join.ROUND);
        fillStrokePaint.setStrokeCap(Paint.Cap.ROUND);
        fillStrokePaint.setStyle(Paint.Style.FILL);

        porterDuffPaint = new Paint();
        porterDuffPaint.setXfermode(new PorterDuffXfermode(
                android.graphics.PorterDuff.Mode.SRC_IN));

        embossPaint = new Paint(Color.RED);
        embossPaint.setFlags(Paint.FILTER_BITMAP_FLAG | Paint.ANTI_ALIAS_FLAG
                | Paint.DITHER_FLAG);
        embossPaint.setStyle(Paint.Style.FILL_AND_STROKE);
        embossPaint.setStrokeJoin(Paint.Join.ROUND);
        embossPaint.setStrokeCap(Paint.Cap.ROUND);

        EmbossMaskFilter mEmboss = new EmbossMaskFilter(
                new float[]{1, 1, 1}, 0.4f, 6, 3.5f);
        embossPaint.setMaskFilter(mEmboss);
    }


text:
Q: Flutterwave Android payment integration - cannot process payment - error unable to retrieve transaction fee I'm using Rave for the first time, it looked so flexible and easier to integrate, but along the line. I got stuck with testing, I'm using only card and bank payments methods.

*

*when I choose the card to and enter some test cards from the test card link https://developer.flutterwave.com/reference#test-cards-1
I get 2 errors, => "unable to retrieve transaction fees" but in my logcat I see => " only test cards ree allowed," of which were using the test cards. And am also on staging mode which I assume is correct while testing with test keys.

*When I use the bank tab I get some error in JSON toasted, but display later => "parents_limit not defined". Not just that I give this errors, I still found transactions of the bank payment types recorded on my dashboard. This confuses me more since I didn't get the payment success message so I can verify and give value to the customer.
I have integrated everything as per guideline in Rave docs, which calls my make payment. from https://github.com/Flutterwave/rave-android
variable for implementation
 //online payment
    String[] fullname;
    String email = "";
    String fName = "";
    String lName = "";
    String narration = "Payment for Riidit App activation";
    String txRef;
    String country = "NG";
    String currency = "NGN";
    private String mUsername, userID, mEmail;

the payment method
private void makePayment(int amount) {
        txRef = email + " " + UUID.randomUUID().toString();

        try {
            fullname = mUsername.split(" ");
            fName = fullname[0];
            lName = fullname[1];

        } catch (NullPointerException ex) {
            ex.printStackTrace();
        }

        /*
        Create instance of RavePayManager
         */
        new RavePayManager(this).setAmount(amount)
                .setCountry(country)
                .setCurrency(currency)
                .setEmail(email)
                .setfName(fName)
                .setlName(lName)
                .setNarration(narration)
                .setPublicKey(RiiditUtilTool.getPublicKey())
                .setEncryptionKey(RiiditUtilTool.getEncryptionKey())
                .setTxRef(txRef)
                .acceptAccountPayments(true)
                .acceptCardPayments(true)
                .acceptMpesaPayments(false)
                .acceptGHMobileMoneyPayments(false)
                .onStagingEnv(false)
                .allowSaveCardFeature(true)
                .withTheme(R.style.DefaultTheme)
                .initialize();
    }

//called from below
 private void payOnline()
{
    makePayment(amount);
}

public void onActivateOnlineClick(View v) {
        payOnline();
    }

// expecting result of payment here either fail or success
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == RaveConstants.RAVE_REQUEST_CODE && data != null) {
            String message = data.getStringExtra("response");
            if (resultCode == RavePayActivity.RESULT_SUCCESS) {
                Toast.makeText(this, "SUCCESS " + message, Toast.LENGTH_LONG).show();

                // get a PIN and SERIAL no when payment succeeds
                getGetPinAndSerialForPaidUser();

            } else if (resultCode == RavePayActivity.RESULT_ERROR) {
                Toast.makeText(this, "ERROR " + message, Toast.LENGTH_LONG).show();
            } else if (resultCode == RavePayActivity.RESULT_CANCELLED) {
                Toast.makeText(this, "Payment CANCELLED " + message, Toast.LENGTH_LONG).show();
            }
        }
    }

I want when this event is triggered, it will make the payment to using the value set in the amount and return status in the onActivityResult above where I can check and give value to the user

A: First of all make sure you are using the api keys which are for testing and if you are on staging mode(testing) then set this to true .onStagingEnv(true) and test after that.


text:
Q: Change css depending on span value I have a span and a div. I need to make it where if the value of span is 123, change the css of the div to display:none;
I'm trying to do it with jQuery, but I cannot see where I am going wrong.
Here is my code:
(by the way, I'm using jQuery no conflict)

123

Foo

Thanks for your help!

A: You can use each() to check each span and next() to hide specialdiv after span with 123

$('span').each(function() {
  if ($.trim($(this).text()) == '123') {
    $(this).next('.specialdiv').css('display', 'none');
  }
});

 123

Foo

lorem

Lorem


text:
Q: WCF UDP discovery only works for BasicHttpBinding not for NetTcpBinding I have a WCF service that has announced two service endpoints. One is for net.tcp and one is for http.

net.tcp://localhost:11110/MyService
http://localhost:11111/MyService

        // Make service discoverable
        var discoveryBehavior = new ServiceDiscoveryBehavior();
        var announceEndpointAddress = ConfigurationManager.AppSettings["AnnouncementEndpoint"];

        var netTcpBinding = new NetTcpBinding(SecurityMode.None)
        {
            ReceiveTimeout = TimeSpan.MaxValue,
            SendTimeout =  TimeSpan.MaxValue,
            OpenTimeout =TimeSpan.MaxValue,
            CloseTimeout =  TimeSpan.MaxValue
        };

        discoveryBehavior.AnnouncementEndpoints.Add(
            new AnnouncementEndpoint(netTcpBinding,
            new EndpointAddress(announceEndpointAddress)
        ));
        _serviceHost.Description.Behaviors.Add(discoveryBehavior);
        _serviceHost.AddServiceEndpoint(new UdpDiscoveryEndpoint());

On the client side, I am using WCF Discovery.
class Program
{
    static void Main(string[] args)
    {
        var optionalBindings = new Binding[]
        {
            new NetTcpBinding(),
            new BasicHttpBinding(),
            new NetNamedPipeBinding()
        };

        var executed = false;

        foreach (var binding in optionalBindings)
        {
            var contract = ContractDescription.GetContract(typeof(IMyService));
            var endpoint = new DynamicEndpoint(contract, binding);

            var factory = new ChannelFactory<IMyService>(endpoint);
            var proxy = factory.CreateChannel();

            try
            {
                var result = proxy.GetData(123456);

                ((ICommunicationObject) proxy).Close();

                executed = true;
                break;
            }
            catch (EndpointNotFoundException)
            {
                // Ignored
            }
        }
    }
}

What confuses me is that it only works with BasicHttpBinding and never works with NetTcpBinding. So if BasicHttpBinding from optionalBindings list, i am not able to call the service although net.tcp endpoint is there.
Can anyone explain the reason for it?


text:
Q: Complex count row etl requirement I have a requirement related as below
1-If there is employee record then count the number of rows
  a-if there are four rows then follow the layout 1,

         and populate the column1 and column 2 with values in report and ltrimrtrim

  b- if there are three rows, then follow the layout 2,

         and hardcode the column 1 and column 2 with NULL

Otherwise, look for the employee record.
Couldn't get the logic, I used the router with as if column 1 and two null the send to layout two else 1. But the requirement is different.
router transformation, if null, layout one else 2

A: Step 1 - Use SRT>AGG>JNR to calculate count. create new column as count_all and set to COUNT(*). Please group by proper key columns.
Step 2 - Use RTR next to split data based on your condition.

*

*group 1- count_all =4 then follow the layout 1 and...

*group 2- count_all =3 then follow the layout 2 and...

*group 3 - if count <3 then do  employee record.


text:
Q: ACF Pro with WooCommerce Recommendations my website works with WooCommerce/Dokan and uses ACF Pro for adding additional fields in the product creation process to add more categorization.
I now want to add some WooCommerce Recommendations depending on the choices made in the ACF fields.
For example:
Available choices for ACF custom fields: "Category 1" "Category 2"
Now I want to create a recommendation that shows products with "Category 2" on every product page with "Category 1".
Unfortunately I cannot get the ACF fields to be a dependencie on the recommendations in WooCommerce.
Are there any ideas/solutions?
Thank you!
Christian


text:
Q: Highcharts displaying improperly labeled data points I'm having an issue with highcharts displaying some of my datapoints with a duplicate label, then skipping subsequent labels, and I can't figure out how to fix it.
I gather from reading various posts that this is an issue with the PointInterval option; I'd like to set its value to 1 month, but since months a different lengths, this is not simple.
I am not sure of what a proper solution is though. Here is my code:
http://jsfiddle.net/KJ3tk/
The graph is displaying January and March twice, and skipping February.
The solution suggested in this thread ( http://highslide.com/forum/viewtopic.php?f=9&t=17269 ) seems to be what I need, but I can't figure out how to implement it in the javascript that I currently have. This is the code that they suggest will fix the problem:
var data = [3,2,5,3,5,6,2,3,1];
var month = 4; // the first month
data = $.map(data, function(value) {
    return {
        x: Date.UTC(2000, month++, 1),
        y: value
    };
});

I'd really appreciate any assistance! Thanks.

A:      var mydata =  [
 7418,7386,7552,8903,8439,9356,9861,9411,10257,10169,9622,9940,
                                    /*2009*/
  10551,10326,12817,11739,11694,12209,12132,11842,11908,11909,11884,12450,
                                    /*2010*/
15545,14495,16195,15064,13788,14452,14908,15858,16213,15994,15213,15651,
                                    /*2011*/
17233,15515,19629,18960,19834,19997,19358,21042,20189,20660,20034,19815,
                                    /*2012*/
22611,21435,23327,22876,22986,23692,21581,21832,22337
            ];
   var month = 0; // the first month
  mydata = $.map(mydata, function(value) {
    return {
      x: Date.UTC(2008, month++, 1),
    y: value
}; });

Live Demo


text:
Q: Read non-blocking from multiple fifos in parallel I sometimes sit with a bunch of output fifos from programs that run in parallel. I would like to merge these fifos. The naïve solution is:
cat fifo* > output

But this requires the first fifo to complete before reading the first byte from the second fifo, and this will block the parallel running programs.
Another way is:
(cat fifo1 & cat fifo2 & ... ) > output

But this may mix the output thus getting half-lines in output.
When reading from multiple fifos, there must be some rules for merging the files. Typically doing it on a line by line basis is enough for me, so I am looking for something that does:
parallel_non_blocking_cat fifo* > output

which will read from all fifos in parallel and merge the output on with a full line at a time.
I can see it is not hard to write that program. All you need to do is:

*

*open all fifos

*do a blocking select on all of them

*read nonblocking from the fifo which has data into the buffer for that fifo

*if the buffer contains a full line (or record) then print out the line

*if all fifos are closed/eof: exit

*goto 2

So my question is not: can it be done?
My question is: Is it done already and can I just install a tool that does this?

A: This solution will only work if the number of fifos are fewer than the number of jobs that GNU parallel can run in parallel (which is limited by file handles and number of processes):
parallel -j0 --line-buffer cat ::: fifo*

It seems to be able to move up to 500 MB/s:
window1$ mkfifo {1..100}
window1$ parallel -j0 --line-buffer cat ::: {1..100} | pv >/dev/null

window2$ parallel -j0 'cat bigfile > ' ::: *

And it does not mix half-lines:
window1$ mkfifo {1..100}
window1$ parallel -j0 --line-buffer cat ::: {1..100} &

window2$ parallel -j0 'traceroute {}.1.1.1 > {}' ::: *

It reads jobs in parallel (it does not read one job completely before going to the next):
window1$ mkfifo {1..100}
window1$ parallel -j0 --line-buffer cat ::: * > >(tr -s ABCabc)

window2$ long_lines_with_pause() {
            perl -e 'print STDOUT "a"x30000_000," "'
    perl -e 'print STDOUT "b"x30000_000," "'
    perl -e 'print STDOUT "c"x30000_000," "'
    echo "$1"
    sleep 2
    perl -e 'print STDOUT "A"x30000_000," "'
    perl -e 'print STDOUT "B"x30000_000," "'
    perl -e 'print STDOUT "C"x30000_000," "'
    echo "$1"
}
window2$ export -f long_lines_with_pause
window2$ parallel -j0 'long_lines_with_pause {} > {}' ::: *

Here a lot of 'a b c' (first half of a job) will be printed before 'A B C' (second half of the job).

A: So,
tail -q -n+1 -f --pid=stop-tail-when-this-is-gone fifo1 fifo2 fifo3

almost works (as alluded to in initial comments about this earlier version of my answer, though you may need a "for f in fifo*; cat < /dev/null > $f & done" beforehand to ensure all FIFOs are open for write because coreutils tail opens them O_RDONLY without O_NONBLOCK).
Unfortunately, there is a bug in that tail is careful about line/record endings only with inputs from pipes on stdin but not with input from named pipes/FIFOs in arguments.  Someday someone may fix coreutils tail.
In the interim, to get a true multi-consumer/single producer queue honoring the line-endings, you can use a simple 100-ish-line C program I call tailpipes.c:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>    //TODO: Find&document build environments lacking memrchr
#include <unistd.h>
#include <fcntl.h>
#include <time.h>
#include <errno.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/stat.h>
#define errstr strerror(errno)

char const * const Use = "%s: %s\n\nUsage:\n\n"
"  %s [-p PID] [-o OPEN_MODE(RW)] [-d DLM(\\n)] [-s SEC(.01)] PATH1 PATH2..\n\n"
"Read delimited records (lines by default) from all input paths, writing only\n"
"complete records to stdout and changing to a stop-at-EOF mode upon receiving\n"
"SIGHUP (unlike \"tail -fqn+1\" which just dies) OR when we first notice that\n"
"PID does not exist (if PID is given).  Since by default fifos are opened RW,\n"
"signal/PID termination is needed to not loop forever, but said FIFOs may be\n"
"closed & reopened by other processes as often as is convenient. For one-shot\n"
"writing style, ending input reads at the first EOF, use \"-oRO\".  Also, DLM\n"
"adjusts the record delimiter byte from the default newline, and SEC adjusts\n"
"max select sleep time.  Any improperly terminated final records are sent to\n"
"stderr at the end of execution (with a label and bracketing).\n";

int writer_done;
void sig(int signum) { writer_done = 1; }

int main(int N, char *V[]) {
    signed char     ch;
    char           *buf[N-1], delim = '\n', *V0 = V[0], *eol;
    int             len[N-1], fds[N-1], nBf[N-1], i, fdMx = 0, nS = 0, nF = 0,
                    oFlags = O_RDWR;
    pid_t           pid = 0;
    ssize_t         nR, nW;
    struct timespec tmOut = { 0, 10000000 }; //10 ms select time out
    fd_set          fdRdMaster, fdRd;
    //If we get signaled before here, this program dies and data may be lost.
    //If possible use -p PID option w/pre-extant PID of appropriate lifetime.
    signal(SIGHUP, sig);                    //Install sig() for SIGHUP
    memset((void *)fds, 0, sizeof fds);
    memset((void *)len, 0, sizeof len);
    FD_ZERO(&fdRdMaster);
    fdRd = fdRdMaster;
    while ((ch = getopt(N, V, "d:p:s:o:")) != -1)
        switch (ch) {                       //For \0 do '' as a sep CLI arg
            double tO;
            case 'd': delim  = optarg ? *optarg : '\n';   break;
            case 'p': pid    = optarg ? atoi(optarg) : 0; break;
            case 's': tO = optarg ? atof(optarg) : .01;
                      tmOut.tv_sec = (long)tO;
                      tmOut.tv_nsec = 1e9 * (tO - tmOut.tv_sec);
                      break;
            case 'o': oFlags = (optarg && strcasecmp(optarg, "ro") == 0) ?
                                 O_RDONLY | O_NONBLOCK : O_RDWR;
                      break;
            default: return fprintf(stderr, Use, V0, "bad option", V0), 1;
        }
    V += optind; N -= optind;               //Shift off option args
    if (N < 1)
        return fprintf(stderr, Use, V0, "too few arguments", V0), 2;
    setvbuf(stdout, NULL, _IONBF, 65536);   //Full pipe on Linux
    for (i = 0; i < N; i++)                 //Check for any available V[]
        if ((fds[i] = open(V[i], oFlags)) != -1) {
            struct stat st;
            fstat(fds[i], &st);
            if (!S_ISFIFO(st.st_mode))
                return fprintf(stderr,"%s: %s not a named pipe\n", V0, V[i]), 3;
            nF++;
            FD_SET(fds[i], &fdRdMaster);    //Add fd to master copy for pselect
            buf[i] = malloc(nBf[i] = 4096);
            if (fds[i] > fdMx)
                fdMx = fds[i];
        } else if (errno == EINTR) {        //We may get signaled to finish up..
            i--; continue;                  //..before we even this far.
        } else
            return fprintf(stderr, "%s: open(%s): %s\n", V0, V[i], errstr), 3;
    fdMx++;
    fdRd = fdRdMaster;
    while (nF && (nS = pselect(fdMx, &fdRd, NULL, NULL, &tmOut, NULL)) != -99) {
        if (pid && kill(pid, 0) != 0 && errno != EPERM) //Given pid didn't exist
            writer_done = 1;
        if (nS == 0 && writer_done)                     //No input & no writers
            break;
        else if (nS == -1) {                            //Some select error:
            if (errno != EINTR && errno == EAGAIN)      //..fatal or retry
                return fprintf(stderr, "%s: select: %s\n", V0, errstr), 4;
            continue;
        }
        for (i = 0; nS > 0 && i < N; i++) {             //For all fds..
            if (fds[i] < 0 || !FD_ISSET(fds[i], &fdRd)) //with readable data
                continue;
            if ((nR = read(fds[i], buf[i]+len[i], nBf[i] - len[i])) < 0) {
                if (errno != EAGAIN && errno != EINTR)
                    fprintf(stderr, "%s: read: %s\n", V0, errstr);
                continue;
            } else if (oFlags == (O_RDONLY | O_NONBLOCK) && nR == 0) {
                FD_CLR(fds[i], &fdRdMaster);
                nF--;
                free(buf[i]);
            }
            len[i] += nR;                               //Update Re: read data
            if ((eol = memrchr(buf[i], delim, len[i]))) {
                nW = eol - buf[i] + 1;                  //Only to last delim
                if (fwrite(buf[i], nW, 1, stdout) == 1) {
                    memmove(buf[i], buf[i] + nW, len[i] - nW);
                    len[i] -= nW;                       //Residual buffer shift
                } else
                    return fprintf(stderr, "%s: %d bytes->stdout failed: %s\n",
                                   V0, len[i], errstr), 5;
            } else if (len[i] == nBf[i]) {              //NoDelim&FullBuf=>GROW
                void *tmp;
                if (nBf[i] >= 1 << 30)
                    return fprintf(stderr, "%s: record > 1 GiB\n", V0), 6;
                nBf[i] *= 2;
                if (!(tmp = realloc(buf[i], nBf[i])))
                    return fprintf(stderr,"%s: out of memory\n", V0), 7;
                buf[i] = tmp;
            }
        }
        fdRd = fdRdMaster;
    }
    for (i = 0; i < N; i++)                     //Ensure any residual data is..
        if (len[i] > 0) {                       //..labeled,bracketed,=>stderr.
            fprintf(stderr, "%s: %s: final unterminated record: {", V0, V[i]);
            fwrite(buf[i], len[i], 1, stderr);
            fputs("}\n", stderr);
        }
    return 0;
}

Install is cut & paste & cc -Owhatever tailpipes.c -o somewhere-in-$PATH/tailpipes.  Tested on Linux & FreeBSD.  I get about 2500e6 bytes/sec output, but memory may be faster than the 500e6 bytes/sec box.
The algorithm is roughly as suggested, but more general.  O_NONBLOCK is only needed with O_RDONLY and with some options for ease of use, like opening FIFOs O_RDWR by default so writers can close and reopen many times and use -p PID tracking for a race-free protocol. You can pass -oRO to use EOF if you want.  tailpipes also handles incomplete lines at program termination, sending them labeled and bracketed to stderr in case there is easy post-processing that can be done to make the records whole or if logs of them would be useful for debugging.
Example usage. GNU xargs can be a single-consumer, multi-producer/fan-out part of a map-reduce-ish parallel pipeline with tailpipes operating as the record-boundary-honoring fan-in part, all with no disk space used for temporary files:
export MYTEMP=$(mktemp -d /tmp/MYPROG.XXXXX)
FIFOs=`n=0; while [ $n -lt 8 ]; do echo $MYTEMP/$n; n=$((n+1)); done`
mkfifo $FIFOs
sleep 2147483647 & p=$!       #Cannot know xargs pid is good for long
( find . -print0 | xargs -0 -P8 --process-slot-var=MYSLOT MYPROGRAM
  kill $p ) &                 #Inform tailpipes writers are done
tailpipes -p$p $FIFOs | CONSUMING-PIPELINE
rm -rf $MYTEMP
wait                          #Wait for xargs subshell to finish

In the above, it is important that A) n goes from 0 to the appropriate upper bound because that is the scheme xargs uses for MYSLOT, and B) MYPROGRAM direct its outputs to a newly assigned $MYSLOT-keyed file like $MYTEMP/$MYSLOT, e.g. exec > $MYTEMP/$MYSLOT if MYPROGRAM is a shell script.  The shell/program wrapper could be eliminated in many cases if xargs took a hypothetical --process-slot-out to setup its kids stdouts.

A: A more elegant answer that does not buffer a useless copy on disk:
#!/usr/bin/perl

use threads;
use threads::shared;
use Thread::Queue;

my $done :shared;

my $DataQueue = Thread::Queue->new();

my @producers;
for (@ARGV) {
    push @producers, threads->create('producer', $_);
}

while($done <= $#ARGV) {
    # This blocks until $DataQueue->pending > 0
    print $DataQueue->dequeue();
}

for (@producers) {
    $_->join();
}

sub producer {
    open(my $fh, "<", shift) || die;
    while(<$fh>) {
        $DataQueue->enqueue($_);
    }
    # Closing $fh blocks
    # close $fh;
    $done++;
    # Guard against race condition
    $DataQueue->enqueue("");
}


text:
Q: How can this approximate donor ionization concentration be derived? I'm currently working about doner ionization.
I've got carrier density $$ n_0 e^\frac{{\mu}-E_c}{k_bT}$$ and product of donor density and fermi distribution, $$ \frac{N_d}{1+2e^\frac{{\mu}-E_d}{k_bT}} $$
And with those, somehow the textbook says the ionization density of donor is approximately given by $$ n \approx (n_0 N_d)^{1/2}e^\frac{-E_d}{k_bT} $$
i've done some works to derive it, like multiplying forms i got and taking sqrt, but it seems to be "approximate" somewhere i am missing.
How can i get there?
edit: $$n_0 = 2\biggr(\frac{m_ek_BT}{2\pi \bar h^2}\biggr)^{3/2}$$ , factor originated from density of states, etc.

A: Generally this is covered early on in most semiconductor physics textbooks. For example, in Sze's Physics of Semiconductor Physics this is in chapter 1.
In the intrinsic case,
There, one has the effective density of states in the conduction band is
$ N_{C} = 2({2\pi m_{de} k T \over h^{2}} )^{3 \over 2}M_{C}$
where $M_{C}$ is the number of minima in the conduction band and $m_{de}$ is the effective mass for electrons in the conduction band. (For acceptors one flips to holes in the valence band).
For reasonable temperatures (i.e. the Fermi level is several $kT$ below the conduction band edge, the overlap integral for the intrinsic case (that is the intrinsic electron concentration) becomes:
$n = N_{C} \exp (-{{E_{C} - E_{F}} \over kT})$
One then proceeds to consider the impact of donors on the carrier concentrations. In that case one can derive (still chapter 1 in Sze) that the number of ionized donors is:
$N_{D}^{+} = N_{D}{1 \over {1 + g \exp ({{E_{F}-E_{D} \over kT}})}}    $
where g is the ground state degeneracy normally taken as 2.
Then, using net neutrality one gets a pretty horrible equation relating the elecyron density in the conduction band with expressions for the ionized donors and the density of holes:
$n = N_{C} \exp (-{{E_{C} - E_{F}} \over kT}) = N_{D} {1 \over {1 + g \exp ({{E_{F}-E_{D} \over kT}})}} + N_{V} \exp ({{E_{V} - E_{F}} \over kT})   $
At temperatures where the Fermi energy is close to the donor level, one can approximate this as:
$n = ({N_{D} - N_{A} \over 2 N_{A}}) N_{C} \exp(-E_{d}/kT)$ where $E_{d} = E_{C}-E_{D}$
In the appropriate limits,
$n = {1 \over \sqrt 2}(N_{D}N_{C})^{1/2}\exp(-E_{d}/2kT) $
Messy, but laid out well in Sze.


text:
Q: Interface compile options for imported library in older CMake versions I'm trying to create an imported target in CMake and specify a compiler option to use with my target from any downstream project. It looks similar to the snippet below (-O3 is just an example, the use case is a bit more sophisticated):
add_library(Foo::Foo UNKNOWN IMPORTED)
set_target_properties(Foo::Foo
    INTERFACE_COMPILE_OPTIONS "-O3")

The issue is that this isn't supported by CMake versions older than 2.8.12.
Is there a way to implement this mechanism in the older versions or are there any reasonable alternatives?


text:
Q: Hibernate noob: criteria to fetch not mapped relationship I have two classes in a many-to-many relationship, but only one of them have a list to the other.
@Entity
public class Product{
  @ManyToMany
  List<Category> categories;
  //...
}

@Entity
public class Category{
  //...
}

I want to find all Products related to a Category using Criteria, but the following doesn't work.
import static java.util.Collections.singletonList;

List<Product> getProductsByCategory(Category category){
    List<Product> results = getCurrentSession()
                            .createCriteria(Product.class)
                            .add(Restrictions.in("categories", singletonList(category)))
                            .list();
    if (results == null || results.size() <= 0)
        throw new EntityNotFoundException(category + "is empty");
    return results;
}

Of course that would be really simple if Product was mapped to Category, but surely Hibernate let's you do such a query without it.
EDIT:
It returns an Oracle error
Caused by: java.sql.SQLException: Missing IN or OUT parameter at index:: 1

Thanks for any help!

A: Criteria c = session.createCriteria(Product.class, "product");
c.createAlias("product.categories", "category");
c.add(Restrictions.eq("category.id", category.getId());
List<Product> results = c.list();

Note: the result list will NEVER be null. And its size will NEVER be < 0. An empty list is the right thing to return if the category doesn't have any product. I wouldn't throw an exception in this case.

A: List<Product> results = getCurrentSession().createCriteria(Product.class)
                        .createCriteria("categories")
                            .add(Restrictions.in("id", uniqueIds(categories)))
                        .list();


text:
Q: workspace switching via ctrl + alt + arrow not working after upgrade to 13.04, how to fix this? So, my update to 13.04 didn't go very well. Due to the lack of a decent driver (Yes, i'm unlucky to have a legacy driver which doesn't play nice with the new Xorg.), I had to mess around with stuff to first troubleshoot and afterwards "fix" my system.
I've finally got unity back, but now CtrlAltarrow and CtrlAltShiftarrow don't work anymore. They are bound in "keyboard" > "shortcuts", but nothing happens when I try it. A strange thing is that other keyboard shortcuts, like ctrlaltt to show terminal are still working.
I noticed that CtrlAltarrow doesn't show in the list with "unity shortcuts" (the list that shows when you hold the super key).
Does anyone know how to re-enable this way of workspace switching?
I enabled workspaces in the appearance menu. It doesn't have any effect though. Switching via the workspace-switcher in the unity dash works fine though.
CCSM is installed, but I can't seem to find a way to add keyboard bindings there.

System: ubuntu 13.04 64bit

A: This may help.
On my system, the same thing was happening. I found, by checking the Keyboard>Shortcuts>Navigation that it's not Ctrl + Alt + Arrow, you haveto press Ctrl + Alt + shift+arrow perhaps the C+S+A is being used bu another programme so conflicts.

A: On Ubuntu 13.04 workspace are disabled by default. To enable it open 'Appearance' from system settings > click to the 'Behavior' tab > check 'Enable workspace'.
And also check the keyboard shortcuts in system setting>keyboard.

A: I had this same issue.  I enabled workspace from Appearance → Behavior, and also tried using Ubuntu Tweak, but no go on the keyboard shortcuts, even though all the defaults were there.
I then opened CCSM to make sure that the Desktop Wall was enabled.  In my case it wasn't, and as soon as I enabled it, my keyboard shortcuts started working again.


text:
Q: Complete Orbits in Compact Dynamical Systems I am going through a book on topological dynamics, and in establishing their definitions they mention the following 'fact,' leaving it as an exercise:
If $X$ is a compact Hausdorff space, $x_0 \in X$ and $f : X \rightarrow X$ is a continuous function, then the following two conditions are equivalent:
1) $x_0 \in \cap f^n(X)$, and
2) there is an infinite sequence $x_{-n}$ with $f(x_{-n }) = x_{-n+1}$
In other words, $x_0$ has a complete 'reverse orbit' iff it is contained in the image of every iterate of $f$.  I am not convinced that (1) implies (2) even if $X$ is compact metric.  To see this, attach a straight line segment $A_n$ to the origin in the plane, such that the length of $A_n$ is $\frac{1}{n}$ with radian angle $\frac{\pi}{n}$.  Then their union is compact metric.
Now, let $B_n = \lbrace b_1^n, b_2^n, \dots, b_n^n \rbrace \subset A_n$ be a subset consisting of $n$ points, each containing the origin.  Let $X = \cup B_n$.  It is compact metric, and we can define a continuous function on each $B_n$ separately via $f(b_k^n) = b_{k+1}^n$, where we assume $b_n^n = b_{n+1}^n = \cdots = 0$, i.e. the origin is a sink for the action on each $B_n$.  Then isn't it true that $0$ satisfies (1) but not (2)?
To avoid the constant sequence being a solution, we can assume that there is a finite tail after $0$ which then becomes a periodic orbit (or anything else with compact phase space).  So these points will pass through $0$ before dumping into a finite periodic orbit.
Thanks for checking!

A: The claim of equivalence is true and employs the compactness of $X$ as a critical assumption.
Per assumption of 1), $x_0\in \bigcap_{n=1}^\infty f^n(X)$, which means that pre-images $\tilde x_{-n}$ of any depth $n$ exist, $x_0=f^n(\tilde x_{-n})$. By compactness, the sequence $f^{n-1}(\tilde x_{-n})$ has an accumulation point $x_{-1}$, which means that there is a sub-sequence $\tilde x_{-n_k}$ with $\lim_{k\to\infty} f^{n_k-1}(\tilde x_{-n_k})=x_{-1}$. By continuity $$f(x_{-1})=f\left(\lim_{k\to\infty} f^{n_k-1}(\tilde x_{-n_k})\right)=\lim_{k\to\infty} f^{n_k}(\tilde x_{-n_k})=x_0.$$

It remains to show that also $x_{-1}\in \bigcap_{n=1}^\infty f^n(X)$. Fix some $N\in \Bbb N$, pick any accumulation point $\tilde x_{-1,N}$  of the sequence $$\left(f^{n_k-1-N}(\tilde x_{-n_k})\right)_{k\in \Bbb N,\, n_k>N+1},$$ which exist because of the compactness of $X$. We get that $x_{-1}$ is the image of  $\tilde x_{-1,N}$ under $f^N$, again by continuity. Thus, $x_{-1}\in f^N(X)$, for any $N\in \Bbb N$.
Now apply the same process on $x_{-1}$ to obtain one $x_{-2}$ etc. to obtain a sequence of points with $f(x_{-k-1})=x_{-k}$ as claimed in 2).


text:
Q: Увеличение фото при нажатии Вот сайт: http://www.richrol.com внизу при нажатии на фото оно увеличивается. Как сделать также но не так убого что б было?) а то там тормозит и какие то лишние символы отображаются. Только, пожалуйста, с оглядкой на то, что фото будет много. Благодарю!
A: как обычно.
А уж будет ли тормозить, и будут ли лишние символы — зависит от вас.
A: Если нужен чистый JavaScript, то лучше подойдет библиотека highslide.js. Как ее внедрить можно посмотреть тут


text:
Q: Munin plugin in perl doesn't fetch correct data I'm trying to use a Munin plugin for software raid. Here's the plugin's code: https://github.com/munin-monitoring/contrib/blob/master/plugins/disk/raid
Currently my raid is rebuilding, here's the current output:
# cat /proc/mdstat
Personalities : [raid0] [raid1] [raid6] [raid5] [raid4] [raid10]
md2 : active raid1 sda3[0] sdb3[1]
      2925544767 blocks super 1.2 [2/2] [UU]
      [==>..................]  resync = 14.4% (422554560/2925544767) finish=5246.6min speed=7950K/sec

md1 : active raid1 sda2[0] sdb2[1]
      524276 blocks super 1.2 [2/2] [UU]
        resync=DELAYED

md0 : active raid1 sda1[0] sdb1[1]
      4193268 blocks super 1.2 [2/2] [UU]
        resync=DELAYED

unused devices: <none>

But when I run the plugin I get the following output (stating that all disks are synced):
# munin-run raid
md2.value 100
md2_rebuild.value 100
md1.value 100
md1_rebuild.value 100
md0.value 100
md0_rebuild.value 100

In the following lines I understand (I'm no programmer) that during the time the code runs, $pct is >= 100, and so $rpct gets set to 100 (which is my output for all raid arrays).
So which values do $nact and $nmem represent in my cat /proc/mdstat output? This would help me find out why $pct is >= 100.
my $pct = 100 * $nact / $nmem;
        my $rpct = 100;
        if ( $pct < 100 ) {
        my @output = `/sbin/mdadm -D /dev/$dev | grep Rebuild`;
        if( $output[0] =~ /([0-9]+)% complete/ ) {
            $rpct = $1;
        } else {
            $rpct = 0;
        }

I think this regexp holds the answer, but as I said, I'm no programmer :P
while ($text =~ /(md\d+)\s+:\s+active\s+(\(auto-read-only\)\s+|)(\w+)\s+(.*)\n.*\[(\d+)\/(\d+)]\s+\[(\w+)]/ ) {
    my($dev,$dummy,$type,$members,$nmem,$nact,$status) = ($1,$2,$3,$4,$5,$6,$7);

Thanks in advance :-)

A: change this:
if ( $pct < 100 ) {

to this:
if ( $pct <= 100 ) {

and make sure you're running the plugin as root


text:
Q: Does Git Rebasing Alter the Commit Tree I was seeing this very reliable tutorial which said rebasing would cause new commits with a different SHA keys ONLY because the parent to which it points to is now different and everything else is identical.
However if this is true and nothing else changes, then if we traverse the latest rebased commit by drilling down into its root-tree, its subtrees and blobs wouldn't it be identical to original rebased tree?
By definition shouldn't the latest rebased commit tree contain an union of content from both master and rebased branches? In which case the commit should point to a new root-tree structure having new subtrees, blobs and possibly new node additions, be it subtrees or more blobs.

A: Without something like a link to the tutorial itself, it's impossible to say whether it's wrong, or you're just holding it wrong. :-)  However, rebase works internally as if by doing a series of git cherry-pick operations.
In fact, interactive rebase literally runs git cherry-pick.  Non-interactive rebase uses git format-patch and git am instead, when it can.
Both rebases will, by default, attempt not to copy commits that do not need to be copied.  That is, if the onto target of some to-be-copied commit (as computed internally after applying previous commits and/or from the --onto argument if any) is the same parent the commit already has, the underlying rebase can simply fast-forward the in-progress new anonymous branch over that commit, rather than copying it.  In this case, the SHA1s all remain undisturbed.  You can explicitly disable this behavior with -f, --force-rebase, or --no-ff.  As long as the time stamp on the new copy differs, it will then acquire a different SHA1 hash (even if/though everything else is the same).
Internally, the onto target is simply HEAD, since rebase works internally by using detached HEAD mode.  As each old commit gets copied to the new one, Git simply needs to make a new commit as usual (or for that one special case, step HEAD forward using git reset).
In general, though, as long as something has changed—which is definitely true if the parent ID has changed (i.e., the onto target differs)—Git must construct a new commit.  It does by, in effect, applying the original commit as a patch atop the current commit.
Note that this cannot work for merge commits, which cannot be represented as a single patch.1  As a consequence, git rebase normally strips out merge commits entirely.  The interactive rebase script has code to "preserve" merges, but it really cannot preserve a merge (except for the special fast-forward case): instead, it must re-perform the merge, with all the consequences of doing so.

1A merge commit could be represented by at least two patches, one against the first parent and one against every other parent, but not by just one.  However, such a representation would be useless for our purposes: --preserve-merges is intended to transplant the merge into a new commit chain, with a different starting code-base, so we can expect the diff against the second (and any additional) parents to change.

A: Git creates new SHA IDs for the commits, as well as for all of the metadata in the trees, like the blobs. You're correct that the content is identical, but all of the IDS have changed entirely.

A: The point is the git is implemented like a linked list! therefore when you lost a link there is no way to track it back.
The easiest way to integrate the branches, is the merge command. It performs a three-way merge between the two latest branch snapshots creating a new snapshot (and commit).

However, in rebase you can take the patch of the change and reapply it on top of your master branch.

You can read more here:

https://git-scm.com/book/en/v2/Git-Branching-Rebasing

I hope it helps ;)


text:
Q: get specific file from sorted files meybe this is too simple but im new on unix.
i have a directory like  /home and in this directory i have 5 files like ;
/home/file1.csv
/home/file2.csv
/home/file3.csv
/home/file4.csv
/home/file5.csv
i want to display a file like , they must be ordered by date and i can display for example 3.file from that order ..

A: I'm not very sure if you want it to be ordered newest first or oldest first.
ls -t | head -3

will print the newest 3 files, and
ls -rt | head -3

will print the oldest 3 files.
And if you want to sort the result in access time (the commands above sort them in modification time), please use the following commands respectively.
ls -u | head -3
ls -ru | head -3

A: The above mentioned method by aifreedom is better than what I had earlier (shifted to the bottom)
@denso, to ignore the directories, you can do this.

ls -p | grep -v \/ | head -3

ls -p lists everything in the current directory with the directories followed by a "/"
grep -v \*symbol* takes a stream and filters out the inputs containing symbol (here, the words containing /)
head -3 will provide the first 3 from the list.
_old_
I don't know if there is an easier way to do this, but this works

ls -t | xargs  | awk '{ print $3 }'


text:
Q: Wordpress - Custom template within plugin using template_include The case
I'm creating a WordPress plugin with some predefined *.php pages, located inside the template folder of the plugin. So this folder contains files like "login.php", "register.php" & "activate.php".
These template-pages could be overwritten by a theme. So my plugin should hook the template_include WordPress filter in order to check if the used theme make use of template-overriding. If so, WordPress should load the theme template, otherwise the predefined plugin template should be loaded.
To determine which template should be used for a page, you could select a page inside the Admin area of WordPress by using my plugin (See picture below)
The problem
I don't know how to get the path of the choosen template for a page. This tutorial is helpfull but doesn't 100% match my needs. So I came up with the following code to retrieve the page ID of the template to be retrieved. But since the ID of the template could change, I don't want to hardcode anything. As a result of that I don't know how to continue. Maybe someone could point me into the right direction?
add_filter('template_include', 'getTemplate');
function getTemplate($template)
{
    global $post;

    /*
    $pages = array (
       'Register' => 2,
       'Login' => 3,
       'Logout' => 5,
       'Activate' => 7,
       'Password reset' => 9,
      )
    */

    $pages = get_option('myPlugin-pages');
    $page_id = $pages[$post->post_title];

    // Whats next?

    return $template;
}

Picture explanation
According to the following picture, the left & bold positioned text is the hardcoded name of the plugin pages. So my plugin requires 5 pages. At the right there is a dropdown with a list of all the pages registered by WordPress. When you save these settings, a record is added/updated to the wp_options database table, with a option name like myPlugin-pages.


text:
Q: SPARQL DELETE in 4store I'm trying to delete a few triples from my triple store but, unfortunately, I can't even get this simple query to work:
WITH <GRAPH> DELETE {
  ?s ?p ?o .
} WHERE {
  <URI> <PREDICATE> ?s .
  ?s ?p ?o .
}

I just want to delete all triples that belong to a subject which is itself connected to the URI I have (with the predicate I have).  The WHERE statement in a SELECT query gives me all the solutions that I want to be deleted.
EDIT
Ok, so I kept playing around with it, and for some reason, this works:
WITH <GRAPH> DELETE {
  ?s ?p ?o .
} WHERE {
  <URI> <PREDICATE> ?s .
  {?s ?p ?o .} UNION {?x ?y ?z}
}

Is this really supposed to work like that or is my triple store faulty? (I'm using 4store.)


text:
Q: Google drive API data doesn't match data in UI I'm trying to connect to Google drive to download files to be consumed by a web application.
I'm using a Service Accounts key that I generated in Google Cloud console.
When I list the files with the API I get only 1 folder, but when I look at the UI I see a few files and 1 folder (not the one that I see with the API).
This is a code I use, an indication on what I'm doing wrong?
from google.oauth2 import service_account
from googleapiclient.discovery import build

def init_connection():
    SERVICE_ACCOUNT_FILE = 'credentials.json'

    credentials = service_account.Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE)

    return credentials

def list_files():
    creds = init_connection()

    drive_service = build('drive', 'v3', credentials=creds)
    # Call the Drive v3 API
    results = drive_service.files().list(
        pageSize=10, fields="nextPageToken, files(id, name)").execute(
    print(results)

A: How about this answer?
Issue and workaround:
From When I list the files with the API I get only 1 folder, but when I look at the UI I see a few files and 1 folder (not the one that I see with the API)., I thought that you might have compared the result value retrieved from the service account with the result value shown in your Google Drive. If it's so, the Drive of the service account is different from your Google Drive. I thought that this might be the reason of your issue.
In order to retrieve the files and folders in your Google Drive using the service account, how about the following workaround?
Workaround :
In this workaround, at first, please share a sample folder in your Google Drive with the email of the service account. And, retrieve the file list using the following script.
Sample script:
from google.oauth2 import service_account
from googleapiclient.discovery import build

def init_connection():
    SERVICE_ACCOUNT_FILE = 'credentials.json'

    credentials = service_account.Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE)
    # or, the following script.
    # SCOPES = ['https://www.googleapis.com/auth/drive.readonly']
    # credentials = service_account.Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE, scopes=SCOPES)

    return credentials

def list_files():
    creds = init_connection()

    drive_service = build('drive', 'v3', credentials=creds)
    # Call the Drive v3 API
    folderId = '###'  # Please set the folder ID of the shared folder with the service account.
    results = drive_service.files().list(pageSize=10, fields="nextPageToken, files(id, name)", q="'" + folderId + "' in parents").execute()
    print(results)

References:

*

*Files: list

*Search for files and folders


text:
Q: I'm getting an ERROR of Infinite loop while comparing 2 ArrayList one from server and the another from local Db I'm trying to compare the ArrayList values between the server ArrayList and local DB ArrayList. Where I compare the ID of each ArrayList object from Server and local DB ArrayList and store if its new data to the DB ArrayList.
Below is my Code.
if(!listServer.isEmpty()){
    for(Model server:listServer){
         for(Model Db:listDb){
             while(!listServer.get( i ).getid().equals(listDb.get(i).getid() )){
                  storeIntoDb.add( listServer.get( i ) );
             }
         }
    }
}

I get an infinite loop in the new list which needed to store into local DB. Actually what I want is to compare if I have a new data in the server then store it into local DB.

A: try this :
if(!listServer.isEmpty()){
for(Model server:listServer){
     for(Model db:listDb){
         if(!server.getid().equals(db.getid() )){
              toreIntoDb.add( server );
              }
            }
          }
       }

A: Try This :
for(Model server:listServer){
   boolean inDb = false;
   for(Model db:listDb){
     if(server.getId().equals(db.getId()) {
        inDb = true;
        break;
     }
   }
   if(!inDb) {
       storeIntoDb.add(server);
   }
}

This will do what you want to do, But this approach will lead to performance issues after your database grows.


text:
Q: Can't receive a response message when using proxy-middleware between react ui and express backend I see that the request sent from the ui created using React is forwarded to the backend, but I can't get the response from the ui. There may be details that I missed as I am very new to these issues, thanks in advance :)
//react Login.js
function Login() {
  const fetch = actions.fetchUser();
  async function handleSubmit() {
    try {
      fetch();
    } catch (err) {
      console.error('err', err);
    }
}
export default Login;

//index.js
import axios from 'axios';
export const fetchUser = () => async () => {
  await axios.get('/api/login');
};

//setupProxy.js
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function (app) {
  app.use(
    ['/api'],
    createProxyMiddleware({
      target: 'http://localhost:5000',
    }),
  );
};

//express app.js
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const app = express();
const port = 5000;
app.use(cors());
app.use(bodyParser.json());
require('./routes/login')(app);

app.listen(port, () => {
   console.log(`Example app listening on port ${port}`)
})

// espress login.js
module.exports = app => {
app.get('/api/login', (req, res) => {
   console.error('express login');
    res.send('login');
});

A: First of all, do not mix cjs and mjs import/exports.
second of all, you export your middleware but never register/use it. At least your code does not show that part.
Here is very minimal example how you can proxy your react UI via express.
const express = require('express');
const proxy = require('express-http-proxy');
const app = express();

app.get('/api', (req, res) => {
  res.send({my: 'data'});
});

// register other routes here

app.use(proxy('http://127.0.0.1:3000'));

app.listen(5000, '0.0.0.0', () => {
  console.log('Server is running at http://127.0.0.1:5000');
});

React app content will be available on http://127.0.0.1:5000 with your routes.
And http://127.0.0.1:5000/api will be your express route.
Note: I assume your react app runs on the port 3000


text:
Q: importar una funcion en especifico desde otro programa? tengo dudas sobre módulos, he realizada varias funciones que las tengo almacenas en un programa que realice, y ahora quiero reutilizar una en especifico , se llama comprovarData()

yo la importo de lasiguiente manera :
from principal import comprovarData

La cosa es que al hacer esto es como si se ejecutara todas las linias de codigo donde he importado. Alguien me podría decir que pasa?

A: Lo que ocurre es lo que tiene que ocurrir.
Cuando haces import, ya sea un import modulo o un from modulo import algo, el código del módulo se ejecuta al completo, pues un def es también "ejecutable" para Python, y la única forma de definir las funciones (y análogamente con class para definir clases, debe ejecutarse para que la clase quede definida).
La diferencia entre import modulo y from modulo import algo es que, aunque en ambos casos se ejecuta el contenido completo del fichero, en el primer caso todas las funciones, clases y variables que quedan definidas como consecuencia de esa ejecución quedan "metidas" en un espacio de nombres llamado modulo, de modo que para acceder a ellas debes hacer modulo.algo por ejemplo. En el segundo caso, en cambio, de todas las clases, funciones y variables definidas, python buscará una llamada algo y la añadirá al espacio de nombres global, de modo que se pueda acceder a ella sin tener que poner delante ningún espacio de nombres.
No puedes evitar que se ejecute el código completo del módulo, pero sí puedes evitar que al importar el módulo se ejecute la función main() de ese módulo ¿cómo? Simplemente no invocándola en el módulo.
El patrón típico (que quizás hayas visto ya) es el siguiente:
# Contenido del modulo
def funcion1():
   ...

def funcion2():
   ...

def main():
   ...

if __name__ == "__main__":
   main()

Esto se ejecuta desde el inicio hasta el fin, tanto si lanzas este script desde línea de comandos con python modulo.py como si importas el módulo desde otro mediante import modulo (o from modulo import funcion1).
En ambos casos se evalúan todas las líneas de modulo.py. La diferencia es que Python asigna diferente valor a la variable __name__. Cuando ejecutas ese script desde línea de comandos, el valor asignado es "__main__". Cuando lo importas, esa variable tiene el valor "modulo" (el nombre del módulo que está siendo importado).
De este modo puedes hacer que ciertas líneas sólo se ejecuten si lanzas el script desde línea de comandos y no si lo importas.


text:
Q: Scrollable widget not filled I tried to get a resizeable widget working, but it won't. I've got a database which I use with greenDAO. So my app should work on Android 2.3+. That's why I want to have got the following widgets:

*

*4x2 with 2 items

*4x3 with 3 items

*4x4 with 4 items

*4x5 with 5 items

In preHoneycomb these Widgets should just show the first items and opens the app on click.
In Android 3+ these widgets should be realizable and scrollable. My problem is that my Widget Service class is never called. So nothing inside the widget will be filled :-
Here is my code:
public class WidgetProvider extends AppWidgetProvider {

private static final String TAG = "WidgetProvider";

@TargetApi(14)
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
        int[] appWidgetIds) {

    Log.i(TAG, "Update!!");

    for (int i = 0; i < appWidgetIds.length; ++i) {
        int appWidgetId = appWidgetIds[i];

        Intent intent = new Intent(context, TimetableActivity_.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
                intent, 0);

        Intent svcIntent = new Intent(context, WidgetService.class);
        svcIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
                appWidgetIds[i]);
        svcIntent.setData(Uri.parse(svcIntent
                .toUri(Intent.URI_INTENT_SCHEME)));

        RemoteViews views = new RemoteViews(context.getPackageName(),
                R.layout.widget);
        views.setOnClickPendingIntent(R.id.img_widget_home, pendingIntent);
        views.setRemoteAdapter(R.id.btn_widget_refresh, svcIntent);

        Intent update = new Intent(context, WidgetProvider.class);

        intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
        intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds);

        PendingIntent pend = PendingIntent.getBroadcast(context, 0, update,
                PendingIntent.FLAG_UPDATE_CURRENT);

        views.setOnClickPendingIntent(R.id.btn_widget_refresh, pend);

        appWidgetManager.updateAppWidget(appWidgetId, views);
    }

    super.onUpdate(context, appWidgetManager, appWidgetIds);
}

@TargetApi(11)
public class WidgetService extends RemoteViewsService {

    private static final String TAG = "WidgetService";

    @Override
    public RemoteViewsFactory onGetViewFactory(Intent intent) {

        Log.i(TAG, "WidgetService called");

        return new ListRemoteViewsFactory(this.getApplicationContext(),
                (TimetableApplication_) this.getApplication(), intent);
    }
}

class ListRemoteViewsFactory implements RemoteViewsService.RemoteViewsFactory {
    private static final String TAG = "ListRemoteViewsFactory";

    private Context mContext;

    private TimetableApplication_ application;
    private List<Events> events = new ArrayList<Events>();

    public ListRemoteViewsFactory(Context context,
            TimetableApplication_ application, Intent intent) {
        this.mContext = context;
        this.application = application;
    }

    public int getCount() {
        return events.size();
    }

    public RemoteViews getViewAt(int position) {
        Log.i(TAG, ""+getCount());

        String title = "";
        String description = "";
        Events e;

        if ((e = events.get(position)) != null) {
            title = e.getSubjects().getTitle();
            description = e.getStart().toGMTString();
        }

        RemoteViews rv = new RemoteViews(mContext.getPackageName(),
                R.layout.widget_item);
        rv.setTextViewText(R.id.txt_widget_item_title, title);
        rv.setTextViewText(R.id.txt_widget_item_description, description);

        return rv;
    }

    public RemoteViews getLoadingView() {
        return null;
    }

    public int getViewTypeCount() {
        return 1;
    }

    public long getItemId(int position) {
        return position;
    }

    public boolean hasStableIds() {
        return true;
    }

    public void onDataSetChanged() {
        if (events != null) {
            events.clear();
        }

        events = application.getEvents();
    }

    @Override
    public void onCreate() {
    }

    @Override
    public void onDestroy() {
    }
}

And here is my Manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="de.mprengemann.hwr.timetabel"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="9"
        android:targetSdkVersion="15" />

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="android.permission.READ_CALENDAR" />
    <uses-permission android:name="android.permission.WRITE_CALENDAR" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <application
        android:name=".TimetableApplication_"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/TimetableTheme" >
        <activity
            android:name=".TimetableActivity_"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".PreferenceActivity_"
            android:label="@string/menu_settings" >
        </activity>
        <activity android:name=".SubjectDetailActivity_" >
        </activity>

        <receiver android:name=".widget.WidgetProvider" >
            <intent-filter>
                <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
            </intent-filter>

            <meta-data
                android:name="android.appwidget.provider"
                android:resource="@xml/widgetprovider" />
        </receiver>

        <service android:name=".widget.WidgetService" />
        <service android:name=".widget.ListWidgetService" />
    </application>

</manifest>

Thanks for your help! :-)

A: Sorry I realise this is an old post but it could be that your problem is that you haven't included a required permission for your widget sevice in the manifest file....
You could try changing:
<service android:name=".widget.WidgetService" />

To
<service android:name=".widget.WidgetService" android:permission="android.permission.BIND_REMOTEVIEWS" />


text:
Q: BetweenPosition and WithinPosition in Biopython What is the difference between "BetweenPosition" and "WithinPosition" in Biopython.
It seems like one of them is inclusive of the endpoints, and the other is not -- but the description in the Biopython documentation didn't seem to describe that explicitly.

A: BetweenPosition is basically obsolete and can be ignored.


text:
Q: OOfflineClusterException Message: Cannot read a record from the offline cluster If some record is available in an offline cluster and I try to fetch it using index, it gives OOfflineClusterException. Why should it access offline cluster, shouldn't it be normal record not found situation.

A: You're right, I've just opened an new issue for this, and fixed in v2.1.7-SNAPSHOT. v2.1.7 GA will be online in few hours.


text:
Q: SPSS - Binary logistic regression: classification cutoff Let's say I want to evaluate the predictive value of a continuous variable in the prediction of malignancy (event/status) of a tumour.
Malignant = 1
Nonmalignant = 0
In SPSS, I can run a binary logistic regression model to do so. It allows me to set a cutoff value for classification. My question is: SPSS assumes equal pretest chances and odds in both groups, and proposes a cutoff value of 0.5. However, research has shown that malignant tumours are 70 % of all tumours, and nonmalignant tumours are 30 % of all tumours. Hence, a priori, there is a chance of 70 % for a tumour to be malignant. There is, however, no way to include an a priori chance in SPSS (at least, not by my knowledge). Am I instead allowed to change the cutoff value to 0.5/(0.7/0.5)?
The rationale is that the probability for malignancy is 0.7/0.5 times larger than 0.5, and thus that, instead of changing pretest probabilities, the posttest probability could be reduced by a factor 0.7/0.5.
Is this correct, or not?

A: It's easy to get confused between the two different types of probabilities that you face in this type of study. One is the probability, before you've run any tests, that someone with such a tumor has the malignant type: the 70% prevalence of the malignant form for this type of tumor. It is prior, apriori probability. The second is the probability, after you've run the test to get the biomarker value, that a tumor with a particular biomarker value is malignant. That depends on the quality of your biomarker and your probability model. It is predicted probability. There may be no simple relation between these two types of probabilities.
A logistic regression model is a model of probabilities, as this answer among others on this site emphasizes. That's a model of the second type of probability: If I know the value of the biomarker, what's the probability that the tumor is malignant?
As an extreme example, say that all tumors with biomarker values < 9 were benign, all those with values > 11 were malignant, and the few tumors with values between 9 and 11 had a 50/50 chance of being malignant. So a tumor with a value of 10 has a probability of 0.5 of being malignant.
If you wanted to use a cutoff to map probabilities into yes/no predictions, then 10 could be a reasonable choice of cutoff even though it maps to the 0.5 probability cutoff in your model of that second type of probability. You would still score about 70% of tumors as malignant because about 70% of tumors have scores above the value of 10, the first type of probability. It's the prevalence of the biomarker scores among tumors, not the choice of cutoff probability itself, that's related to the overall prevalence of malignancy if you have a near-perfect biomarker like this.
That said, it is seldom wise to reduce your logistic regression probability model directly to an immediate yes/no decision about tumor type. In a clinical context there is always other information available that needs to be taken into account. And you also have to weigh the relative costs of misclassification: what are the risks of treating a benign tumor as if it were malignant, versus the risks of treating a malignant tumor as if it were benign? If you are forced for some reason to make an all-or-none decision about classification, it's those relative risks that should be informing your cutoff.


text:
Q: Selenium abotring with "UnreachableBrowserException/Address already in use" occurring on one computer I have a java webdriver driven selenium execution which does a loop over a list to enter different infomation into a textbox and sending it using the FirefoxDriver.
On one computer, quite reproducible, after the 10th or 11th iteration, the call of  findElement(By.id("mi4")) raises an UnreachableBrowserException.
Jun 29, 2012 1:52:02 PM org.apache.http.impl.client.DefaultRequestDirector tryConnect
Information: I/O exception (java.net.BindException) caught when connecting to the target host: Address already in use: connect
Jun 29, 2012 1:52:02 PM org.apache.http.impl.client.DefaultRequestDirector tryConnect
Information: Retrying connect
Jun 29, 2012 1:52:02 PM org.apache.http.impl.client.DefaultRequestDirector tryConnect
Information: I/O exception (java.net.BindException) caught when connecting to the target host: Address already in use: connect
...
Exception in thread "main" org.openqa.selenium.remote.UnreachableBrowserException: Error communicating with the remote browser. It may have died.
Build info: version: '2.24.1', revision: '17205', time: '2012-06-19 15:28:49'
System info: os.name: 'Windows XP', os.arch: 'x86', os.version: '5.1', java.version: '1.7.0_04'
Driver info: driver.version: RemoteWebDriver
   at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:467)
   at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:242)
Caused by: java.net.BindException: Address already in use: connect
   at java.net.TwoStacksPlainSocketImpl.socketConnect(Native Method)
   at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
   at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:820)
   at org.openqa.selenium.remote.HttpCommandExecutor.fallBackExecute(HttpCommandExecutor.java:337)
   at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:297)
   at org.openqa.selenium.firefox.internal.NewProfileExtensionConnection.execute(NewProfileExtensionConnection.java:136)

There is no third party program listening on any ports. However, I use two instances of FirefoxDriver, meaning two Firefox instances/Windows opened in parallel, which works without any problem on a Win7 machine, the problem described occurs on a Windows XP machine.
I use Firefox 13 with selenium 2.24.1.

A: It sounds like you are running out of ephemeral ports since you are iterating over and over. The default maximum number of ephemeral TCP ports is 5000 in windows XP. Try increasing the limit as per the resolution in Microsoft KB article here. Restart the machine. This solution has worked for me.


text:
Q: How to check of the user input value is Upper case, Lower case or a digit using Shell Script? I am trying to write a shell script to read user input data and check if the input value is either Upper Case, Lower Case or anything else. But what I wrote is only checking a single character
Here is what I wrote:
printf 'Please enter a character: '
IFS= read -r c
case $c in
  ([[:lower:]]) echo lowercase letter;;
  ([[:upper:]]) echo uppercase letter;;
  ([[:alpha:]]) echo neither lower nor uppercase letter;;
  ([[:digit:]]) echo decimal digit;;
  (?) echo any other single character;;
  ("") echo nothing;;
  (*) echo anything else;;
esac

How can I make it read a long String other than a single character and get the output accordingly?

A: You can do it in many ways, here you have one:
#!/bin/bash

read -p "Enter something: "  str
echo "Your input is: $str"

strUppercase=$(printf '%s\n' "$str" | awk '{ print toupper($0) }')
strLowercase=$(printf '%s\n' "$str" | awk '{ print tolower($0) }')

if [ -z "${str//[0-9]}" ]
then
    echo "Digit"
elif [ $str == $strLowercase ]
then
    echo "Lowercase"
elif [ $str == $strUppercase ]
then
    echo "Uppercase"
else
    echo "Something else"
fi

A: Preceding your use with shopt -s extglob, you can use +([[:upper:]]) to match a string composed of one or more uppercase letters.
From man 1 bash:
       If the extglob shell option is enabled using the shopt builtin, several
       extended  pattern  matching operators are recognized.  In the following
       description, a pattern-list is a list of one or more patterns separated
       by a |.  Composite patterns may be formed using one or more of the fol‐
       lowing sub-patterns:

              ?(pattern-list)
                     Matches zero or one occurrence of the given patterns
              *(pattern-list)
                     Matches zero or more occurrences of the given patterns
              +(pattern-list)
                     Matches one or more occurrences of the given patterns
              @(pattern-list)
                     Matches one of the given patterns
              !(pattern-list)
                     Matches anything except one of the given patterns

Use, for example, +([[:upper:][:digit:] .]) to match one or more {uppercase letters, digits, spaces, dots}. Consider using some of the other following classes defined in the POSIX standard:
alnum alpha ascii blank cntrl digit graph lower print punct space upper word xdigit
Proof (just a test on an example) that it works:
shopt -s extglob; case "1A5. .Q7." in (+([[:upper:][:digit:] .])) echo "it works";; esac


text:
Q: QProcess does not properly trigger executable .sh Probelm: I have been trying to run an executable file using QProcess triggering the executable file using a QPushButton and showing the whole result of the output on QTextEdit but without success.
*The error: I don't see the whole output despite, following the official documentation I used this->executeJuliaCheck->readAllStandardOutput()
I have an executable file called check_julia.sh which is located in /home/esoMars/Alignsys/scripts/check_julia.sh which is in the qrc folder of a standard Qt5 project. The file is very simple and is below:
#!/bin/bash

echo "Checking"
cd /home/esoMars/julia-1.7.3/bin
julia

If I type on my home folder the command (base) eso@eso-Oryx-Pro:~$ julia the folloing output appears:
   _       _ _(_)_     |  Documentation: https://docs.julialang.org
  (_)     | (_) (_)    |
   _ _   _| |_  __ _   |  Type "?" for help, "]?" for Pkg help.
  | | | | | | |/ _` |  |
  | | |_| | | | (_| |  |  Version 1.7.3 (2022-05-06)
 _/ |\__'_|_|_|\__'_|  |  Official https://julialang.org/ release
|__/                   |

julia>

All this happens because I use the command line.
Desired goal: I would like NOT to use a command line, but rather I am trying to use a small graphical user interface where to show the output of the same command(base) eso@eso-Oryx-Pro:~$ julia
The way I am doing it is by using a QPushButton that check if julia is installed and show the output on a QTextEdit.
Below what I have done so far:
main.cpp
#include "mainwindow.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();
    return a.exec();
}

mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QProcess>

QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = nullptr);
    ~MainWindow();
    void check_julia_installation();

private slots:
    void on_juliaCheckBtn_clicked();

private:
    Ui::MainWindow *ui;
    QProcess *executeJuliaCheck;
    void executeJulia(QString command);
};
#endif // MAINWINDOW_H

mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
#include <QDir>
#include <QStringLiteral>
#include <iostream>

using namespace std;

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    // Check Julia Installation
    check_julia_installation();
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::check_julia_installation()
{
    // Execution of the QProcess
    this->executeJuliaCheck = new QProcess(this);
    this->executeJuliaCheck->setProcessChannelMode(QProcess::MergedChannels);
    QObject::connect(this->executeJuliaCheck, QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished),
            [this](int exitCode, QProcess::ExitStatus exitStatus){
            qDebug() << "CODE " << exitCode << exitStatus;

                if(exitCode == 0)
                {
                    QString stdOutput = QString::fromUtf8(this->executeJuliaCheck->readAllStandardOutput());
                    qDebug() << stdOutput;
                    ui->textEdit->setText(stdOutput);
                    ui->outputLineEdit->setText("SUCCESS: JULIA IS PROPERLY INSTALLED");
                }
                else
                {
                    QString stdErr = QString::fromUtf8(this->executeJuliaCheck->readAllStandardError());
                    qDebug() << stdErr;
                    QString stdOutput = QString::fromUtf8(this->executeJuliaCheck->readAllStandardOutput());
                    qDebug() << stdOutput;
                    ui->textEdit->setText(stdErr + "\n" + stdOutput);
                    ui->outputLineEdit->setText("CONNECTION ERROR: JULIA NOT PRESENT");
                }
                ui->juliaCheckBtn->setEnabled(true);
    });
}

void MainWindow::on_juliaCheckBtn_clicked()
{
  this->executeJuliaCheck->start("sh",QStringList() << "-c" << "echo /home/esoMars/Alignsys/scripts/check_julia.sh");

  if(! this->executeJuliaCheck->waitForStarted()) //default wait time 30 sec
      qWarning() << " cannot start process ";

  int waitTime = 60000 ; //60 sec
  if (! this->executeJuliaCheck->waitForFinished(waitTime))
           qWarning() << "timeout .. ";
  this->executeJuliaCheck->waitForFinished();

ui->juliaCheckBtn->setEnabled(true);

}

Updates
A user suggested to reduce the clicked button to the following statement. I tried that but unfortunately the QProcess does not do anything:
void MainWindow::on_juliaCheckBtn_clicked()
{
    this->executeJuliaCheck->waitForStarted();
    this->executeJuliaCheck->start("sh",QStringList() << "-c" << "echo /home/esoMars/Alignsys/scripts/check_julia.sh");
    ui->juliaCheckBtn->setEnabled(true);
}

I looked up QProcess quite a while before writing and searched a lot. I found quite a few posts that I read and studied to understand the problem. One post suggested to look at setWorkingDirectory which I did but that didn't help much.
Another posts suggested to use for waitForFinished() just in case other processes are running but it is not my case. Despite a clean exit I don't see the whole output.  However, for debugging reasons I put this->executeJuliaCheck->start("sh",QStringList() << "-c" << "echo /home/esoMars/Alignsys/scripts/check_julia.sh"); so that I could confirm the executable file read. However, I still can't see the whole output
I looked also at additional posts such as this one but I still could not figure out how to show the whole output.
Thanks for pointing in the right direction.

A: I believe you want to see the Julia banner in order to show it to the user.
The problem is that once started, the Julia process is waiting for the input.
This can be simply circumvented as:
$ echo "exit()" | julia --banner=yes
               _
   _       _ _(_)_     |  Documentation: https://docs.julialang.org
  (_)     | (_) (_)    |
   _ _   _| |_  __ _   |  Type "?" for help, "]?" for Pkg help.
  | | | | | | |/ _` |  |
  | | |_| | | | (_| |  |  Version 1.8.0 (2022-08-17)
 _/ |\__'_|_|_|\__'_|  |  Official https://julialang.org/ release
|__/                   |

$

The above command produces the banner (so you can collect it by reading the standard output of your process) and then immediately exits.


text:
Q: UIStackView - drag to reorder arranged subviews? I'm trying to get some advice on how to go about implementing the same sort of "drag to reorder" behavior found on a UITableView but on a UIStackView.
So far this is what I'm thinking:

*

*Add a long press gesture recognizer to each of the arrangedSubviews

*On long press, add an overlay UIView as a subview to the main view and that fills the entire main view. This overlay view will act as a "canvas" of sorts as I'm dragging the temporary "reorder" view—we'll call this the tempView— around (more on that in 4)

*Set the alpha of the arrangedSubview to 0 (setting hidden = true would result in the UIStackView animating closing in as if it were removed.

*Add a tempView to the overlay view (see 3) with the same initial frame as the arrangedSubview

*Drag the tempView up or down and insert/remove the actual arrangedSubview at a calculated index based on the position of the tempView.

*Listen for when the long press state is .Ended and set the arrangedSubview.alpha = 1 and remove the overlay view from the main view.

Any suggestions? Any glaring holes that anyone sees? What would you change? What direction would you go to accomplish this?

A: I've created a custom control to solve this problem that can be found here.
Please see my last comment on the question post regarding known issues and future updates.


text:
Q: Как сохранить русские названия папок при копировании на ftp? Для связи с ftp сервером использую org.apache.commons.net.ftp библиотеку. Все работает, претензий никаких. Но на локальной машине встречаются файлы и папки вида qweУЙ12.22.12, то есть содержащие в себе русские буквы. Естественно моя программа копирует имена этих папок и файлов на ftp сервер неверно (заменяет русские буквы на ??). Как я могу копировать каталоги, содержащие русские буквы?
A: Надо посмотреть в каком виде читает ваш клиент русские имена файлов (кодировка Win-1251?)из локальной машины. По идее (если все настроено правильно) она должна транслировать их нормально - выведите их имена в лог и сразу увидите имена правильные или нет.
Далее надо посмотреть/получить кодировку оси на удаленной машине (КОИ-8/UTF-8?). Если ваша библиотека не обеспечивает автоматом кодировку - то надо перекодировать полученные из локальной машины имена в кодировку удаленного сервера.
В общем смысл в том, чтобы передавать на удаленную машину правильные имена.
A: FTPClient ftpClient = new FTPClient();
ftpClient.setControlEncoding("CP1251");
ftpClient.connect(server, port);

A: Решил просто... Почему-то на всех фтп что я видел внутренняя кодировка koi8-r поэтому при считывании файлов я конвертировал все в utf-8 так как использовал java. А когда грузил на фтп конвертировал в koi8-r.
A: Не создавал вообще каталоги с кириллицей, пока не добавил кодировку. Главное установить кодировку до соединения с сервером.
val ftpClient = FTPClient()
ftpClient.controlEncoding = "Windows-1251"
ftpClient.connect(host, port)


text:
Q: Проверить на js существование Cookie Появилась задача проверить существование COOKIE на стороне клиента, если существует, предоставить доступ{Вопрос закрыт}

A: // возвращает cookie с именем name, если есть, если нет, то undefined
function getCookie(name) {
  var matches = document.cookie.match(new RegExp(
    "(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
  ));
  return matches ? decodeURIComponent(matches[1]) : undefined;
}

Взято от сюда

A: Cкрипт, суть которого в том, чтобы он проверял наличие куков у пользователя. Если их нет, то ничего не происходит, если они есть и их значение "yes", то выполняется действие. Источник: тык

function setcookie(a,b,c) {if(c){var d = new Date();d.setDate(d.getDate()+c);}if(a && b) document.cookie = a+'='+b+(c ? '; expires='+d.toUTCString() : '');else return false;}
function getcookie(a) {var b = new RegExp(a+'=([^;]){1,}');var c = b.exec(document.cookie);if(c) c = c[0].split('=');else return false;return c[1] ? c[1] : false;}

setcookie("block","yes",10) //Cтавим кук (10 - число действующих дней

var block = getcookie( "block" );

   if ( block != "yes")
  {
    alert('TEST');
  }
  else
  {
    $("#errorbody").show("fast");
  }


text:
Q: Softlayer API: Cannot cancel virtual machine Team,
I am having issues canceling a virtual machine via API/CLI.
slcli virtual cancel 27493017

This action cannot be undone! Type "27493017" or press Enter to abort:
  27493017 SoftLayerAPIError(SoftLayer_Exception_Public): This
  cancellation could not be processed please contact support.This
  cancellation could not be processed. Please contact support. Unable to
  create cancel ticket for virtual server.

slcli --version
slcli (SoftLayer Command-line), version 5.1.0

I can cancel through the UI
-Guy

A: Something weird, I recommend to submit a ticket for further assistance. but I see the virtual: 27493017 is already deleted.

A: A lot of times when you see that message it indicates that an existing transaction is on going for the VSI. Double check with the command slcli --format=raw call-api Virtual_Guest getActiveTransaction --id=VIRTUAL_GUEST_ID