text:
Q: Complete the payment process with PayPal Java and get the status whether it is completed successfully or not to integrate PayPal payment into Java web application ,i use this link Text,
but when i verify the paypal sandbox account for both buyer and seller i found the transaction will be added but it has a "pending" status and the money is not changing,so i want to complete the transaction to transfer money from buyer to seller and paypal inform me whether the transaction is successful or not.

A:
I found the transaction will be added but it has a "pending" status

There are a few possible reasons for this, one is simply the expected behavior of requestPayment.setIntent("authorize");. You may simply want to change that to "sale" if it's not being captured automatically by the guide you were following.
Another possible reason is the currency if it is new to that sandbox receiver account. Log into the receiver account via https://www.sandbox.paypal.com , and see if you can accept one of the payments in the new currency, which will open a currency balance. Future payments won't be pending.
Also ensure the sandbox Business account receiving the payment has a confirmed email in the sandbox environment...

*

*Log into it at https://www.sandbox.paypal.com/businessprofile/settings/email

*Send the confirmation from there, if necessary

*Read and proceed with the confirmation, via https://www.paypal.com/signin?intent=developer&returnUri=https%3A%2F%2Fdeveloper.paypal.com%2Fdeveloper%2Fnotifications%2F


text:
Q: How to load valid current days in rails date_select tag I have used date_select :filter, :start_date in my application. I need to load valid date for current month. for example default date loaded for february month is 1 to 31 but need to load actual days for February (1 to 28).
How to resolve ?
Thanks in advance.

A: You can use the activesupport helpers for date to get the start and end of the month and then add that into a range. Once you have the range then you can pass that to options_from_collection_for_select.
For example:
<% range = (DateTime.now.beginning_of_month .. DateTime.now.end_of_month) %>
<%= select_tag :date,
      options_from_collection_for_select(
        range.collect{|d|['date', d.mday]}, :first, :last) %>

redpajama_set_name: RedPajamaStackExchange


text:
Q: What should a reply to "What's up?" be? How should you reply to "what's up?"

A: Normally people reply "not much", which I think is the appropriate way of answering this question when you are not doing anything. But in case you are doing something, it would be better to say what you are doing.

A: To me, and probably to most of my fellow Britons, the question "What's up?" means "What's wrong?" or "What's the matter?" — usually asked of someone looking sad or angry. The normal reply would be to say "Nothing" or give the reason for the sadness or anger.

A: "What's up" means "What's happening." I usually just reply "nothing." because nothing is happening to me.
But, there are alternatives, such as the usual reply to a greeting:

*

*Not much

*Nothing. Yourself?

*I'm good, yourself?

*Good. How are you?

However, if there is something that you would like to tell the other person e.g. You've sold your car, it might go like this:

A: What's up?
  B: I've sold my car.
  A: Good on you mate!

A:
Some dude: Hey, what's up?
You: Just chillin.


text:
Q: how to have root partition LVM for RHEL 5.8 64 bit on AWS EC2 I have to create a RHEL 5.8 Amazon Machine Image (AMI) in which the root partition should be a logical volume. I know how to create a data partition as a logical volume but am not able to find how to create the root partition as a LVM.

A: It is just the same as a data partition. Just the /boot partition can't live on LVM. At least in Fedora, the installer guides you through all steps here.


text:
Q: Android Activity life cycle issues What I actually Wanted ?
In my app I have 4/5 activities and one background thread which talks with the server. I wanted to have some way to get the top most activity of my app. But surprisingly their was no way I could get that ?
What I did ?
After searching for a while, I implemented a variable mCurrentOnTopActivity of Type Activity and on onResume() and onPause() of every activity I set that variable. (That is actually a bad way).
Where I reached ?
Now their are cases in which after receiving some messages from the server I want to do some thing on UI thread i.e. show some dialogs or refresh ListView, now their is no way to check whether the mCurrentOnTopActivity refers an activiy which is actually running or not (finished or out Of focus for whatever reason).
What I want now ?
Now I basically want help in following two problems:-

*

*How do I know which is the currently running top most activity of my App ?

*How do I know whether activity is still running or not (i.e. I want some thing like isActicitAlive() (imaginary function) which returns true between calls of onResume() and onPause() ?

I implemented 2 point using a variable in activity and setting it in onResume() and onPause(). But, is this the only way to do this ?

A: ArrayList<String> runningactivities = new ArrayList<String>();

ActivityManager activityManager = (ActivityManager)getBaseContext().getSystemService (Context.ACTIVITY_SERVICE);

List<RunningTaskInfo> services = activityManager.getRunningTasks(Integer.MAX_VALUE);

for (int i1 = 0; i1 < services.size(); i1++) {
    runningactivities.add(0,services.get(i1).topActivity.toString());
}

if(runningactivities.contains("ComponentInfo{com.app/com.app.main.MyActivity}")==true){
    Toast.makeText(getBaseContext(),"Activity is in foreground, active",1000).show();
}

With this, you can check, whether the activity you are looking for is running or not.
esle, if you want to use the onStart() and onStop() methods, you can use the following code,
class MyActivity extends Activity {
     static boolean active = false;

      @Override
      public void onStart() {
         super.onStart();
         active = true;
      }

      @Override
      public void onStop() {
         super.onStop();
         active = false;
      }
}

A: You could use service binding so that only your topmost activity binds to the service.


text:
Q: How to get a pointer to a variable that's masked as an interface? I prefer not to dive into the rationale of the situation below. It has to do with unmarshaling an serialized object that can be any of a fixed set of types, but you don't know which type.
I have the following types:

type I interface {
    Do()
}

type someI struct {}
func (i *someI) Do() {}

type otherI struct {}
func (i *otherI) Do() {}

So, two structs of which the pointers implement interface I.
Now I have this method that wants to return a value of type I:
func GetSomeI(marshalled []byte) (I, error) {
    var obj interface{}
    // The following method magically puts an instance
    // of either someI or otherI into obj.
    magicUnmarshall(marshalled, obj)
    // The problem now is that we cannot return obj,
    // because the raw structs don't implement I.

    // One solution would be to do a type switch like this:
    switch obj.(type) {
    case someI:
        i := obj.(someI)
        return &i, nil
    case otherI:
        i := obj.(otherI)
        return &i, nil
    default:
        return nil, errors.New("marschalled object was not of type I")
    }

    // But now consider the case that there are quite some
    // different implementations of I.
    // We would prefer to have a general way of getting
    // a reference to obj.
}

A: To tell if a value wrapped in an interface{} implements some other interface (I), you may simply use a type assertion.
Note that you must pass the address of the variable you want results unmarshaled to.
For demonstration purposes, let's use the following magicUnmarshal() function:
func magicUnmarshal(what int, obj interface{}) {
    v := reflect.ValueOf(obj).Elem()
    switch what {
    case 0:
        v.Set(reflect.ValueOf(&someI{}))
    case 1:
        v.Set(reflect.ValueOf(&otherI{}))
    case 2:
        v.Set(reflect.ValueOf("just a string"))
    case 3:
        v.Set(reflect.ValueOf(someI{}))
    case 4:
        v.Set(reflect.ValueOf(otherI{}))
    }
}

Note that case 3 and case 4 are returning non-pointers.
Your GetSomeI() implementation can be:
func GetSomeI(what int) (I, error) {
    var obj interface{}
    magicUnmarshal(what, &obj)

    // Try the value as-is:
    if i, ok := obj.(I); ok {
        return i, nil
    }

    // No success. Try a pointer to the value:
    v := reflect.Indirect(reflect.New(reflect.TypeOf(obj)))
    v.Set(reflect.ValueOf(obj))
    pobj := v.Addr().Interface()
    if i, ok := pobj.(I); ok {
        return i, nil
    }

    return nil, fmt.Errorf("%T does not implement I!", obj)
}

First GeSomeI() tests if the value got form magicUnmarshal() implements I, and if so, it is used as-is. If not, we construct a new using reflection, and get its address (a pointer to a value), and we test that. If that pointer implements I, we return it.
Testing it:
func main() {
    for what := 0; what < 5; what++ {
        i, err := GetSomeI(what)
        fmt.Printf("%T %v\n", i, err)
    }
}

And the output is (try it on the Go Playground):
*main.someI <nil>
*main.otherI <nil>
<nil> string does not implement I!
*main.someI <nil>
*main.otherI <nil>


text:
Q: Gulp: concatenate a file to each separate sass process I wrote a gulp task to process all scss files in one folder into separate css files.
gulp.task('process', function () {
  gulp.src(['./base.scss', './layout/*.scss'])
    .pipe(sass())
    .pipe(gulp.dest('dist'))
});

Now I want to concatenate one file (base.scss) to each scss process; how can I do this?

A: This should help you but I didn't test it.  Gulp-foreach is good for you, it will treat each file from gulp.src as its own stream which you can manipulate separately.  The code below then appends your base.scss to each stream, then concatenates them and then they go through the sass pipe.
var foreach = require('gulp-foreach');
var concat = require('gulp-concat');
var addsrc = require('gulp-add-src');

gulp.task('default', function () {
  return gulp.src('./layout/*.scss')
      // treats each file in gulp.src as a separate stream
    .pipe(foreach(function (stream, file) {
      return stream
         // append or prepend
       .pipe(addsrc.append('./base.scss'))
        //  you do have access to the 'file' parameter here if you need to rename
       .pipe(sass())
       .pipe(concat(path.basename(file.path)))
       .pipe(gulp.dest('dist'));
    }));
});

Let me know if it works for you.


text:
Q: How to make a Square Frame Layout? I tried making custom MySquareFrame class by extending android.widget.FrameLayout and override onMeasure mehtod by passing custom width and height.
public class MySquareFrame extends FrameLayout {

public MySquareFrame(Context context) {
    super(context);
}

public MySquareFrame(Context context, AttributeSet attrs) {
    super(context, attrs);
}

public MySquareFrame(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
}

@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public MySquareFrame(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
    super(context, attrs, defStyleAttr, defStyleRes);
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    int width = MeasureSpec.getSize(widthMeasureSpec);
    int height = MeasureSpec.getSize(heightMeasureSpec);
    int size = width > height ? height : width;
    setMeasuredDimension(size, size);
}
}

and used this in xml like this
<com.example.akash.view.MySquareFrame
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/background3">
<ImageView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:src="@drawable/fuel_meter"
    android:rotation="120"
    />
<com.triggertrap.seekarc.SeekArc
    android:id="@+id/seekArc"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    seekarc:max="120"
    android:padding="70dp"
    seekarc:rotation="180"
    seekarc:startAngle="30"
    seekarc:sweepAngle="300"
    seekarc:touchInside="false"
    seekarc:clockwise="false"
    seekarc:thumb="@drawable/nob" />
</com.example.akash.view.MySquareFrame>

and what I get

So I want MySquareFrame class to look Square in xml. Please help..
--------------------UPDATED-------------------------
DisplayMetrics displaymetrics = new DisplayMetrics();
    ((Activity) getContext()).getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
    int height = displaymetrics.heightPixels;
    int width = displaymetrics.widthPixels;
    int size = width > height ? height : width;
    setMeasuredDimension(size, size);

this helped me to get square frame according to screen dimension.

A: You can see implementation of SquareFrameLayout from android developers website:

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        final int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        final int heightSize = MeasureSpec.getSize(heightMeasureSpec);

        if (widthSize == 0 && heightSize == 0) {
            // If there are no constraints on size, let FrameLayout measure
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);

            // Now use the smallest of the measured dimensions for both dimensions
            final int minSize = Math.min(getMeasuredWidth(), getMeasuredHeight());
            setMeasuredDimension(minSize, minSize);
            return;
        }

        final int size;
        if (widthSize == 0 || heightSize == 0) {
            // If one of the dimensions has no restriction on size, set both dimensions to be the
            // on that does
            size = Math.max(widthSize, heightSize);
        } else {
            // Both dimensions have restrictions on size, set both dimensions to be the
            // smallest of the two
            size = Math.min(widthSize, heightSize);
        }

        final int newMeasureSpec = MeasureSpec.makeMeasureSpec(size, MeasureSpec.EXACTLY);
        super.onMeasure(newMeasureSpec, newMeasureSpec);
    }

A: Check out SquareLayout, an Android Library which provides a wrapper class for different Layouts, rendering them Squared dimensioned without losing any core functionalities.
The dimensions are calculated just before the Layout is rendered, hence there is no re-rendering or anything as such to adjust once the View is obtained.
To use the Library, add this to your build.gradle:
repositories {
    maven {
        url "https://maven.google.com"
    }
}

dependencies {
    compile 'com.github.kaushikthedeveloper:squarelayout:0.0.3'
}

A: I've found a much "reduced" solution for this. Create your own OneOneFrameLayout as follows and then just add this FrameLayout to your xml:
public class OneOneFrameLayout extends FrameLayout {

public OneOneFrameLayout(@NonNull Context context) {
    super(context);
}

public OneOneFrameLayout(@NonNull Context context, @Nullable AttributeSet attrs) {
    super(context, attrs);
}

public OneOneFrameLayout(@NonNull Context context, @Nullable AttributeSet attrs, @AttrRes int defStyleAttr) {
    super(context, attrs, defStyleAttr);
}

public OneOneFrameLayout(@NonNull Context context, @Nullable AttributeSet attrs, @AttrRes int defStyleAttr, @StyleRes int defStyleRes) {
    super(context, attrs, defStyleAttr, defStyleRes);
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    int snHeight = MeasureSpec.getSize(widthMeasureSpec);
    int snHeightSpec = MeasureSpec.makeMeasureSpec(snHeight, MeasureSpec.EXACTLY);
    super.onMeasure(widthMeasureSpec, snHeightSpec);
}
}

A: For purposes of wanting square views using GridLayoutManager, Koopa has a good answer but you already have the widthMeasureSpec.
The width is all that matters, then get the height to match the width:
package com.my.package;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.FrameLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

public class SquareFrameLayout extends FrameLayout {

    public SquareFrameLayout(@NonNull Context context) {
        super(context);
    }

    public SquareFrameLayout(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public SquareFrameLayout(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, widthMeasureSpec); //<-- Width + Width...
    }
}

Simply use it in the xml layout file:
<?xml version="1.0" encoding="utf-8"?>
<com.my.package.SquareFrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="center">

    //<!--Views..-->

</com.my.package.SquareFrameLayout>


text:
Q: SQL Server 2008 + expensive union all We have 5 tables over which we should query with user search input throughout a stored procedure. We do a union all of the similar data inside a view. Because of this the view can not be materialized. We are not able to change these 5 tables drastically (like creating a 6th table that contains the similar data of the 5 tables and reference that new one from the 5 tables).
The query is rather expensive / slow
What are our other options? It's allowed to think outside the box. Unfortunately I cannot give more information like the table/view/SP definition because of customer confidentiality...

A: UNION ALL is literally one of the cheapest operations that exists in SQL Server.  It simply takes the result sets from each candidate query and concatenates the results.  UNION is different, it needs to perform a DISTINCT sort, but if you are using UNION ALL then I can guarantee you that the concatenation itself is not the problem.
There are a few reasons why your query might be performing poorly:

*

*The underlying queries being concatenated are inefficient, due to poor indexing or other factors.  Post the execution plan.

*You're applying the UNION ALL before the predicates, i.e. assuming that UNION ALL obeys the distributive law (it doesn't).  This turns a simple post-concatenation into a table concatenation and very expensive table scan.

*The plan itself is not slow, but you are selecting a huge number of results.  If so, then there's not much you can do other than to try to limit the result size (normalize?).
Edit - I just reread the question and noticed this line:

We do a union all of the similar data inside a view

The problem is definitely #2 - what you're essentially doing is concatenating the entire tables and then applying predicates, which destroys any chance the optimizer might have had of effectively using any indexes on the underlying tables.  Every query will end up as 5 expensive table scans.
The only way you're going to solve this is by either materializing the view (which you say you can't do) or getting rid of it and substituting a stored procedure or UDF.  You need to treat individual tables individually for best performance; concatenating them all together and trying to query against the concatenated results will always be (very) slow.

A: Try changing the UNION to UNION ALL
UNION is more expensive than UNION ALL because it will remove duplicates
Also do you have indexes on those columns and are the queries that you are writing SARGable, if you for example have to look in the middle of a column then indexes won't be used

A: You need to classify your tables in order of importance and level.  You start with your basic table and you build on top of that.
Depending on the size of the other tables, and they information they pertain you join them differently.  The order in which you join also matters.
If you could please post a little more about your tables, what they contain, how they are used etc, I would be able to give u an example.
More specifically, do all 5 tables contain the same information, and u join them, to query a 'super set' of data? or are they 5 tables with various attributes that together make a resultset that you need?

A: It all depends a bit on the way you query the view, and what kind of data is in there
=> do the 5 tables contain 'separate' data, or is there overlap that needs to be removed again from the end-result ? (if there is no overlap, make sure to use UNION ALL)
Assuming you query the view using WHERE statements :

*

*Assuming the queries are 'predictable', make sure to have proper indexes

*If there is no overlap between the tables, are there fields that clearly distinguish what data comes from which table ? You might want to add CHECK constraints on said tables and try to make the view act like an "old-school" partitioned view. (see here)
And as always, make sure statistics are up-to-date, run a manual update after big (or many) changes to a table (simply running sp_updatestats now end then never hurts IMHO) !


text:
Q: WSDL auto generated with a complex node does not match service request I have this WSDL,
     <s:element name="IncidentCreated">
        <s:complexType>
          <s:sequence>
            <s:element minOccurs="1" maxOccurs="1" name="IncidentCreatedStc" type="tns:IncidentCreatedStc" />
          </s:sequence>
        </s:complexType>
      </s:element>
      <s:complexType name="IncidentCreatedStc">
        <s:sequence>
          <s:element minOccurs="1" maxOccurs="1" name="CreationDate" type="s:dateTime" />
          <s:element minOccurs="1" maxOccurs="1" name="DangerFlag" nillable="true" type="s:int" />
          <s:element minOccurs="1" maxOccurs="1" name="DeadDeviceAlias" nillable="true" type="s:string" />
        </s:sequence>
      </s:complexType>

And I auto generate the service reference (WSDL) in c#  and it look like this:
<wsdl:definitions targetNamespace="ENMAC/TCS" xmlns:s="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://schemas.xmlsoap.org/wsdl/soap12/" xmlns:http="http://schemas.xmlsoap.org/wsdl/http/" xmlns:mime="http://schemas.xmlsoap.org/wsdl/mime/" xmlns:tns="ENMAC/TCS" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tm="http://microsoft.com/wsdl/mime/textMatching/" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/">
<wsdl:types>
<s:schema elementFormDefault="qualified" targetNamespace="ENMAC/TCS">
<s:element name="IncidentCreated">
<s:complexType>
<s:sequence>
<s:element minOccurs="0" maxOccurs="1" name="CreationDate" type="s:string"/>
<s:element minOccurs="1" maxOccurs="1" name="DangerFlag" nillable="true" type="s:int"/>
<s:element minOccurs="0" maxOccurs="1" name="DeadDeviceAlias" type="s:string"/>
</s:sequence>
</s:complexType>
</s:element>

The node IncidentCreatedStc never got created, what I actually wouldn't think it would anyway, the problem is that when I receive the XML from the service it look like
<IncidentCreated>
    <IncidentCreatedStr>
        <CreationDate></CreationDate>
        <DangerFlag></DangerFlag>
        <DeadDeviceAlias></DeadDeviceAlias>
    </IncidentCreatedStr>
</IncidentCreated>

My question is how do I make my soap service conform to this last format?


text:
Q: My program is not executing I am trying to draw to a square on python 2.7.13 and after writing a code. I am trying to run it it always take me to shell page and displays "restart- destination of the file"?
This is my code:
 import turtle
 def draw_square():
    window = turtle.screen()
    screen.bgcolor("red")
    brad = turtle.Turtle()
    brad.forward(100)
    window.exitonclick()

 draw_square()

This is what I am getting after execution

========================= RESTART: C:/Python27/a.py =========================

A: The "screen" method is "Screen" with capital S. To draw a square:
import turtle
def draw_square():
    window = turtle.Screen()
    window.bgcolor("red")
    brad = turtle.Turtle()
    brad.forward(100)
    brad.left(90)
    brad.forward(100)
    brad.left(90)
    brad.forward(100)
    brad.left(90)
    brad.forward(100)
    brad.left(90)
    window.exitonclick()

draw_square()

A: I assume you're running it from IDLE or something similar as that gives me the "=== RESTART ===" output. Your program does not run properly for me, but this one does (capital 'S' in Screen):
import turtle

def draw_square():
    window = turtle.Screen()
    window.bgcolor("red")
    brad = turtle.Turtle()
    brad.forward(100)
    window.exitonclick()

draw_square()

Do you get some red error messages in the shell starting like "Traceback..." perhaps?


text:
Q: Creating Tables with R using multiple Variables (List-Solution) I've been handling a dataset with six items, which I need to refer to back to back over my whole analysis. I'm quite novice in R, and until now I just copy'n'pasted all my code six times and changed the variable names.
I know that in STATA you can do 'foreach'-loops using lists and just set a placeholder in your code everytime the items on the list should be inserted. I've tried to recreate something like this with R using the 'for'-loop, failed, and went on the internet. After hours of searching all I really got was "Don't produce zombie-code, use lists" :)
So I began reading tutorials and other material about lists and the lapply()-function, but I can't really get behind how to do what I want to do with it.
Here's an example of what I want to do:
t_var1 <- table ( mydata$var1, mydata$constant ) #crosstable
p_var1 <- round ( prop.table ( crosstable ) *100, 1 ) #proptable

Something like this I would like to do for variables 1 to 6.
My last try with 'for'-loop looked like this (example for crosstable):
varlist <- c("var1", "var2", "var3", "var4", "var5", "var6")
for (var in 1:6){
    eval(parse(text=paste("t_", varlist[[var]],sep=""))) <- table (eval(parse(text=paste("mydata$", varlist[[var]],sep=""))), mydata$constant) }

I also tried that one just with paste() (w/o eval(parse)), with get() and with 'varlist' as list(). Either way, it produces error messages. And considering that the whole internet tells me to use lists and apply-functions, I tend to believe i should.
I already understood that lists can contain elements of different classes, so you can more or less fill them with anything you like. I think I also understand how to use [] and [[]] to refer to single items of lists. Unfortunately, all the tutorials and examples I've read so far use lapply() for functions like mean or summary. So what I ask is an example of how to create multiple tables with different input- and output-names (which of course could be put into the same list) using lists and the correct apply-function to get on with my understanding.
Thank you in advance for your help! If any further information is needed, just comment and I will try to provide.
Best Regards,
Leo

A: You can use the values of your string vector varlist in the for-loop:
attach(mydata)
crosstables<-list(NULL)
for(i in varlist)
 {crosstables[[i]]<-table(get(i),constant)}
crosstables

I hope I understood and this is helping.
Edit: A nicer approach, using lapply():
lapply(mydata[1:6],table,mydata$constant)

A: I'm not sure if I understood your question correctly, but does this help?
# Creating example data
my.data <- matrix(rnorm(40,mean=1),ncol=4)
my.data2<- matrix(jitter(rbinom(20, 10, 0.7)),ncol=2)

# producing variable names
number.of.var <- dim(my.data)[2]
var.names <- c()
for (i in 1:number.of.var) {
  var.names <- c(var.names, paste("var",i, sep="_"))
}
var.names

# save data to a list
new.list <- list()
for (col in 1:number.of.var) {
  new.list[[col]] <- my.data[,col]
}
# name list elements
names(new.list) <- var.names

# add other table
new.list[5] <- list(my.data2)
names(new.list)[5] <- "last.not.least"

# watch at content of list
str(new.list)

# create new list with percentage data
new.list.percentage <- lapply(new.list,
                              function(x) {
                                return(x*100)
                              }
)

# You can also access the elements of the list with a for-loop directly:
par(mfrow=c(2,3))
for (element.in.list in new.list) {
  plot(element.in.list)
}

I'm sure this is far from optimal and quite soon someone with more profound knowledge will answer, but maybe it helps a bit. Sorry if I did not understand correctly your question.
Edit: Added a second table so that you can see that list can have different dimensioned elements. You can access them directly (see plot loop), though for the last element it does not make much sense.


text:
Q: How can I implement this register file Verilog module This is the module I have been provided, I need to design a register file module using this format.
module RegisterFile(ReadRegister1, ReadRegister2, WriteRegister, WriteData, RegWrite,
Clk, ReadData1, ReadData2);
  input [4:0] ReadRegister1, ReadRegister2; // Two registers to be read
  input [4:0] WriteRegister; // Register address to write into
  input [31:0] WriteData; // Data to be written into WriteRegister
  input RegWrite; // RegWrite control signal. Data is written only when this signal is enabled
  input Clk; // very important!
  output [31:0] ReadData1, ReadData2;

I understand that the two read registers and the write register are the register numbers according to MIPS. However, I'm not sure exactly what the write data and read datas are supposed to be and why they are 32 bits long. Also, I'm assuming data is always read on posedge clk but only written when regwrite is true.
Are write data and the read datas supposed to be each of the 32 registers in MIPS? I am thinking this because a hint we are provided with is that we can use two-dimensional arrays within verilog. If this is the case how can I implement this? If not what is the purpose of the write data and read data arrays?

A: If you're confused about why some of these are 32 bits in width, then start with a review of what the MIPS registers are, and what the register block does.
The registers on MIPS are 32-bits wide.  There are 32 of them, with the caveat that the 0th register must be designed so that it always reads as the value zero.
The register block provides the storage for and access to values held by the MIPS registers.
During instruction decode, the register numbers — two 5 bit fields — from the fetched instruction are feed into the register block, so that the register block will output the 32-bit values held in those register numbers.  Those outputs connect to the ALU, which takes two 32-bit inputs, so it might do a 32-bit add or something else.
During writeback the register block captures whatever value is on WriteData, and puts that into the register identified by WriteRegister — when RegWrite is asserted.  (Later when the machine code program reads that register, the most recent value written to that register will be output.)
So, register names (numbers) are 5 bits wide and datapath values are 32-bits wide.
What you need to do is implement the above description:  Create a 32 element array, whose elements are each 32 bits in width.  Retrieve the values needed for output from the array given the register numbers, and store the given value in the given register on write.
Also, make sure the 0 register always reads as the value 0.
And further, if there's a write operation, the circuit should allow forwarding that new value to the output(s) rather than forwarding a stale value from the registers array.


text:
Q: Loading NDIS drivers automatically on Windows Embedded CE 6.0 during boot time I have a Wi-Fi driver from a manufacturer. That driver has Plug and Play support. After the adapter has been inserted or removed, Windows CE has recognized it successfully. But at boot time, if the adapter is "inserted state", CE OS does not load it so I must remove then insert it.
I want to load the driver automatically during boot time. Is it possible?
Before, I've written a simple stream interface driver. I have edited project.reg to create a sub-key under HKLM\Devices\BuiltIn so that Device Manager can load automatically during boot time. And it was successfully loaded. But Wi-Fi driver is a non-stream driver. Can Device Manager load Wi-Fi driver automatically with the same way?
Are "all of drivers under HKLM\Drivers\BuiltIn" stream interface drivers? What differences are there between stream interface drivers and NDIS Wi-Fi drivers from the point of loading automatically during boot-time? I will very happy if you can explain it a little.

A:
I want to load the driver automatically during boot time. Is it
  possible?

Yes, it is definitely possible. That was the main purpose of plug and play devices. The WinCE device automatically loads a driver appropriate to the Plug 'n' Play device. There would not be any need for doing it manually. If so, then there is no need for a Plug 'n' Play functionality.
As this is not happening in your case, you could try the following

*

*Have you checked with any other Plug-n-Play devices to the WinCE device?

*Each time you plug-out and plug-in, is it installing the drivers or is it just loading? You can verify the debug logs to confirm this.

Are "all of drivers under HKLM\Drivers\BuiltIn" stream interface drivers? What differences are there between stream interface drivers and NDIS Wi-Fi drivers from the point of loading automatically during boot-time?

Actually, the block devices can also be loaded automatically, as similar to stream interface drivers. The HKEY_LOCAL_MACHINE\Drivers\BuiltIn registry key recognizes built-in block devices also.
You can refer this msdn link for further information regarding loading the block devices.


text:
Q: quality standards not met
Possible Duplicate:
What can I do when getting "It does not meet our quality standards"?

I had a good question IMHO:
"I want to sign two dozen jar files using jarsigner, giving the password only once. Is this possible; if so, how?"
with two tags "jar-signing" and "applet" and a subject line "bulk-signing of jar files"
It was not accepted and I think it's a bug.

A: Your question seems to be too short and could be enhanced with more information about your situation.

*

*Your subject could be much clearer and possibly a Question Like "How do I sign a dozen jar-files with jarsigner"

*You could expand the question body with examples of what you tried and what you learned from the doc

*You should add the java tag

*Perhaps add extra information like "I would prefer a solution for the command line, but would be okay with ant/maven solution).

*Your operating system could be a vital information for finding a solution


text:
Q: How do I get my image to go in the center of the div? Given this HTML:

How do I get the image to go in the center of the div?
At the moment it is located in the top left of the div.
I tried
img#image
{
    text-align:center;
}

But it made no difference.

A: Try giving position relative to div:
#div_id{
  position:relative;
  width:400px;
  height:200px;
}

and this CSS for image:
#img_id{
  position:absolute;
  top:100px; /* half of parent div's height */
  left:200px;  /* half of parent div's width */
  display:block;
}

A: You need to set the text-align on the container like:

div.image {
   text-align: center;
}

More info here:
http://www.gtalbot.org/NvuSection/NvuWebDesignTips/HorizontalAlignment.html

A:

Will center the image within its container

A: CSS:
div { text-align: center; }
#image { display: inline-block; vertical-align: middle; }


text:
Q: How do I use text from a file as a variable name? How do I use text from a file as a variable name?
I am pulling values out of an excel file.
I am using xlrd and xlutils with python 3.
class employee(object):
def __init__(self, name):
    self.name = name
    emp_list.append(name)
def bulk_hours(self,sunday=0,monday=0,tuesday=0,wednesday=0,thursday=0,friday=0,saturday=0):
    self.sunday = sunday
    self.monday = monday
    self.tuesday = tuesday
    self.wednesday = wednesday
    self.thursday = thursday
    self.friday = friday
    self.saturday = saturday

I'm pulling employees out of a spreadsheet.
I'm trying to use their actual names.
I would love to know any working solution.
Thanks!
Edit: Pardon my ignorance regarding programming and my horrible post.
I'm trying to make a simple program that allows me to load an employees name and work schedule from Excel.
I will also make sure any edits are saved back into the spreadsheet.
The employees are labeled by their names. I'm trying to load their name as a variable so I can do:
John = employee('John')
John.bulk_hours(0,8,8,8,8,8,0)
Stacy = employee('Stacy')
print(John.monday)

I'm aiming to use their name as the variable I can use dot notation on.
Is this feasible? Is their some other way I should approach this?
def load(row):
employee2 = employee(s.cell(row, 0).value)
employee2.bulk_hours(s.cell(row, 1).value, s.cell(row, 2).value, s.cell(row, 3).value, s.cell(row, 4).value,
                     s.cell(row, 5).value, s.cell(row, 6).value, s.cell(row, 7).value)
print(employee2.saturday)

I'm trying to use a function like this to load multiple employees and their hours.
Could I use a list like this somehow?
worker = ['Joe']
worker[0] = employee('Joe')
worker[0].bulk_hours(0,8,8,8,8,8,0)
print(worker[0].monday)

Thank you for your valuable time.

A: Override __getattr__ to transparently access an internal dictionary.
class employee(object):
    def __init__(self, ...):
        self._internal_d = extract_data()  # replace extract_data with however you extract CSV values to a dictionary
        ...  # perform other initialization

    def __getattr__(self, name):
        try:
            return self._internal_d[name]
        except KeyError:
            raise AttributeError()

Optionally, you can implement __setattr__ to allow writing properties.
    def __setattr__(self, name, value):
        return self._internal_d[name] = value

Explanation: when python does variable assignment and can't find a variable name "normally", it checks if an object has __getattr__. If it does, it calls __getattr__ to get the value with the specified name. Thus, you can have dynamic variable names. Likewise for __setattr__.

A: You don't want to use variable names comming from the spreadsheet.
or one: variable names are internal to the running program, and are not meant to be exported again to an output file.
It is meaningless that the variable is bamed John to represent John's data when the program is running.  For example, let's suppose it would be possible to create a special markup to use teh variable name - say a ? prefix to fetch the name from another variable. Your example would be something like this:
def row_data(emp_name, *args):
    ?emp_name = employee(emp_name)
    ?emp_name.bulk_hours(*args)
    print(?emp_name.monday)

So, even if at runtime ?emp_name would be exchanged by the contents of the variable name, yur program would still look the same to someone reading the code.  So, it makes more sense to simply let the variable be named person or employee  or anything, since it can represent any employee (and in fact will, as you loop through the spreadsheet contents, usually the variable will carry the data about one person a time).
That said, there are times when we do want to have data in the program which do have programmatic labeling. but still on those cases - that is what dictionaries are for - create an employees dict, and fill it - and then you can have the names as the keys:
employees = dict()
def row_data(emp_name, name):
    person = employee(emp_name)
    person.bulk_hours(*args)
    employes[emp_name] = person

def print_employeers():
    for person_name, person_data in employees.items():
         print(person_name, person_data)

As you can see, it is possible to print all employees data without having to type in their names. Also, if it is an interactive program, it is possible to find the data related to a name that is input by the user, using it as the dictionary key.
However if you intend to have a program to generate other Python source files themselves, and end-up with a .py file for each employee. In that case just make use of a templating engine, like Jinja2,  or simply use str's format method. (It still hard to imagine why you would need such a thing).
And, just to have a complete answer, it is possible to create dynamic variable names in Python. However, you will be in the exact same situation I described in the first example here.
Global variables for any running code are kept in a regular Python dictionary, which is returned by a call to the globals() function. And similarly, values for local variables are kept in a dictionary that returned by a call to locals()  - although these do not behave nicely for variables known at compile time (in that case, the local variables are cached in the frame object, and the locals dict is only synchornized with them when it is read, but they can't be written via locals)
So:
def row_data(emp_name, *args):
    globals()[emp_name] = employee(emp_name)
    globals()[emp_name].bulk_hours(*args)
    print(globals()[emp_name].monday)

will work just as you asked - but it is easy to see it is useless.


text:
Q: Version number is not read from ConfigMap in this Nginx yaml deployment If I curl to the container: kubectl exec <my-nginx-> -- curl localhost:80
It displays no version number, just:

  <title>Welcome to my Nginx page</title>

Hello World!

This is version  of my site.

I'd expect to see the literal string ${VERSION} in the output.
Update:

I can see the environment variable is set using kubectl describe deployment my-nginx. Maybe it has something to do with reading
envoronment variable from HTML.

apiVersion: v1
kind: ConfigMap
metadata:
  name: my-configmap
data:
  index.html: |

      <title>Welcome to my Nginx page</title>

Hello World!

This is version ${VERSION} of my site.

  version: "1.0"
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: my-nginx
spec:
  selector:
    matchLabels:
      app: my-nginx
  replicas: 1
  template:
    metadata:
      labels:
        app: my-nginx
    spec:
      containers:
      - name: nginx
        image: nginx:latest
        env:
        - name: VERSION
          valueFrom:
            configMapKeyRef:
              name: my-configmap
              key: version
        ports:
        - containerPort: 80
        volumeMounts:
        - name: html
          mountPath: /usr/share/nginx/html
      volumes:
      - name: html
        configMap:
          name: my-configmap


text:
Q: Referring to the previous string in an array of strings I'm pretty new to Java and I'm having trouble with arrays. Here's the code I have right now.
String english = "hip-hop";
    String[] words = english.split ("[\\s+]|(?<=-)|(?=-)");
    String[] latin = new String [words.length];
    String phrase = "";

    for (int i = 0 ; i < words.length ; i++)
    {
        int k;
        k = words.length - 1;

         latin [i] = words [i]; //stays the same
        if ((words [i].charAt (0) == '-') || (words [k].equals("-") == true)) //PROBLEM RIGHT HERE
        {
            phrase = phrase + latin [i]; //add latin to previous phrase
        }
        else
        {
            phrase = phrase + " " + latin [i]; //add latin to previous phrase
        }
    }
    System.out.println (phrase);

So the output for this program is : hip- hop
The correct output should be: hip-hop
I know it may seem pointless to break hip-hop and then recombine it, but it's a small thing i need to get right for the pig latin translator I am creating.
The code here compiles correctly.
I created the int k so that if the previous word in the array is equal to "-", then when latin is added to the phrase, no space will be present.
Any help is greatly appreciated, thanks.

A: You were never updating the value of k so the detection of the previous word being equal to - would never evaluate to true. Instead just use a variable to track the previous word like this.
String english = "hip-hop";
String[] words = english.split("[\\s+]|(?<=-)|(?=-)");
String[] latin = new String[words.length];
String phrase = "";

String previousWord = "";
for (int i = 0; i < words.length; i++) {
   latin[i] = words[i];
   if (words[i].equals("-") || previousWord.equals("-")) {
      phrase = phrase + latin[i];
   } else {
      phrase = phrase + " " + latin[i];
   }
   previousWord = words[i];
}

System.out.println(phrase);


text:
Q: If $M$ is an $R$-module, how can I show that the Eilenberg-Maclane spectrum $HM$ is an $HR$-module spectrum Let $R$ be a commutative ring with identity, and let $M$ be an $R$-module. I want to show that the Eilenberg-Maclane spectrum $HM$ is an $HR$-module spectrum. Specifically, I want to know how to construct the action of $HR$ on $HM$: $$HR \wedge HM \to HM$$
Here's something related which I believe I understand (please let me know if this is incorrect). Let $S$ be a commutative ring with identity. If we have an action of $S$ on $M$, $$f:S \to End(M)$$ $$x \mapsto f_x$$ then, by applying $H$ to each $f_x$, we get the maps $$Hf_x : HM \to HM$$ Hence, we get an action of $S$ on $HM$. But doing the same thing with the action of $R$ on $M$ clearly doesn't show that $HM$ is an $HR$-module spectrum. I'd appreciate any help you all can give.

A: Here you can find the definition of $HA$ for symmetric spectra (Example 1.14), the construction of the smash product $\wedge$ on the category $\mathcal S^\Sigma$ of symmetric spectra (Section I.5) and that $H$ defines a lax symmetric monoidal functor $$(\mathbf{Ab},\otimes)\rightarrow(\mathcal S^\Sigma,\wedge)$$
(Example 5.28). An $A$-module structure on $M$ is a group homomorphism $A\otimes M\rightarrow M$, so by applying $H$ we get the $HA$-module structure on $HM$ $$HA\wedge HM\rightarrow H(A\otimes M)\rightarrow HM$$


text:
Q: Difference in surface between particle size Not sure if this is allowed here, but I have a very basic question, I can't quite wrap my head around.
One glass has $1$kg of powder with particle size of $4$ microns. A second one is double, $8$ microns.
How much more surface area has the smaller grained powder and how does the relationship between particle size and surface are look? I know its not linear, but not sure if its close to exponential?
Meaning the $4$ micron powder doesn't have double the surface are, but many times more.
How do I calculate that and write down in simple terms?

A: Assuming that the particles are smooth surfaces, generally speaking the surface area will scale proportional to the square of the linear measurements. So if the diameter of the particles doubles, the surface area will quadruple; if the diameter increases by a factor of ten, the surface area will increase by a factor of one hundred, and so on.
You can prove this directly for simple shapes - for example, if we assume the particles are spherical with radius $R$ then their surface area is $4 \pi R^2$; if they're cubes with side length $R$ then their surface area is $6R^2$.
On the other hand, if the particles are better approximated as being of a fractal dimension $D$, which could be the case if they are very coarse and have lots of detail at a microscopic level, then the surface are will scale relative to $R^D$. $D$ will be a value between 2 and 3, so the scaling will be somewhere between the square and the cube of the particle size.


text:
Q: How to build only usb-storage.ko? How can I build usb-storage.ko module for a running kernel distro (ubuntu)
thanks for your response.

A: You need the kernel source and kernel configuration (just as for compiling the complete kernel).
To build only a single file, tell make about it:
make drivers/usb/storage/usb-storage.ko


text:
Q: Replace object in array with two objects I have an array of objects which contain an end and a start date. But the period between dates may straddle midnight. If they do I wish to replace the object with two objects, the first with the previous start date and an end date of midnight. The second with a start time of 00:00 the next day and end date of what it was previously.
So for example if the array contains an object such as this,
{
  "start": "2016-11-04 22:00",
  "end": "2016-11-05 03:00"
}

I want to replace that object with two objects,
{
  "start": "2016-11-04 22:00",
  "end": "2016-11-04 24:00"
},
{
  "start": "2016-11-05 00:00",
  "end": "2016-11-05 03:00"
}

Here is my attempt using data.push(). Clearly this is not the way to do it:
d3.json("data.json", function(data) {
  var parseTime = d3.timeParse("%Y-%m-%d %H:%M");
  data.forEach(function(d) {
    d.commence = parseTime(d.start);
    d.conclude = parseTime(d.end);
    if (d.commence.getDay() != d.conclude.getDay()) {
      midnight = d.commence.getFullYear() + "-" + d.commence.getMonth() + "-" + d.commence.getDay() + " 24:00";
      morning = d.conclude.getFullYear() + "-" + d.conclude.getMonth() + "-" + d.conclude.getDay() + " 00:00";
      data.push({
        "start": d.start,
        "end": midnight
      }, {
        "start": morning,
        "end": d.end
      })
    }
  });
...

So how can I add or remove an object as I am iterating through the array of objects?
The data starts like this,
[
  {
    "start": "2016-11-01 12:00",
    "end": "2016-11-01 22:00"
  },
  {
    "start": "2016-11-02 02:00",
    "end": "2016-11-02 18:00"
  },
  {
    "start": "2016-11-03 09:00",
    "end": "2016-11-03 12:00"
  },
  {
    "start": "2016-11-04 22:00",
    "end": "2016-11-05 03:00"
  },
  {
    "start": "2016-11-06 12:00",
    "end": "2016-11-06 23:00"
  }
]

And in the console I can see it ultimately looks like this,
[
  {
    "start": "2016-11-01 12:00",
    "end": "2016-11-01 22:00",
    "commence": "2016-11-01T12:00:00.000Z",
    "conclude": "2016-11-01T22:00:00.000Z"
  },
  {
    "start": "2016-11-02 02:00",
    "end": "2016-11-02 18:00",
    "commence": "2016-11-02T02:00:00.000Z",
    "conclude": "2016-11-02T18:00:00.000Z"
  },
  {
    "start": "2016-11-03 09:00",
    "end": "2016-11-03 12:00",
    "commence": "2016-11-03T09:00:00.000Z",
    "conclude": "2016-11-03T12:00:00.000Z"
  },
  {
    "start": "2016-11-04 22:00",
    "end": "2016-11-05 03:00",
    "commence": "2016-11-04T22:00:00.000Z",
    "conclude": "2016-11-05T03:00:00.000Z"
  },
  {
    "start": "2016-11-06 12:00",
    "end": "2016-11-06 23:00",
    "commence": "2016-11-06T12:00:00.000Z",
    "conclude": "2016-11-06T23:00:00.000Z"
  },
  {
    "start": "2016-11-04 22:00",
    "end": "2016-10-5 24:00"
  },
  {
    "start": "2016-10-6 00:00",
    "end": "2016-11-05 03:00"
  }
]

The full code is on github and a demo is running on gh-pages.
Any suggestions would be greatly appreciated,
Thanks

A: Here is a solution using the flatMap concept (functional programming):
Array.prototype.flatMap = function(lambda) {
  return Array.prototype.concat.apply([], this.map(lambda));
};

d3.json("data.json", function(data) {

  var parseTime = d3.timeParse("%Y-%m-%d %H:%M");
  var formatEndOfDay = d3.timeFormat("%Y-%m-%d 24:00");
  var formatStartOfDay = d3.timeFormat("%Y-%m-%d %H:%M");

  var result = data.flatMap( d => {
    var start = parseTime(d.start);
    var end = parseTime(d.end);
    if (start.getDay() == end.getDay())
      return [d];
    else {
      var firstPart = { "start": d.start, "end": formatEndOfDay(start) }
      var secondPart = { "start": formatStartOfDay(end.setHours(0)), "end": d.end }
      return [firstPart, secondPart];
    }
  });

  console.log(result);
});

Array.prototype.flatMap = function(lambda) {
  return Array.prototype.concat.apply([], this.map(lambda));
};

var data = [
  {
    "start": "2016-11-01 12:00",
    "end": "2016-11-01 22:00"
  },
  {
    "start": "2016-11-02 02:00",
    "end": "2016-11-02 18:00"
  },
  {
    "start": "2016-11-03 09:00",
    "end": "2016-11-03 12:00"
  },
  {
    "start": "2016-11-04 22:00",
    "end": "2016-11-05 03:00"
  },
  {
    "start": "2016-11-06 12:00",
    "end": "2016-11-06 23:00"
  }
];

var parseTime = d3.timeParse("%Y-%m-%d %H:%M");
var formatEndOfDay = d3.timeFormat("%Y-%m-%d 24:00");
var formatStartOfDay = d3.timeFormat("%Y-%m-%d %H:%M");

var result = data.flatMap( d => {
  var start = parseTime(d.start);
  var end = parseTime(d.end);
  if (start.getDay() == end.getDay())
    return [d];
  else {
    var firstPart = { "start": d.start, "end": formatEndOfDay(start) }
    var secondPart = { "start": formatStartOfDay(end.setHours(0)), "end": d.end }
    return [firstPart, secondPart];
  }
});

console.log(result);
<script src="https://d3js.org/d3.v4.min.js"></script>

As a reminder, here is an example of flatMap: each element of the list is transformed into multiple elements; and these sub-lists are then flattened to produce a list:

Array.prototype.flatMap = function(lambda) {
  return Array.prototype.concat.apply([], this.map(lambda));
};

console.log([1, 2, 3, 4].flatMap(d => d % 2 == 0 ? [d, d] : [d]))

Which translates in our case to going through each start/end element, and if an element has its start and end on the same day, then we transform it into a list of 1 element (itself); and if an element doesn't start and end on the same day, then we transform it in a list of 2 elements (first day / end day).

As javascript doesn't have a built-in implementation of flatMap, we can create one this way:
Array.prototype.flatMap = function(lambda) {
  return Array.prototype.concat.apply([], this.map(lambda));
};


text:
Q: Why did installing VS break Python scripts from running at Command Prompt? I'm using Python 3.7. I've installed a few packages using pip install. I usually run the scripts I've written directly from the command line, in the Windows Command Prompt.
The other day I installed Visual Studio 2019 Community Edition, mainly for coding C++ console apps. While installing, I noticed it has support for Python, so I checked the box to include the Python features of Visual Studio. I've done nothing further with respect to configuring VS.
Now, when I try to run my Python scripts from the command line, I get a ModuleNotFoundError. For example:
C:\Users\me\Python\MyScript.py
Traceback (most recent call last):
  File "C:\Users\me\Python\MyScript.py", line 25, in <module>
    import pyvisa.errors
ModuleNotFoundError: No module named 'pyvisa'

Here are the import statements at the top of my script:
# System imports
import sys
import os
import re
import argparse
from enum import Enum

# Third-party library imports
import pyvisa.errors
import pyvisa as visa

The library in question is still installed:
C:\Users\me\Python>pip show pyvisa
Name: PyVISA
Version: 1.10.1
Summary: Python VISA bindings for GPIB, RS232, TCPIP and USB instruments
Home-page: https://github.com/pyvisa/pyvisa
Author: Torsten Bronger, Gregor Thalhammer
Author-email: bronger@physik.rwth-aachen.de
License: MIT License
Location: c:\users\me\appdata\local\programs\python\python37-32\lib\site-packages
Requires:
Required-by:

My path and PYTHONPATH are:
Path=C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Windows\System32\OpenSSH\;C:\Users\me\AppData\Local\Programs\Python\Python37-32\Scripts\;C:\Users\me\AppData\Local\Programs\Python\Python37-32\;C:\Users\me\AppData\Local\Microsoft\WindowsApps;

PYTHONPATH=C:\Users\me\Python\pkg

Here is the sys.path:
    C:\Users\me\Python>python -m site
sys.path = [
    'C:\\Users\\me\\Python',
    'C:\\Users\\me\\Python\\pkg',
    'C:\\Users\\me\\AppData\\Local\\Programs\\Python\\Python37-32\\python37.zip',
    'C:\\Users\\me\\AppData\\Local\\Programs\\Python\\Python37-32\\DLLs',
    'C:\\Users\\me\\AppData\\Local\\Programs\\Python\\Python37-32\\lib',
    'C:\\Users\\me\\AppData\\Local\\Programs\\Python\\Python37-32',
    'C:\\Users\\me\\AppData\\Local\\Programs\\Python\\Python37-32\\lib\\site-packages',
    'C:\\Users\\me\\Python\\common',
    'C:\\Users\\me\\AppData\\Local\\Programs\\Python\\Python37-32\\lib\\site-packages\\win32',
    'C:\\Users\\me\\AppData\\Local\\Programs\\Python\\Python37-32\\lib\\site-packages\\win32\\lib',
    'C:\\Users\\me\\AppData\\Local\\Programs\\Python\\Python37-32\\lib\\site-p`enter code here`ackages\\Pythonwin',
]
USER_BASE: 'C:\\Users\\me\\AppData\\Roaming\\Python' (doesn't exist)
USER_SITE: 'C:\\Users\\me\\AppData\\Roaming\\Python\\Python37\\site-packages' (doesn't exist)
ENABLE_USER_SITE: True

I've read several of the top Google hits for ModuleNotFoundError, but a simple explanation is not to be found.
What is a straightforward solution to this?


text:
Q: Django URL dispatcher not working urls.py in project folder:
url('aaa', include('main_app.urls')),

urls.py in main_app folder:
url('aaa', views.index),

If I type /aaa in the address bar and press enter, it doesn't work. How do I make it work?
From my understanding, in the urls.py of the project folder, Django checks for a matching string in the urls.py of the main_app folder.
In both the project and main_app folders, it is 'aaa' yet it doesn't work?


text:
Q: C# How is my Bitmap using a different MemoryStream then the one specified? I am writing a handler that creates two bitmaps via two separate MemoryStreams and then returns one of those bitmaps as a ByteArrayContent response.
Unfortunately, regardless of which bitmap I choose to return, response is always the first bitmap.
For Example:

*

*stream1 is initialised from byteArray1. image1 is initialised from stream1.

*stream2 is initialised from byteArray2. image2 is initialised from stream2.

I then intialise finalImage from either image1 or image2. finalImage is then saved to a finalStream MemoryStream object.
finalStream is then returned as a byteArray.
Note 1: The above only returns image1. Even if finalImage is initialised using image2.
Note 2: If I remove all the code that relates to image1, image 2 is returned as expected.
Note 3: This block of code will ultimately be used to return both image1 and image2 as a combined image with the two side by side. Unfortunately it was only ever returning image1 so I've had to refactor the code so as to investigate further. Apologies for the mess.
Note 4: The data returned by GetTop5SuppliersChart is different and can be seen by the byte array length.
Note 5: I thought this might be a caching issue so I have tried loading the handler via incognito mode and via different browsers with no change in result.
The below code has been annotated with the stream lengths
HttpResponse r = context.Response;
r.ContentType = "image/png";

byte[] byteArray1 = GetTop5SuppliersChart(brokerPerformanceEmailInformation, false);
//byteArray1.length is 22919
byte[] byteArray2 = GetTop5SuppliersChart(brokerPerformanceEmailInformation, true);
//byteArray2.length is 22375

Bitmap image1 = null;
Bitmap image2 = null;
byte[] chartImage = null;
using (MemoryStream stream1 = new MemoryStream(byteArray1))
{
    //stream1.length is 22919
    image1 = new Bitmap(stream1);

    using (MemoryStream stream2 = new MemoryStream(byteArray2))
    {
        //stream2.length is 22375
        image2 = new Bitmap(stream2);

        using (MemoryStream finalStream = new MemoryStream())
        {
            var finalImage = new Bitmap(image2);
            finalImage.Save(finalStream, System.Drawing.Imaging.ImageFormat.Png);
            //finalStream.length is 127637

            byteArrayToReturn= finalStream.ToArray();
         }
     }
}
r.Write(new ByteArrayContent(byteArrayToReturn));

The GetTop5SuppliersGraphData method returns different data for both image1 and image2.
private byte[] GetTop5SuppliersChart(BrokerPerformanceEmailInformation emailInformation, bool showCurrentMonth)
{
    var graphData = GetTop5SuppliersGraphData(emailInformation, showCurrentMonth);

    var myChart = new System.Web.Helpers.Chart(chartwidth, chartHeight, GetPieTheme(false))
    .AddSeries(chartType: "pie",
      xValue: graphData.Series,
      yValues: graphData.Values).Write();

    var chartBytes = myChart.GetBytes();
    return chartBytes;
}

To summarise:
Regardless of what is used to create finalImage, byteArrayToReturn will always return image1.


text:
Q: Blockquote CSS styling The styling of blockquotes is somewhat sub-optimal

This is blockquoted

As you can see, there is some extra space at the bottom of the block quote. The reason is this:
blockquote {
  background-color: #EEEEEE;
  margin-bottom: 10px;
  padding: 10px 10px 1px;
}

p {
  clear: both;
  margin-bottom: 1em;
}

The margin-bottom of 1em is inconsistent with the blockquote's padding of 10px. Code blocks don't have that problem. Top and bottom padding are the same. The following style might help, but I cannot assess whether it would break something else
blockquote p {
  margin-bottom: 10px;
}


text:
Q: Why do my train_generator and val_generator produce the same picture? I set aside a validation split like below:
val_samples = 60
train_imgs = coco_imgs[:-val_samples]
train_masks = coco_masks[:-val_samples]
val_imgs = coco_imgs[-val_samples:]
val_masks = coco_masks[-val_samples:]

My train_imgs and val_imgs show different pictures:
fig, ax = plt.subplots(ncols =2, figsize = (10,3), sharex = True, sharey = True)
ax[0].imshow(train_imgs[14])
ax[1].imshow(val_imgs[14])

Then I write data generator function:
class DataGenerator(keras.utils.Sequence):
  def __init__(self, input_img, input_mask, image_size,
               augmentation, batch_size):
    self.image_size = img_size
    self.augmentation = augmentation
    self.batch_size = batch_size
    self.input_img = train_imgs
    self.input_mask = train_masks

  def __len__(self):
        return len(self.input_img) // self.batch_size

  def __getitem__(self, index):
     data_index_min = int(index*self.batch_size)
     data_index_max = int(min((index+1)*self.batch_size, len(self.input_img)))

     indexes = self.input_img[data_index_min:data_index_max]
     this_batch_size = len(indexes)

     X = np.empty((this_batch_size, self.image_size , self.image_size , 3), dtype=np.float32)
     y = np.empty((this_batch_size, self.image_size , self.image_size , self.nb_y_features), dtype=np.uint8)

     for i, sample_index in enumerate(indexes):
          X_sample = self.input_img[index * self.batch_size + i]
          y_sample = self.input_mask[index * self.batch_size + i]
          if self.augmentation is True:
              aug = transform(image = X_sample, mask = y_sample)
              img_aug = aug['image']
              mask_aug = aug['mask']
              X[i, ...] = img_aug/255
              y[i, ...] = mask_aug.reshape(self.image_size , self.image_size , self.nb_y_features).astype(np.uint8)
          else:
              pass
     return X, y

Here is my train_generator and val_generator.
train_generator = DataGenerator(input_img = train_imgs, input_mask = train_masks, image_size = img_size,
                                augmentation=True, batch_size = 5)
val_generator = DataGenerator(input_img = val_imgs, input_mask = val_masks, image_size = img_size,
                                augmentation=True, batch_size = 5)

They show the same picture with train_imgs.
for i in range(3):
  X_sample_temp, y_sample_temp = train_generator[2]
  fig, ax = plt.subplots(ncols=2)
  ax[0].imshow(X_sample_temp[4])
  ax[1].imshow(y_sample_temp[4,:,:,0])
  plt.show()

and
for i in range(3):
  X_sample_temp, y_sample_temp = val_generator[2]
  fig, ax = plt.subplots(ncols=2)
  ax[0].imshow(X_sample_temp[4])
  ax[1].imshow(y_sample_temp[4,:,:,0])
  plt.show()

I want val_generator produces same pictures with val_imgs, but I don't know how to fix it. I appreciate any inputs.

A: In __init__ you have hardcoded
    self.input_img  = train_imgs
    self.input_mask = train_masks

so all generators use the same train_imgs train_masks
but you should use parameters input_img and input_mask
    self.input_img  = input_img
    self.input_mask = input_mask

I'm not sure if it is not typo in self.image_size = img_size
because it should be self.image_size = image_size


text:
Q: easy_install lxml error on Redhat I have tried several ways to install lxml (actually I need to install Scrapy, which depend on lxml installed), easy_install, pip, build from source, but they didn't work out.
Now I use: STATIC_DEPS=true easy_install lxml. But got the following error:

/usr/bin/ld:
  /tmp/easy_install-mptFTT/lxml-3.0alpha2/build/tmp/libxml2/lib/libexslt.a(exslt.o):
  relocation R_X86_64_32 against `a local symbol' can not be used when
  making a shared object; recompile with -fPIC
  /tmp/easy_install-mptFTT/lxml-3.0alpha2/build/tmp/libxml2/lib/libexslt.a:
  could not read symbols: Bad value

Not sure what does the error mean. I use Python 2.7.3.

A: maybe you need to install libxml2-dev and libxslt-dev
in ubuntu do
sudo apt-get install libxml2-dev libxslt-dev


text:
Q: Using the predefined colors in .NET Surely this has been asked before but I am not finding the answer so...
I am changing the backColor in a tool strip with code. When I go into the GUI editor for the back color I am presented with pre-named colors. The color I am interested in is "System->Control"

When I try to specify this color in C# code the color "Control" does not exist:

How do I use the predefined colors presented in the GUI editor in my code?

A: Based on the clue from @MiscellaneousUser in the comments above the proper form appears to be:
public Color StatusStripColor => SystemColors.Control;


text:
Q: Are there efficent ways to do bidirectional dimensionality reduction? Are there any sensible techniques for dimensionality reduction, for example from 20 to 5 dimensions, and then being able (albeit with loss of data) go back from 5 to 20?
Algorithms like t-SNE, PCA, Gaussian Random Projection are great but as far as I can tell there's no easy way to (somewhat) consistently go back from the compressed lower-dimensional data to higher dimensional data.
I am specifically training GPs for candidate generation, and the GPs in question perform better when I am working in lower dimensions. In order to generate a candidate I need to be able to go from the trained model to a new point in the same dimensions as what I give it.
I use a small untrained Neural network (linear layer and and an activation function) that takes higher and outputs lower dimensional data. When I want to go back, I do gradient descent on the input of the net based on the output (which is the lower dimensional data I have).
This kind of works, but an untrained network is unlikely to be the best technique.

A: Independent component analysis could take you there: essentially the reverse of principal component analysis.


text:
Q: QWebPage - Getting a list of resources / Verifying page loaded with no errors I am loading a webpage in PySide. I want to be able to see if it has loaded successfully without errors. If I get an error, then I want to know about it.  I can not simply use the "success" parameter to the load finished signal, as it seems to always indicate success. The only way I know how to do it, is to do something like this:
class WebPageResourceTracker(
    PySide.QtCore.QObject
):
    def __init__(self, url):
        PySide.QtCore.QObject.__init__(self)
        self.page = PySide.QtWebKit.QWebPage()
        self.frame = self.page.currentFrame()

        # The reason for the lambda is that otherwise I get this:
        #ASSERT: "self" in file /var/tmp/portage/dev-python/pyside-1.1.0/work/pyside-qt4.7+1.1.0/libpyside/signalmanager.cpp, line 534
        self.frame.loadFinished.connect(lambda ok: self.onLoadFinished(ok))
        self.page.networkAccessManager().finished.connect(lambda reply: self.onResourceFinished(reply))

        self.frame.setUrl(
            PySide.QtCore.QUrl(
                url,
            )
        )

    def onLoadFinished(self, ok):
        print 'onLoadFinished', ok

    def onResourceFinished(self, reply):
        print 'onResourceFinished', reply.url().toString(), reply.error()

import sys
from PySide import QtGui

app = QtGui.QApplication(sys.argv)
#WebPageResourceTracker("http://google.com")
WebPageResourceTracker(
    "http://migration.tanagerproductions.com/broken.html"
)
sys.exit(app.exec_())

But, I would imagine there would be a way to directly access a list of resources for the page, because the webkit inspector, can list off resources...
Bonus: I would also like to know if there is any JavaScript errors in the page, how would I do this?

A: One way to do this would be to first create a new class inheriting from QNetworkManager that overrides QNetworkAccessManager::createRequest. In your createRequest function you would first call the base/super class to get the request, then connect to the QNetworkReply::error signal or QNetworkReply::finished and check the QNetworkReply::error function.
You then set this custom QNetworkAccessManager on the QWebPage with QWebPage::setNetworkAccessManager.
To intercept JavaScript messages, you create a new class inheriting from QWebPage that overrides QWebPage::javaScriptConsoleMessage. Any errors or calls to console.log will be passed to this function:

This function is called whenever a JavaScript program tries to print a message to the web browser's console.
  For example in case of evaluation errors the source URL may be provided in sourceID as well as the lineNumber.

Note: This answer assumes that PySide provides the full Qt API, I haven't actually checked this is possible in Python, but it's the way I've previously done similar things in C++.


text:
Q: Alter the color of table-row on hover when color set I have an http table created dynamically by the server from data from a database. Depending on some values, the server sets the table row style="background-color:#RRGGBB". This value is from a string in the database, so CSS is not an option.
This all works nice and well, but this overrides the CSS which sets the background-color for hovering on a table row.
In this case, how do I change the color of the table row on hover, perferably while maintaining some resemblance to the color from the database?

table tr:nth-child(2n):hover {
  background-color: silver;
}

table tr:nth-child(2n+1):hover {
  background-color: gray;
}

table tr:nth-child(2n) {
  background-color: #DDDDEE;
}

table tr:nth-child(2n+1) {
  background-color: #CCCCDD;
}

    Line1

    Line2

    Line3

    Line4 - With color, no hover effect

    Line5 - With color, no hover effect

    Line6

    Line7

    Line8

A: You can apply a partially-transparent box-shadow to each element on hover.

table tr:hover {
    box-shadow: inset 0 0 0 99999px rgba(0,0,0,0.2);;
}

table tr:nth-child(2n) {
  background-color: #DDDDEE;
}

table tr:nth-child(2n+1) {
  background-color: #CCCCDD;
}

    Line1

    Line2

    Line3

    Line4 - With color, no hover effect

    Line5 - With color, no hover effect

    Line6

    Line7

    Line8

A: you can use onMouseOver and onMouseOut events to hover.
onMouseOver="this.style.backgroundColor='grey'"
onMouseOut="this.style.backgroundColor='#FFDDDD'"

table tr:nth-child(2n):hover {
  background-color: silver;
}

table tr:nth-child(2n+1):hover {
  background-color: gray;
}

table tr:nth-child(2n) {
  background-color: #DDDDEE;
}

table tr:nth-child(2n+1) {
  background-color: #CCCCDD;
}

    Line1

    Line2

    Line3

    Line4 - With color, no hover effect

    Line5 - With color, no hover effect

    Line6

    Line7

    Line8

A: Just add td in your hover

table tr:nth-child(2n) td:hover {
  background-color: silver;
}

table tr:nth-child(2n+1) td:hover {
  background-color: gray;
}

table tr:nth-child(2n) {
  background-color: #DDDDEE;
}

table tr:nth-child(2n+1) {
  background-color: #CCCCDD;
}

    Line1

    Line2

    Line3

    Line4 - With color, no hover effect

    Line5 - With color, no hover effect

    Line6

    Line7

    Line8


text:
Q: ssh to a qemu virtual machine guest without typing in the password Now I want to run a script from a client machine which will ssh to a virtual machine guest on a host machine and start to run a shell command. I do not want to be prompted to input the password.
So firstly I try to do it to connect to the host. I copy the file id_rsa.pub in the .ssh folder from the client to the host's file called authorized_keys in the .ssh folder. Then when I
"ssh root@hostname"
It works fine and I do not need to input the password(note my client's account is not root).
Then I try the same thing to the virtual machine guest in the host. I copied the same file to the guest. I started the guest  using qemu with option "-net user,vlan=0,hostfwd=tcp::5555-:22 " which will forward the requests to host 5555 port to guest's 22 port. Then in the client, I executed
" ssh -p 5555 root@hostname "
It fails. It shows that RSA key for the host has changed or something... Note that my guest's account is also root and I can use Putty to ssh to the guest by  connecting to the  5555 port of the host. And I believe the file permission is also properly handled.
Does anyone have a clue :>

A: Yes, this is correct behavior.
When you get connected to the host system first time, the ssh at your client machine ask you if the machine with fingerprint bla-bla-bla really the one you are  wanted to connect. You replied 'yes' and ssh at your client machine memorized the host name, IP and the fingerprint in the file ~/.ssh/known_hosts. Then during all subsequent connections it verifies that the fingerprint is not changed as a change is an indication that the authentication process requires your attention. There could be a few valid reasons of a mismatch:

*

*you re-installed sshd at the remote host;

*your host uses DHCP to get its IP and the IP got changed.

The case when you know precisely that the fingerprint should not change indicates to you an attempt to make you get into another system.
This mechanism aimed to make you sure that you are logged in to the system you are expected to log in.
In your case you first log into the system at IP a.b.c.d at port 22. Then you try to log in with the same IP a.b.c.d at port 5555. There is your VM behind this port that is having different fingerprint. So ssh complains.
The solution for your problem will be to log in to the host system and then from this remote shell session into VM. Also I would recommend you to generate another pair of public/private keys for this 'remote' connection. Thus when your private key kept at the host get compromised then your private key that is kept at your workstation remains valid.


text:
Q: link to popup compare list in magento I want to add a link to show the compare list.
The list should open in a smaler kind of popup.
The following link i have copy from top.phtml an edit it an put it into the header-template.
<a id="btccart" title="<?php echo Mage::helper('cartpro')->__('View Comparison');?>" href="javascript:void('0')" onclick="$('confirmbox').innerHTML='';$('fancybox-wrap-clone').setStyle({display:'none'});$('options').setStyle({display:'none'});'+strclick+'"><?php echo Mage::helper('cartpro')->__('View Comparison');?>

But the link wont work - what did i wrong?

A: i find it out and i use the following link, for me it works fine.
<a data-original-title="<?php echo Mage::helper('cartpro')->__('View Comparison');?>" data-toggle="tooltip" data-placement="bottom" id="btccart" title="<?php echo Mage::helper('cartpro')->__('View Comparison');?>" href="javascript:void('0')" onclick="$('confirmbox').innerHTML='';$('fancybox-wrap-clone').setStyle({display:'none'});$('options').setStyle({display:'none'});popWin('http://www.domain.com/catalog/product_compare/index/,,/','compare','top:0,left:0,width=820,height=600,resizable=yes,scrollbars=yes')" class="btn-vergleich">


text:
Q: C Warning "format '%d' expects argument of type 'int *', but argument 2 has type 'int" I want to fill up these arrays with a string and some numbers, but can't really seem to figure out why I cannot.
#include <stdio.h>

struct students{
char name[30];
int points[10];
int absences[10];
};

int main()
{
int i, n;
printf("Declare the number of students: ");
scanf("%d", &n);

struct students stud[n];

for (i = 0; i < n; i++) {
    printf("Name: ");
    scanf("%s", &stud[i].name);
    printf("Points: ");
    scanf("%d", &stud[i].points);
    printf("Absences: ");
    scanf("%d", &stud[i].absences);
}

for( i = 0; i < n; i++)
{
    printf("%s\n", stud[i].name);
    printf("%d\n", stud[i].points);
    printf("%d\n", stud[i].absences);

}

}

This is the warning i get:
warning: format '%s' expects argument of type 'char ', but argument 2 has type 'char ()[30]' [-Wformat=]
     scanf("%s", &stud[i].name);

feladat1.c:21:15: warning: format '%d' expects argument of type 'int ', but argument 2 has type 'int ()[10]' [-Wformat=]
     scanf("%d", &stud[i].points);

feladat1.c:23:15: warning: format '%d' expects argument of type 'int ', but argument 2 has type 'int ()[10]' [-Wformat=]
     scanf("%d", &stud[i].absences);

feladat1.c:30:16: warning: format '%d' expects argument of type 'int', but argument 2 has type 'int *' [-Wformat=]
     printf("%d\n", stud[i].points);

feladat1.c:31:16: warning: format '%d' expects argument of type 'int', but argument 2 has type 'int *' [-Wformat=]
     printf("%d\n", stud[i].absences);

A: *

*In struct students, int points[10]; should be int points;, int absences[10]; should be int absences;

*The line scanf("%s", &stud[i].name); should be scanf("%s", stud[i].name);
The follow code could work:
#include <stdio.h>
#include <stdlib.h>

struct students{
    char name[30];
    int points;
    int absences;
};

int main()
{
    int i, n;
    printf("Declare the number of students: ");
    scanf("%d", &n);

    struct students *stud = malloc(sizeof(struct students) * n);

    for (i = 0; i < n; i++) {
        printf("Name: ");
        scanf("%s", stud[i].name);
        printf("Points: ");
        scanf("%d", &stud[i].points);
        printf("Absences: ");
        scanf("%d", &stud[i].absences);
    }

    for( i = 0; i < n; i++)
    {
        printf("%s\n", stud[i].name);
        printf("%d\n", stud[i].points);
        printf("%d\n", stud[i].absences);

    }
    return 0;
}


text:
Q: Hyperlink not showing correct route in href I've got the following route added to our route table:
       map.Route(new Route("Car/Delete/{id}",
            new RouteValueDictionary(new
            {
                controller = "Car",
                action = "Delete",
            }), new MvcRouteHandler()));

In my Car.cshtml I've got:
@Html.ActionLink("X", "Delete", "Car", @Model.Car.CarId, null)
But when the link renders, its href is set to the same url that I'm on (page I'm no) and not set to /Car/Delete/10 (10 is a carId).
Not sure why the hyperlink isn't showing the right route.

A: Bassam has answered your question already, so I won't add my identical version.
However, what you are doing is very bad practice (at least on the surface as I can't see your controller action). You are issuing a delete action via a HttpGet request on the URL, i.e.
http://www.mydomain.com/Car/Delete/10

this is gonna be asking for big trouble, unless you of course have a rather elegant '2nd level' HttpPost going on via a confirmation message from said get request.
i just wanna point this out as it's very dangerous looking.

A: try
@Html.ActionLink("X", "Delete", "Car", new { id = @Model.Car.CarId }, null)


text:
Q: Font to Image in SWT I want to draw single character with specified Font and transparent background to an SWT Image, later save it to file. I do it like this:
FontData fontData; // info about the font
char ch = 'a'; // character to draw

Display display = Display.getDefault();
TextLayout textLayout = new TextLayout(display);
textLayout.setAlignment(SWT.CENTER);
textLayout.setFont(font);
textLayout.setText("" + ch);
Rectangle r = textLayout.getBounds();
Image img = new Image(display, r.width, r.height);
GC gc = new GC(img);
textLayout.draw(gc, 0, 0);

The character is drawn but it gets white background.
I tried to solve it by setting transparentPixel to white color, this makes background transparent but character looks ugly.
I also tried to set alphaData of the Image with 0's (fully transparent) before drawing anything on it, but alphaData doesn't update after drawing anything on the Image, it stays transparent all the time.
How to draw character with transparent background on the Image?

A: Have u tried drawing to BufferedImage with TYPE_INT_ARGB?
Image fontImage= new BufferedImage(width,height,BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = fontImage.createGraphics();

//here u write ur code with g2d Graphics

g2d.drawImage(fontImage, 0, 0, null);
g2d.dispose();

A: You have to use an intermediary ImageData to enable transparency
TextLayout textLayout = new TextLayout(font.getDevice());
textLayout.setText(s);
textLayout.setFont(font);
Rectangle bounds = textLayout.getBounds();
PaletteData palette = new PaletteData(0xFF, 0xFF00, 0xFF0000);
ImageData imageData = new ImageData(bounds.width, bounds.height, 32, palette);
imageData.transparentPixel = palette.getPixel(font.getDevice().getSystemColor(SWT.COLOR_TRANSPARENT).getRGB());
for (int column = 0; column < imageData.width; column++) {
    for (int line = 0; line < imageData.height; line++) {
        imageData.setPixel(column, line, imageData.transparentPixel);
    }
}
Image image = new Image(font.getDevice(), imageData);
GC gc = new GC(image);
textLayout.draw(gc, 0, 0);
return image;


text:
Q: matlab's addpoints function stopped working, it says that I'm trying to use the script as a function I'm just trying to add points to an animated line like this:
f=figure('Visible','on','units','normalized','outerposition',[0 0 1 1],'Numbertitle','off','Name','test');
for i=1:2
    S(i)=subplot(2,1,i,'Parent',f);
    h(i)=animatedline(S(i),'color','b','marker','.');
end
i=1;x=[1 2];
for j=1:numel(h)
    addpoints(h(j),i,x(j));
end

But I get this error:
Attempt to execute SCRIPT addpoints as a function:
/usr/local/MATLAB/R2019b/toolbox/matlab/graphics/addpoints.m

Note that last time I used it it worked just fine...
BTW, I'm using matlab r2019b under ubuntu 18.04.
I went to matlab's install directory and find . -type f -name "addpoints.m" give me this:
./mcr/toolbox/matlab/graphics/addpoints.m
./toolbox/distcomp/array/+parallel/+internal/+array/@PlottableUsingGather/addpoints.m
./toolbox/matlab/graphics/addpoints.m

Of those 3, only the last one isn't empty and it's just a help file, no function there...
EDIT:
On matlab, which addpoints -all gives me:
/usr/local/MATLAB/R2019b/toolbox/matlab/graphics/addpoints.m
addpoints is a built-in method                                % matlab.graphics.animation.AnimatedLine method


text:
Q: why is a wget to http://graph.facebook.com resolving to my server's IP? This makes absolutely no sense and I spent 3 hours trying to figure this out. Suddenly all my scripts connecting to Facebook stopped working, so I tried to do this:
root@s01 [~]# wget http://graph.facebook.com
--2015-11-18 15:27:47--  http://graph.facebook.com/
Resolving graph.facebook.com... MY.SERVERS.IP
Connecting to graph.facebook.com|MY.SERVERS.IP|:80... connected.
HTTP request sent, awaiting response... 200 OK
Cookie coming from graph.facebook.com attempted to set domain to graph.facebook.com
Length: unspecified [text/html]
Saving to: `index.html.2'

    [ <=>                                                                                ] 85,752      --.-K/s   in 0s

2015-11-18 15:27:47 (397 MB/s) - `index.html.2' saved [85752]

root@s01 [~]#

Strangely, when I connect to graph.facebook.com, it shows my server's IP instead. And I also can't access it via lynx, I get the same problem.
When I do a nslookup however or a host I get the correct IP for the Facebook graph server. What is happening here?
root@s01 [~]# nslookup graph.facebook.com
Server:     8.8.8.8
Address:    8.8.8.8#53

Non-authoritative answer:
graph.facebook.com  canonical name = api.facebook.com.
api.facebook.com    canonical name = star.c10r.facebook.com.
Name:   star.c10r.facebook.com
Address: 31.13.70.1

root@s01 [~]# host graph.facebook.com
graph.facebook.com is an alias for api.facebook.com.
api.facebook.com is an alias for star.c10r.facebook.com.
star.c10r.facebook.com has address 31.13.70.1
star.c10r.facebook.com has IPv6 address 2a03:2880:f00d:1:face:b00c:0:1
star.c10r.facebook.com mail is handled by 10 msgin.vvv.facebook.com.
root@s01 [~]#


text:
Q: future builder keeps rebuilding on every setstate I am building an app which uses an api and I am using the future builder to fetch the data but the problem is when the state changes it rebuilds and I want to prevent this from happen.
Thanks,

A: try using this :
class Example extends StatefulWidget {
  @override
 _ExampleState createState() => _ExampleState();
}

class _ExampleState extends State<Example> {
 Future<response> future;

 @override
 void initState() {
   future = _asyncmethodCall();
   super.initState();
}

@override
Widget build(BuildContext context) {
return FutureBuilder(
  future: future,
  builder: (context, snapshot) {
    // create some layout here
  },
 );
 }

Future<someResponse> _asyncmethodCall() async {
 // async code here
 }
}

similar question: How to deal with unwanted widget build?


text:
Q: Checkbox inside a link behaves wrong when Bootstrap toggling is added There are three content blocks and I'd like to enable/disable them with the Bootstrap's data-* "tools". The control elements should be checkboxes. When a content block is displayed, its checkbox should be checked.
summary
The problem is, that the checkbox inside links are not working as expected (starting to change the state only after the second click), after adding the Bootstrap behavior to the wrapping a tags.
The code is here.
long version
So first of all I created the content blocks and the controls without functionality (and gave them some styles):

                    <input type="checkbox" checked autocomplete="off">
                    foo

                    <input type="checkbox" checked autocomplete="off">
                    bar

                    <input type="checkbox" checked autocomplete="off">
                    buz

foo

bar

buz

The checkboxes are behaving as expected. Now the actual functionality needs to be added. The the A tags were extended as follows:
...

    ...

    ...

    ...

...

Now the toggling is working. But the checkboxes are always checked. Well, after it I also extended the DIV wrapper around the control checkboxes:

Now the checkboxes are behaving ever stranger. On the first click the checkbox remains on (checked). An from the second click on the same checkbox the behavior becomes normal: the state gets changed on every click.
Is it a bug or am I doing something wrong?
How to get checkboxes inside links working correctly, when Bootstrap toggling is used?

A: I would keep the link and drop the form elements.
the checkbox can be drawn from a pseudo holding a checkmark or not.
here is the basic idea : https://jsfiddle.net/jsL3dx1w/7/

#filter-bar {
    margin: 0;
    padding: 0;
    white-space: nowrap;
    text-align: right;
}

#filter-bar * {
    box-sizing: border-box;
}

#filter-bar a,
#filter-bar a:hover {
    text-decoration: none;
}
a[data-toggle]:before {
  display:inline-block;
  content:'\2713';
  border:solid 1px white;
  box-shadow:inset 0 0 2px black, 0 0 1px black;
  line-height:0.6em;
  color:darkblue;
  width:0.8em;height:0.8em;
}
a[data-toggle].collapsed:before {content:''}
#filter-bar  {
    outline: none;
    border: 0;
    color: #ffffff;
}

#filter-bar  span{
    margin: 5px 5px 0 5px;
    outline: 0;
}

#filter-bar .btn:active,
#filter-bar .btn.active {
    outline: 0;
    -webkit-box-shadow: none;
    box-shadow: none;
}

#containerFoo,
#filter-bar #filterFoo {
    background: #f5a623;
}

#containerBar,
#filter-bar #filterBar {
    background: #50c14e;
}

#containerBuz,
#filter-bar #filterBuz {
    background: #d21f31;
}

.clear {
    float: none;
}

<link href="https://cdn.rawgit.com/twbs/bootstrap/v3.3.7/dist/css/bootstrap.css" rel="stylesheet"/>

            foo

            bar

            buz

foo

bar

buz

automatix wrote
I took your solution and edited it a bit. The principle is still the same, but implemented with glyphicons: http://jsfiddle.net/automatix/jsL3dx1w/41 .


text:
Q:   instead of
* in {% recursetree nodes %} I have this working:

    {% recursetree nodes %}

            {{ node.name }}
            {% if not node.is_leaf_node %}

                    {{ children }}

            {% endif %}

    {% endrecursetree %}

However, I need to display the tree inside a table tag so I want the items to be indented by spaces, not ul and li.
How can I do that?

A: The problem with a table will be, that you need to know how many cells the table will get - so you could use colspan="x" or something else within your child objects. So I guess that'll bring more trouble and overhead than needed.
Maybe you are only looking for some "table like" design...something like this?

If so, here's the code with default bootstrap3-css and some added css (tagged with i3):
html

{% recursetree service_items %}

                {{ node.name }}

            {% include 'service/_service_options.html' %}

        {% if not node.is_leaf_node %}

                {{ children }}

        {% endif %}

{% endrecursetree %}

css
.i3servicelist ul {list-style-type: none;}
.i3servicelist_element {border-bottom:1px solid #ddd;display:block;margin:0;padding: 8px;}


text:
Q: Cant copy elements of 2D array into another array using for loop What's wrong with this code?

let matrix1 = [
        [2, 7, 9, 2],
        [8, 0, 7, 1],
        [8, 8, 0, 8]
    ];

let arr = []; // or arr = [[]];

for (let i = 0; i < matrix1.length; i++) {
        for (let j = 0; j < matrix1[i].length; j++) {
            arr[i][j] = matrix1[i][j];
        }
    }

console.log(arr);

Error is:

Cannot set property '0' of undefined
This is when I try to assign the value of an element of matrix1 to the new array.
for loop works for the single dimensional array.

A: try this

   let matrix1 = [
    [2, 7, 9, 2],
    [8, 0, 7, 1],
    [8, 8, 0, 8]
];

let arr = []; // or arr = [[]];

for (let i = 0; i < matrix1.length; i++) {
    for (let j = 0; j < matrix1[i].length; j++) {
        if(!arr[i])
            arr[i] = []
        arr[i][j] = matrix1[i][j];
    }
}

if you want copy a 2d array without for loop try this one:

   let matrix1 = [
    [2, 7, 9, 2],
    [8, 0, 7, 1],
    [8, 8, 0, 8]
];
let arr = JSON.parse(JSON.stringify(matrix1))

A: You need to create a new sub array in the outer loop so that arr[i] is an array and not undefined

    let matrix1 = [
    [2, 7, 9, 2],
    [8, 0, 7, 1],
    [8, 8, 0, 8]
];

let arr = [];

for (let i = 0; i < matrix1.length; i++) {
    // push a new sub array to be populated in next loop
    arr.push([]);

    for (let j = 0; j < matrix1[i].length; j++) {
        arr[i][j] = matrix1[i][j];
    }
}

console.log(arr);

A: The problem is the line arr[i][j] = matrix1[i][j];, since arr[i][j] is undefined at this point.
The correct way of adding elements to an array is using the .push() function:

let matrix1 = [
  [2, 7, 9, 2],
  [8, 0, 7, 1],
  [8, 8, 0, 8]
];

let arr = [];

for (let i = 0; i < matrix1.length; i++) {

  arr.push([]);

  for (let j = 0; j < matrix1[i].length; j++) {
    arr[i].push(matrix1[i][j]);
  }
}

console.log(arr);

Also note that using JSON might achieve the same task in a simpler way:

let matrix1 = [
  [2, 7, 9, 2],
  [8, 0, 7, 1],
  [8, 8, 0, 8]
];

let arr = JSON.parse(JSON.stringify(matrix1))

console.log(arr)


text:
Q: JavaScript next div is revealed after selecting a yes/no checkbox I'm trying to make a quiz where each question gets revealed after the Yes/No checkbox is selected from the previous one, I've got this working to an extent, but if you select 'Yes' and then 'No' the second question wont reveal because the 'No' is triggering a toggle function to hide the question.
here is my code:

HTML

   <input type="checkbox" id="A1" name="q1" value="Yes"> Yes</input>

   <input type="checkbox" id="A1N" name="q1" value="No"> No</input>

   <input type="checkbox" name="q1r" value="Yes" id="Q1R"> Yes</input>

   <input type="checkbox" name="q1r" value="No"> No</input>

toggle

What is the solution to this? or have I maybe overcomplicated it?

A: Don't use .slideToggle() use .slideDown()

A: This is because slideToggle both hides and reveals elements whereas slideDown just reveals them


text:
Q: XCode 9 stop debugging and running application and giving error "The LLDB RPC server has crashed." The LLDB RPC server has crashed. The crash log is located in ~/Library/Logs/DiagnosticReports and has a prefix 'lldb-rpc-server'. Please file a bug and attach the most recent crash log.

A: Please have a look into LLDB CRASH
Uninstalling the Xcode and reinstalling it will undo it. Dont know if there is any other known solution as its a known bug of Xcode 8.2 beta and 8.3

A: I have found a solution for this, this may not be the perfect but kind a fix my problem.
Go to target Build Settings -> Other Swift Flags -> check Debug Values added Remove everything except $(inherited) and -DDEBUG
Remove Derived Data
Clean and Run
https://stackoverflow.com/a/63357101/2699432


text:
Q: Dynamically provide directory and file name to ftp outbound gateway We have a requirement for the FTP client to download a file whose name and directory is provided at run-time. So, the FTP client may be asked to download  file1.txt from foo1/foo2 directory path on the remote server.
We do have a solution using Spring Integration FTP outbound gateway. With this solution to make it dynamic:

*

*the ApplicationContext for the gateway is created

*the gateway properties get set using file name and remote directory path

*the file is downloaded

*the ApplicationContext is closed.

What we're not happy about is that the ApplicationContext is created and closed every time which obviously affects performance. Is there a way to dynamically pass the file name and the directory path to the gateway without reloading the Appplication Context every time?
Your help will be greatly appreciated.
Here's the main code and configuration:
package com.cvc.ipcdservice.ftp;

import java.util.List;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.StandardEnvironment;

public class DynamicFtpClient {
    private static final Logger LOGGER = LoggerFactory
            .getLogger(DynamicFtpClient.class);

    public void download(final FtpMetaData ftpMetaData) {
        final ConfigurableApplicationContext ctx = new ClassPathXmlApplicationContext(
                new String[] { "/META-INF/spring/integration/FtpOutboundGateway-context.xml" },
                false);

        setEnvironment(ctx, ftpMetaData);
        ctx.refresh();

        final ToFtpFlowGateway toFtpFlow = ctx.getBean(ToFtpFlowGateway.class);

        // execute the flow (mget to download from FTP server)
        final List<Boolean> downloadResults = toFtpFlow.mGetFiles("/");

        LOGGER.info(
                "Completed downloading from remote FTP server. ftpMetaData:{}, downloadResults.size:{} ",
                ftpMetaData, downloadResults.size());

        ctx.close();
    }

    /**
     * Populate {@code ConfigurableApplicationContext} with Provider-specific
     * FTP properties.
     *
     * @param ctx
     * @param customer
     */
    private void setEnvironment(final ConfigurableApplicationContext ctx,
            final FtpMetaData ftpMetaData) {
        final StandardEnvironment env = new StandardEnvironment();
        final Properties props = new Properties();
        // populate properties for customer
        props.setProperty("ftp.host", ftpMetaData.getHost());
        props.setProperty("ftp.port", ftpMetaData.getPort());
        props.setProperty("ftp.userid", ftpMetaData.getUserName());
        props.setProperty("ftp.password", ftpMetaData.getPassword());
        // props.setProperty("remote.directory", "/");
        // WARNING: the file name pattern has to be surrounded by single-quotes
        props.setProperty("ftp.remote.filename.pattern",
                "'" + ftpMetaData.getFileNamePattern() + "'");
        props.setProperty("ftp.local.dir", ftpMetaData.getLocalDirectory());

        final PropertiesPropertySource pps = new PropertiesPropertySource(
                "ftpprops", props);
        env.getPropertySources().addLast(pps);
        ctx.setEnvironment(env);
    }
}

 <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:int="http://www.springframework.org/schema/integration"
    xmlns:int-ftp="http://www.springframework.org/schema/integration/ftp"
    xsi:schemaLocation="http://www.springframework.org/schema/integration/ftp http://www.springframework.org/schema/integration/ftp/spring-integration-ftp.xsd
        http://www.springframework.org/schema/integration http://www.springframework.org/schema/integration/spring-integration.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <context:property-placeholder/>

    <int:gateway id="gw" service-interface="com.cvc.ipcdservice.ftp.ToFtpFlowGateway"
        default-request-channel="inbound"/>

    <bean id="ftpSessionFactory"
        class="org.springframework.integration.ftp.session.DefaultFtpSessionFactory">
        <property name="host" value="${ftp.host}"/>
        <property name="port" value="${ftp.port}"/>
        <property name="username" value="${ftp.userid}"/>
        <property name="password" value="${ftp.password}"/>
    </bean>

    <int-ftp:outbound-gateway id="gatewayGET"
        local-directory="${ftp.local.dir}"
        session-factory="ftpSessionFactory"
        request-channel="inbound"
        command="mget"
        command-options="-P"
        expression="${ftp.remote.filename.pattern}"/>

</beans>

A: There is no need to create the context for each request.
Instead of using a literal for the expression:
props.setProperty("ftp.remote.filename.pattern",
            "'" + ftpMetaData.getFileNamePattern() + "'");

Use an expression based on the request; e.g.
props.setProperty("ftp.remote.filename.pattern",
            "payload");

Then simply send the required path in your gateway call...
final List<Boolean> downloadResults = toFtpFlow.mGetFiles("/some/path/*.txt");


text:
Q: Moving back nodes with D3.js d3.selection.prototype.moveToBack = function() {
    return this.each(function() {
        var firstChild = this.parentNode.firstChild;
        if (firstChild) {
            this.parentNode.insertBefore(this, firstChild);
        }
    });
};

this is the function for moving back the nodes, so:
node.enter().append("g").moveToBack();

if I use it this way it will work, but:
node.exit().select("g").moveToBack();

the moveToBack is undefined, the question is which object should I prototype to make it work for the select("g") ???