Q: Script to position chart misaligns when sheet isn't active? I have a script that essentially renders/updates an entire page, including two charts on it. These charts are positioned dynamically using the .top property. I write my scripts intentionally independent of the users currently selected sheet, so there is no .Select or .Activate here.
This is the expected result, which works fine when the sheet is active:

Notice the Immediate window in the bottom-right. This debug shows the calculation that determined what each chart's .Top property is, which determines the vertical position.
The first (Spending) chart's .Top property:
Sheets("Overview").Shapes.Range(Array("Spending_Chart")).Top = _
        Sheets("Overview").Shapes.Range(Array("Add_Category_Button")).Top + 22

Debug.Print "1st:  " & _
        Sheets("Overview").Shapes.Range(Array("Add_Category_Button")).Top & _
        " + 22" & _
        " = " & _
        Sheets("Overview").Shapes.Range(Array("Spending_Chart")).Top
' Note: The Add_Category_Button.Top property is consistent and doesn't change.

The second (Income) chart's .Top property:
Sheets("Overview").Shapes.Range(Array("Earning_Chart")).Top _
        = Sheets("Overview").Shapes.Range(Array("Spending_Chart")).Top + _
            Sheets("Overview").Shapes.Range(Array("Spending_Chart")).Height

Debug.Print "2nd:  " & _
        Sheets("Overview").Shapes.Range(Array("Spending_Chart")).Top & _
        " + " & _
        Sheets("Overview").Shapes.Range(Array("Spending_Chart")).Height & _
        " = " & _
        Sheets("Overview").Shapes.Range(Array("Earning_Chart")).Top

The second chart's position is determined by the bottom (.Top + .Height) of the first chart. They stack directly on top of eachother.
However, when I run this script while on a different sheet, this is the result:

First chart aligns fine, but the second one is miscalculated.
My confusion is, looking at the debug, the values it retrieves to calculate the .Top are correct, but the result isn't.
Also, when I run this function on each sheet, they consistently deliver unique results per sheet:

One sheet even messed with the 1st chart calculation.
What part of my code is relying on the currently selected sheet? I don't see anything, so it may be some sort of Excel behavior I don't understand.
Edit
Here's the code used to place the Add_Category_Button shape, which is the only other context there is regarding positioning the charts. I don't see how this could be useful but it was requested.
Sheets("Overview").Shapes.Range(Array("Add_Category_Button")).Top = _
        Sheets("Overview").Range("B" & Functions.GetCategoryCount + _
        Functions.GetAccountCount + 6).Top + 4

The GetCategoryCount and GetAccountCount functions run a CountA worksheet function on a range inside of another sheet, and return that value. Throughout the screenshots provided, those numbers have been the same each time, so it wouldn't relate to the odd positioning issues.
Note: The CountA functions are ran without 'selecting' any other sheets or ranges, so the context of the VBA interpreter doesn't change.
Other than that information, none of the rest of the code relates to positioning the charts, so I don't see a reason to dump it here.

A: It looks like the two sheets in your example are at different zoom levels, theorizing this may be an excel bug:
Have you tried with the zoom levels set the same on the active sheet and the sheet containing the plot? If that works you could try getting the location of two vertically adjacent cells on both sheets and then using the difference of the .top values as the 'row height' on each sheet and using the ratio between the active sheet and the target plot's sheets row height as a conversion factor.
Another thought (an ugly kludge, since the row height difference is probably not accurate enough) is that you could turn application.screenupdating off (if it's not already 'false'), then create a plot on the active page and get its height and width, then compare that to the height and width of a new plot on the target sheet (and use that for the conversion factor).

A: I think it has something to do with not updating "graphically", try making the graph(s) invisible at the beginning of the code and visible again at the end:
With Sheets("Overview").ChartObjects("Spending_Chart")
    .Visible = False
    'Do all your stuff including setting the .Top
    .Visible = True
End With

A: Hard to say without more of your code. Your snippet works fine on my sample workbook. I don't think this is a code problem as much as an Excel/VBA bug you are hitting. More on that below.
One quick comment up front... I don't like your syntax of Shapes.Range(Array("Add_Category_Button")). I would prefer the shorter Shapes("Add_Category_Button") but both work the same for me.
Here is my test routine:
Sub my_test()
    Dim i As Integer

    For i = 1 To ThisWorkbook.Sheets.Count
        ThisWorkbook.Sheets(i).Activate

        Debug.Print ActiveSheet.Name
        Sheets("Overview").Shapes("Pie_Chart").Top = _
            Sheets("Overview").Shapes("Add_Category_Button").Top + 22

        Debug.Print "1st:  " & _
            Sheets("Overview").Shapes("Add_Category_Button").Top & _
            " + 22 = " & _
            Sheets("Overview").Shapes("Pie_Chart").Top

        Sheets("Overview").Shapes("Column_Chart").Top = _
            Sheets("Overview").Shapes("Pie_Chart").Top + _
            Sheets("Overview").Shapes("Pie_Chart").Height

        Debug.Print "2nd:  " & _
            Sheets("Overview").Shapes("Pie_Chart").Top & _
            " + " & _
            Sheets("Overview").Shapes("Pie_Chart").Height & _
            " = " & _
            Sheets("Overview").Shapes("Column_Chart").Top
    Next i
End Sub

And my result:
Overview
1st:  64 + 22 = 86
2nd:  86 + 216 = 302
Interval
1st:  64 + 22 = 86
2nd:  86 + 216 = 302
1-16 to 1-14
1st:  64 + 22 = 86
2nd:  86 + 216 = 302
1-17 to 1-15
1st:  64 + 22 = 86
2nd:  86 + 216 = 302
Control
1st:  64 + 22 = 86
2nd:  86 + 216 = 302

I tried using different view percentages and got consistent results, though the numbers above changed any time I altered the view percentage on the Overview sheet.
I did find I could create some wrong results if I had 2 windows of the same workbook open via View > New Window:
Interval
1st:  75.33331 + 22 = 114.6666
2nd:  114.6666 + 258.5001 = 445.3889
1-16 to 1-14
1st:  75.33331 + 22 = 114.6666
2nd:  114.6666 + 310.5001 = 508.9445
1-17 to 1-15
1st:  75.33331 + 22 = 114.6666
2nd:  114.6666 + 374.0557 = 584.0556
Control
1st:  75.33331 + 22 = 114.6666
2nd:  114.6666 + 449.1668 = 676.5002

In my case, I think the height of the chart was changing after setting the .top property. If you have more than one window or form open, I could imagine that you could have a similar issue. This was very finicky and hard to replicate, but I suspect it has to do with situations where .top was changed with different windows and view percentages involved. When I just had one window and no forms my results were solid.
In my file, the chart height and width seemed to be altered as well, and I was seeing issues where the chart rendered improperly (for example, the selection box was a different size than the chart as displayed, or part of the chart was truncated). This is why I think this may be a bug.
The rendering errors always reset when I reset the chart size, so maybe try also setting the height/width in your code?
    Sheets("Overview").Shapes("Add_Category_Button").Top = 58
    Sheets("Overview").Shapes("Add_Category_Button").Height = 22
    Sheets("Overview").Shapes("Pie_Chart").Height = 200
    Sheets("Overview").Shapes("Pie_Chart").Width = 300
    Sheets("Overview").Shapes("Column_Chart").Height = 200
    Sheets("Overview").Shapes("Column_Chart").Width = 300


Q: building PyMC3 model incorporating different measurements I am trying to incorporate different types and replicates of measurements into one model in PyMC3.
Consider the following model: P(t)=P0*exp(-kBt) where P(t), P0, and B are concentrations. k is a rate. We measure P(t) at different times and B once, all through counting of particles. k is the parameter of interest we are trying to infer.
My question has two parts:
(1) How to incorporate measurements on P(t) and B into one model?
(2) How to use a variable number of replicate experiments to inform on the value of k?
I think I can answer part (1), but am unsure about whether it is right or done in the right flavour. I failed to generalise the code to include a variable number of replicates.
For one experiment (one replicate):
ts=np.asarray([time0,time1,...])
counts=np.asarray([countforB,countforPattime0,countforPattime1,...])
basic_model = pm.Model()
with basic_model:
    k=pm.Uniform('k',0,20)
    B=pm.Uniform('B',0,1000)
    P=pm.Uniform('P',0,1000)
    exprate=pm.Deterministic('exprate',k*B)
    modelmu=pm.math.concatenate(B*(np.asarray([1.0]),P*pm.math.exp(-exprate*ts)))
    Y_obs=pm.Poisson('Y_obs',mu=modelmu,observed=counts))

I tried to include different replicates along the lines of the above, but to no avail:
...
    k=pm.Uniform('k',0,20) # same within replicates
    B=pm.Uniform('B',0,1000,shape=numrepl) # can vary between expts.
    P=pm.Uniform('P',0,1000,shape=numrepl) # can vary between expts.
    exprate=???
    modelmu=???

A: Multiple Observables
PyMC3 supports multiple observables, that is, you can add multiple RandomVariable objects to the graph with the observed argument set.
Single Trial
In your first case, this would lend some clarity to the model:
counts=[countforPattime0, countforPattime1, ...]

with pm.Model() as single_trial:
    # priors
    k = pm.Uniform('k', 0, 20)
    B = pm.Uniform('B', 0, 1000)
    P = pm.Uniform('P', 0, 1000)

    # transformed RVs
    rate = pm.Deterministic('exprate', k*B)
    mu = P*pm.math.exp(-rate*ts)

    # observations
    B_obs = pm.Poisson('B_obs', mu=B, observed=countforB)
    Y_obs = pm.Poisson('Y_obs', mu=mu, observed=counts)

Multiple Trials
With this additional flexibility, hopefully it makes the transition to multiple trials more obvious.  It should go something like:
B_cts = np.array(...) # shape (N, 1)
Y_cts = np.array(...) # shape (N, M)
ts = np.array(...)    # shape (1, M)

with pm.Model() as multi_trial:
    # priors
    k = pm.Uniform('k', 0, 20)
    B = pm.Uniform('B', 0, 1000, shape=B_cts.shape)
    P = pm.Uniform('P', 0, 1000, shape=B_cts.shape)

    # transformed RVs
    rate = pm.Deterministic('exprate', k*B)
    mu = P*pm.math.exp(-rate*ts)

    # observations
    B_obs = pm.Poisson('B_obs', mu=B, observed=B_cts)
    Y_obs = pm.Poisson('Y_obs', mu=mu, observed=Y_cts)

There might be some extra syntax stuff to get the matrices multiplying correctly, but this at least includes the correct shapes.

Priors
Once you get that setup working, it would be in your interest to reconsider the priors. I suspect you have more information about the typical values for those than is currently included, especially since this seems like a chemical or physical model.
For instance, right now the model says,

We believe the true value of B remains fixed for the duration of a trial, but across trials is a completely arbitrary value between 0 and 1000, and measuring it repeatedly within a trial would be Poisson distributed.

Typically, one should avoid truncations unless they are excluding meaningless values. Hence, a lower bound of 0 is fine, but the upper bounds are arbitrary.  I'd recommend having a look at the Stan Wiki on choosing priors.


Q: Many to many getting "is invalid" error in Rails I am trying to do a many-to-many relation but I get :roles=>[{:error=>:invalid}] when trying to save.
Models
class User < ApplicationRecord
  has_many :user_roles, dependent: :destroy
  has_many :roles, through: :user_roles
end

class Role < ApplicationRecord
  has_many :children, :class_name => "Admin::Role", foreign_key: "parent_id"
  belongs_to :parent, :class_name => "Admin::Role"
  has_many :user_roles, dependent: :destroy
  has_many :users, through: :user_roles
end

class Admin::UserRole < ApplicationRecord
  belongs_to :user
  belongs_to :role
end

Controller
def new
  @user = User.new
end

def create
  @user = User.new(user_params)
  respond_to do |format|
    if @user.save
      redirect_to users_url
    end
  end
end

def user_params
  params.require(:user).permit(:role_ids => [])
end

_form.html.erb
form_with(model: user) do |form|
    form.collection_select(:role_ids, Roles.all, :id, :title, multiple: "multiple")
end

Params log
"user"=>{"role_ids"=>["", "1"]}


Q: R: Data Quality Check: Zip Code matching the City Can someone help me to realize an idea in R?
I want to achieve, that when R gets an Input File with e.g. a list of companies and their address, it will check wether the zip Code fits to the City for each Company. I have a list of all cities and Zip codes from a certain Country. How can I implement the list into an if sentence?
Did someone Programm something similar before?
Thanks for ur help!
Sandra

A: Just a quick example of what one could do. It is, however, probably better to use fuzzy matching for your cities.
# City codes (all city codes can be found at https://www.allareacodes.com/)
my_city_codes <- data.frame(code = c(201:206),
                            cities = c("Jersey City, NJ", "District of Columbia", "Bridgeport, CT", "Manitoba", "Birmingham, AL", "Seattle, WA"),
                            stringsAsFactors = FALSE)

# Function for checking if city/city-code matches those in the registries
adress_checker <- function(adress, citycodes) {
  # Finding real city
  real_city <- my_city_codes$cities[which(adress$code == my_city_codes$code)]

  # Checking if cities are the same
  if(real_city == adress$city) {
    return("Correct city")
  } else {
    return("Incorrect city")
  }
}

# Adresses to check
right_city <- data.frame(code = 205, city = c("Birmingham, AL"), stringsAsFactors = FALSE)
wrong_city <- data.frame(code = 205, city = c("Las Vegas"), stringsAsFactors = FALSE)

# Testing function
adress_checker(right_city, my_city_codes)
[1] "Correct city"
adress_checker(wrong_city, my_city_codes)
[1] "Incorrect city"


Q: Drawbacks to nesting of child windows? Just for fun I'm developing a native Win32 port of Mozilla XUL. XUL allows to create complex nested structures of all kinds of layout boxes (hbox, vbox, grid, deck..). For my Windows implemenation it would be convenient to implement them as STATIC child windows. Because then I can position their child windows using x & y offsets independent of the position of the parent box.
However, this approach may lead to certain windows having a lot of nested child windows. And I wonder if there would be any disadvantages to such a situation. Does anyone here know?

A: I've been down this path, and I don't recommend you actually make deep hierarchies of windows.  Lots of Windows helper functions (e.g., IsDialogMessage) work better with "traditional" layouts.  Also, windows in Windows are relatively heavy objects, mostly for historical reasons.  So if you have tons of objects, you could run into limitations, performance problems, etc.
What I've done instead is to represent the deeply-nested layout as a tree of regular C++ objects that parallels the flatter hierarchy of actual windows.  Some nodes of the object hierarchy have the HWNDs of the "real" windows they represent.  You tell the hierarchy to lay out, and the nodes apply the results to the corresponding windows.
For example, the root of the hierarchy may represent a dialog window, and the leaf nodes represent the child windows.  But the hierarchy has several layers of non-window objects in between that know about layout.

A: A rough take on this:

*

*memory overhead for the window management on application- and os-side

*reduced speed due to calls to external library / os which do way more for windows than needed for your application

*possibly quite some overhead through long window message paths in complex layouts

It probably depends on wether you want a very fast implementation and do efficient buffered drawing by yourself or want it to work more reliably and with less time invested.


Q: Create VectorDrawable from String (path)? Is there a way to get SVG path string from the API and create VectorDrawable dynamically?
I have been trying to do this for hours without success. Even more, all (!) examples on the Internet explain creating VectorDrawable from XML resources.
In my case, XML resource file is pointless as I am trying to fetch SVG path from the Internet API.

A: Inflating a drawable from a XML file instead of from resources is actually impossible, because the drawable will try to cast the XmlPullParser to XmlResourceParser which is only implemented by private class XmlBlock.Parser. Even that parser is only used for parsing binary XML files. I tried every possible way of doing this without reflection, it's impossible.
So I found documentation on binary XML files and learned how they were made, helped with some compiled binary XML vector drawable files I had. The documentation dates back to 2011 and is still valid, I guess it will most likely remain this way, so future compatibility isn't an issue.
A previous version was tested for more than a thousand paths, without problem. The new version posted here should work just as well. (Previous versions are available in the answer history) Compared with loading a drawable directly from resources, I found that there's an average of 14 microseconds or so of extra loading, not noticeable.
Here's the code:
public class VectorDrawableCreator {

    private static final byte[][] BIN_XML_STRINGS = {
            "width".getBytes(),
            "height".getBytes(),
            "viewportWidth".getBytes(),
            "viewportHeight".getBytes(),
            "fillColor".getBytes(),
            "pathData".getBytes(),
            "path".getBytes(),
            "vector".getBytes(),
            "http://schemas.android.com/apk/res/android".getBytes()
    };

    private static final int[] BIN_XML_ATTRS = {
            android.R.attr.height,
            android.R.attr.width,
            android.R.attr.viewportWidth,
            android.R.attr.viewportHeight,
            android.R.attr.fillColor,
            android.R.attr.pathData
    };

    private static final short CHUNK_TYPE_XML = 0x0003;
    private static final short CHUNK_TYPE_STR_POOL = 0x0001;
    private static final short CHUNK_TYPE_START_TAG = 0x0102;
    private static final short CHUNK_TYPE_END_TAG = 0x0103;
    private static final short CHUNK_TYPE_RES_MAP = 0x0180;

    private static final short VALUE_TYPE_DIMENSION = 0x0500;
    private static final short VALUE_TYPE_STRING = 0x0300;
    private static final short VALUE_TYPE_COLOR = 0x1D00;
    private static final short VALUE_TYPE_FLOAT = 0x0400;

    /**
     * Create a vector drawable from a list of paths and colors
     * @param width drawable width
     * @param height drawable height
     * @param viewportWidth vector image width
     * @param viewportHeight vector image height
     * @param paths list of path data and colors
     * @return the vector drawable or null it couldn't be created.
     */
    public static Drawable getVectorDrawable(@NonNull Context context,
                                             int width, int height,
                                             float viewportWidth, float viewportHeight,
                                             List<PathData> paths) {
        byte[] binXml = createBinaryDrawableXml(width, height, viewportWidth, viewportHeight, paths);

        try {
            // Get the binary XML parser (XmlBlock.Parser) and use it to create the drawable
            // This is the equivalent of what AssetManager#getXml() does
            @SuppressLint("PrivateApi")
            Class<?> xmlBlock = Class.forName("android.content.res.XmlBlock");
            Constructor xmlBlockConstr = xmlBlock.getConstructor(byte[].class);
            Method xmlParserNew = xmlBlock.getDeclaredMethod("newParser");
            xmlBlockConstr.setAccessible(true);
            xmlParserNew.setAccessible(true);
            XmlPullParser parser = (XmlPullParser) xmlParserNew.invoke(
                    xmlBlockConstr.newInstance((Object) binXml));

            if (Build.VERSION.SDK_INT >= 24) {
                return Drawable.createFromXml(context.getResources(), parser);
            } else {
                // Before API 24, vector drawables aren't rendered correctly without compat lib
                final AttributeSet attrs = Xml.asAttributeSet(parser);
                int type = parser.next();
                while (type != XmlPullParser.START_TAG) {
                    type = parser.next();
                }
                return VectorDrawableCompat.createFromXmlInner(context.getResources(), parser, attrs, null);
            }

        } catch (Exception e) {
            Log.e(VectorDrawableCreator.class.getSimpleName(), "Vector creation failed", e);
        }
        return null;
    }

    private static byte[] createBinaryDrawableXml(int width, int height,
                                                  float viewportWidth, float viewportHeight,
                                                  List<PathData> paths) {
        List<byte[]> stringPool = new ArrayList<>(Arrays.asList(BIN_XML_STRINGS));
        for (PathData path : paths) {
            stringPool.add(path.data);
        }

        ByteBuffer bb = ByteBuffer.allocate(8192);  // Capacity might have to be greater.
        bb.order(ByteOrder.LITTLE_ENDIAN);

        int posBefore;

        // ==== XML chunk ====
        // https://justanapplication.wordpress.com/2011/09/22/android-internals-binary-xml-part-two-the-xml-chunk/
        bb.putShort(CHUNK_TYPE_XML);  // Type
        bb.putShort((short) 8);  // Header size
        int xmlSizePos = bb.position();
        bb.position(bb.position() + 4);

        // ==== String pool chunk ====
        // https://justanapplication.wordpress.com/2011/09/15/android-internals-resources-part-four-the-stringpool-chunk/
        int spStartPos = bb.position();
        bb.putShort(CHUNK_TYPE_STR_POOL);  // Type
        bb.putShort((short) 28);  // Header size
        int spSizePos = bb.position();
        bb.position(bb.position() + 4);
        bb.putInt(stringPool.size());  // String count
        bb.putInt(0);  // Style count
        bb.putInt(1 << 8);  // Flags set: encoding is UTF-8
        int spStringsStartPos = bb.position();
        bb.position(bb.position() + 4);
        bb.putInt(0);  // Styles start

        // String offsets
        int offset = 0;
        for (byte[] str : stringPool) {
            bb.putInt(offset);
            offset += str.length + (str.length > 127 ? 5 : 3);
        }

        posBefore = bb.position();
        bb.putInt(spStringsStartPos, bb.position() - spStartPos);
        bb.position(posBefore);

        // String pool
        for (byte[] str : stringPool) {
            if (str.length > 127) {
                byte high = (byte) ((str.length & 0xFF00 | 0x8000) >>> 8);
                byte low = (byte) (str.length & 0xFF);
                bb.put(high);
                bb.put(low);
                bb.put(high);
                bb.put(low);
            } else {
                byte len = (byte) str.length;
                bb.put(len);
                bb.put(len);
            }
            bb.put(str);
            bb.put((byte) 0);
        }

        if (bb.position() % 4 != 0) {
            // Padding to align on 32-bit
            bb.put(new byte[4 - (bb.position() % 4)]);
        }

        // Write string pool chunk size
        posBefore = bb.position();
        bb.putInt(spSizePos, bb.position() - spStartPos);
        bb.position(posBefore);

        // ==== Resource map chunk ====
        // https://justanapplication.wordpress.com/2011/09/23/android-internals-binary-xml-part-four-the-xml-resource-map-chunk/
        bb.putShort(CHUNK_TYPE_RES_MAP);  // Type
        bb.putShort((short) 8);  // Header size
        bb.putInt(8 + BIN_XML_ATTRS.length * 4);  // Chunk size
        for (int attr : BIN_XML_ATTRS) {
            bb.putInt(attr);
        }

        // ==== Vector start tag ====
        int vstStartPos = bb.position();
        int vstSizePos = putStartTag(bb, 7, 4);

        // Attributes
        // android:width="24dp", value type: dimension (dp)
        putAttribute(bb, 0, -1, VALUE_TYPE_DIMENSION, (width << 8) + 1);

        // android:height="24dp", value type: dimension (dp)
        putAttribute(bb, 1, -1, VALUE_TYPE_DIMENSION, (height << 8) + 1);

        // android:viewportWidth="24", value type: float
        putAttribute(bb, 2, -1, VALUE_TYPE_FLOAT, Float.floatToRawIntBits(viewportWidth));

        // android:viewportHeight="24", value type: float
        putAttribute(bb, 3, -1, VALUE_TYPE_FLOAT, Float.floatToRawIntBits(viewportHeight));

        // Write vector start tag chunk size
        posBefore = bb.position();
        bb.putInt(vstSizePos, bb.position() - vstStartPos);
        bb.position(posBefore);

        for (int i = 0; i < paths.size(); i++) {
            // ==== Path start tag ====
            int pstStartPos = bb.position();
            int pstSizePos = putStartTag(bb, 6, 2);

            // android:fillColor="#aarrggbb", value type: #rgb.
            putAttribute(bb, 4, -1, VALUE_TYPE_COLOR, paths.get(i).color);

            // android:pathData="...", value type: string
            putAttribute(bb, 5, 9 + i, VALUE_TYPE_STRING, 9 + i);

            // Write path start tag chunk size
            posBefore = bb.position();
            bb.putInt(pstSizePos, bb.position() - pstStartPos);
            bb.position(posBefore);

            // ==== Path end tag ====
            putEndTag(bb, 6);
        }

        // ==== Vector end tag ====
        putEndTag(bb, 7);

        // Write XML chunk size
        posBefore = bb.position();
        bb.putInt(xmlSizePos, bb.position());
        bb.position(posBefore);

        // Return binary XML byte array
        byte[] binXml = new byte[bb.position()];
        bb.rewind();
        bb.get(binXml);

        return binXml;
    }

    private static int putStartTag(ByteBuffer bb, int name, int attributeCount) {
        // https://justanapplication.wordpress.com/2011/09/25/android-internals-binary-xml-part-six-the-xml-start-element-chunk/
        bb.putShort(CHUNK_TYPE_START_TAG);
        bb.putShort((short) 16);  // Header size
        int sizePos = bb.position();
        bb.putInt(0); // Size, to be set later
        bb.putInt(0);  // Line number: None
        bb.putInt(-1);  // Comment: None

        bb.putInt(-1);  // Namespace: None
        bb.putInt(name);
        bb.putShort((short) 0x14);  // Attributes start offset
        bb.putShort((short) 0x14);  // Attributes size
        bb.putShort((short) attributeCount);  // Attribute count
        bb.putShort((short) 0);  // ID attr: none
        bb.putShort((short) 0);  // Class attr: none
        bb.putShort((short) 0);  // Style attr: none

        return sizePos;
    }

    private static void putEndTag(ByteBuffer bb, int name) {
        // https://justanapplication.wordpress.com/2011/09/26/android-internals-binary-xml-part-seven-the-xml-end-element-chunk/
        bb.putShort(CHUNK_TYPE_END_TAG);
        bb.putShort((short) 16);  // Header size
        bb.putInt(24);  // Chunk size
        bb.putInt(0);  // Line number: none
        bb.putInt(-1);  // Comment: none
        bb.putInt(-1);  // Namespace: none
        bb.putInt(name);  // Name: vector
    }

    private static void putAttribute(ByteBuffer bb, int name,
                                     int rawValue, short valueType, int valueData) {
        // https://justanapplication.wordpress.com/2011/09/19/android-internals-resources-part-eight-resource-entries-and-values/#struct_Res_value
        bb.putInt(8);  // Namespace index in string pool (always the android namespace)
        bb.putInt(name);
        bb.putInt(rawValue);
        bb.putShort((short) 0x08);  // Value size
        bb.putShort(valueType);
        bb.putInt(valueData);
    }

    public static class PathData {

        public byte[] data;
        public int color;

        public PathData(byte[] data, int color) {
            this.data = data;
            this.color = color;
        }

        public PathData(String data, int color) {
            this(data.getBytes(StandardCharsets.UTF_8), color);
        }

    }

}

A call to getVectorDrawable returns a VectorDrawable from a list of paths. The drawable can contain multiple paths with different colors. There are also parameters for the drawable and viewport size.
Here's an example:
List<PathData> pathList = Arrays.asList(new PathData("M128.09 5.02a110.08 110.08 0 0 0-110 110h220a109.89 109.89 0 0 0-110-110z", Color.parseColor("#7cb342")),
                    new PathData("M128.09 115.02h-110a110.08 110.08 0 0 0 110 110 110.08 110.08 0 0 0 110-110z", Color.parseColor("#8bc34a")),
                    new PathData("M207.4 115.2v-.18h-5.1l-61.43-61.43h-25.48v20.6h-6.5a11.57 11.57 0 0 0-11.53 11.53v26.09h.11c-.11.9.5 2 1.7 3.32.12.08.12.08.12.2l3.96 4-46.11 79.91c5.33 4.5 11.04 8.4 17 11.8a109.81 109.81 0 0 0 108.04 0 110.04 110.04 0 0 0 51.52-64.65c.38-1.28.68-2.57 1.1-3.78z", Color.parseColor("#30000000")),
                    new PathData("M216.28 230.24a6.27 6.27 0 0 0-.9-2.8l-31.99-55.57-10.58-18.48-19.85-34.21-15.08 15.12 18.6 32.28 10.2 17.73 30.92 53.37a5.6 5.6 0 0 0 1.97 2.12l15.42 10.5c.6.39 1.29.39 1.9.08.6-.37.9-.98.9-1.7z", Color.parseColor("#e1e1e1")),
                    new PathData("M186.98 115.02a58.9 58.9 0 0 1-30.5 51.6 58.4 58.4 0 0 1-56.7 0l18.6-32.28-15.13-15.12-62.48 108.22c-.5.9-.8 1.78-.9 2.8l-1.4 18.6c-.12.71.3 1.28.9 1.7.6.37 1.29.3 1.9-.12l15.41-10.4a7.87 7.87 0 0 0 1.97-2.07l30.92-53.53a78.74 78.74 0 0 0 77.23 0 76.65 76.65 0 0 0 16.6-12.4 79.3 79.3 0 0 0 24.07-56.89z", Color.parseColor("#f1f1f1")),
                    new PathData("M147.3 74.12h-6.43v-20.6h-25.48v20.6h-6.5a11.57 11.57 0 0 0-11.53 11.5v26.07h.11c-.11 1.02.5 2.12 1.82 3.4l23.05 23.14a8.3 8.3 0 0 0 5.75 2.38v-.07l.07.07c2.12 0 4.2-.75 5.71-2.38l23.1-23.1c1.32-1.32 1.81-2.53 1.81-3.4h.12V85.7a11.68 11.68 0 0 0-11.6-11.6zm-19.14 40.9h-.07a15.4 15.4 0 0 1 0-30.8v-.2l.07.2a15.46 15.46 0 0 1 15.31 15.38 15.46 15.46 0 0 1-15.3 15.42z", Color.parseColor("#646464")));

A: @Andre.Anzi To extend the class to support strokeColor and strokeWidth, you can try to arrange the attributes in an alphabetical order.


Q: Ionic Cordova Device UUID Hi i am developing a hybrid app using the Ionic framework and Cordova. I am looking to use the device uuid as an ID so i have added the cordova device plugin. Additionally i am using the NG-Cordova wrapper for calling my cordova plugins. However whenever i run my app in the xcode Simulator or on an actual Ipad all i get is {{uuid}} .
There does not seem to be any error message i can only assume that the Device Plugin is not working.
i have put my code below however im not sure this is the issue, Has anyone had this issue before and if so how did they work around it?
Controller:
angular.module('starter.controllers', []).controller('DashCtrl', function(
$scope, $state, $cordovaDevice) {
var init = function() {
    console.log("initializing device");
    try {
        $scope.uuid = $cordovaDevice.getUUID();
    } catch (err) {
        console.log("Error " + err.message);
        alert("error " + err.$$failure.message);
    }
};
init();

})
Html
<ion-view title="Dashboard">
  <ion-content class="padding">

Dash

    {{uuid}}
  </ion-content>
</ion-view>

app.js
angular.module('starter', ['ionic', 'starter.controllers', 'starter.services'])
    .run(function($ionicPlatform) {
        $ionicPlatform.ready(function() {
            if (window.cordova && window.cordova.plugins.Keyboard) {
                cordova.plugins.Keyboard.hideKeyboardAccessoryBar(
                    true);
            }
            if (window.StatusBar) {
                // org.apache.cordova.statusbar required
                StatusBar.styleDefault();
            }
        });
    }).config(function($stateProvider, $urlRouterProvider) {
        $stateProvider
        // setup an abstract state for the tabs directive
            .state('tab', {
                url: "/tab",
                abstract: true,
                templateUrl: "templates/tabs.html"
            })
            // Each tab has its own nav history stack:
            .state('tab.dash', {
                url: '/dash',
                views: {
                    'tab-dash': {
                        templateUrl: 'templates/tab-dash.html',
                        controller: 'DashCtrl'
                    }
                }
            });
        // if none of the above states are matched, use this as the fallback
        $urlRouterProvider.otherwise('/tab/dash');
    });

A: the reason behind my issue was due to using a custom build of ngCordova.
if i just the normal or Minified version of ngcordova it works perfectly.
Thanks for all the help.


Q: Docker Remote API to login to registry I am looking for documentation for docker login, I need to login to a registry to pull docker image and I need to do it remotely using docker remote APIs.
But unfortunately I am unable to find docker remote API docs, any help would be greatly appreciated.
API doc :
https://docs.docker.com/engine/reference/api/docker_remote_api_v1.19/
Thanks in advance.
Sarath Krishnan

A: you go as
 docker login your.domain.to.the.registr.without.protocol.or.port
 enter username
 enter password

now you can pull using docker pull your.domain.to.the.registr.without.protocol.or.port/youimage
Ensure your registry runs behind a SSL proxy / termination, or you run into security issues. Consider reading this in this case https://docs.docker.com/registry/insecure/


Q: Nginx conditional rewrite I am trying to redirect domain1.com to domain2.com based on http/https.

*

*So a request to http://domain1.com will go to http://domain2.com.

*Request to https://domain1.com goes to https://domain2.com
My current Nginx vhost file setup as:
server {
    listen 80;
    listen 443 ssl;

    ssl_certificate /etc/nginx/xxx.crt;
    ssl_certificate_key /etc/nginx/xxx.key;

    server_name *.domain1.com;
    if ( $scheme = "https" ) {
        rewrite ^ https://domain2.com$request_uri? permanent;
    }
    rewrite ^ http://domain2.com$request_uri? permanent;
}

However visiting https://domain1.com just goes to http://domain2.com. I can't seem to detect https. What am I doing wrong? Thanks.
EDIT:
I have edited my vhost to the below but the same issue occurs.:
server {
    listen 80;
    listen 443 ssl;

    ssl_certificate /etc/nginx/xxx.crt;
    ssl_certificate_key /etc/nginx/xxx.key;

    server_name *.domain1.com domain1.com;
    return 301 $scheme://domain2.com$request_uri;
}

A: There is no need to use if and rewrite
return 301 $scheme://domain2.com$request_uri;


Q: Python: all index of list greater than x data = [10, 90, 20, 80, 30, 40, 70, 60]
A_list=[A,B,C,D,E,F,G,H]

How do I find all the values in data that are above 50.
Next how do I print so that it displays
B:90
D:80
H:60
G:70

Also I haven't used enumerate yet.

A: If you just want to print all the values higher then 50 a simple loop will do.
data = [10, 90, 20, 80, 30, 40, 70, 60]
for value in data:
    if value > 50:
        print(value)

If you need the indexes use this code. enumerate will give you an automatic counter.
data = [10, 90, 20, 80, 30, 40, 70, 60]
for index, value in enumerate(data):
    if value > 50:
        print(index)

If you need a list of indexes to print the values (your question is unclear at that point) then construct this list and loop over it.
data = [10, 90, 20, 80, 30, 40, 70, 60]
indexes = [index for index, value in enumerate(data) if value > 50]
for index in indexes:
    print(data[index])

According to the question in your comment you could do the following (based on the last solution).
data = [10, 90, 20, 80, 30, 40, 70, 60]
characters = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']
indexes = [index for index, value in enumerate(data) if value > 50]
for index in indexes:
    print('{}: {}'.format(characters[index], data[index]))

This code uses the index for both lists.
If this is homework and you can't use enumerate you have to construct the indexes list with a standard for loop.
indexes = []
for index in range(len(data)):
    if data[index] > 50:
        indexes.append(index)

A pythonic solution would be something like this.
data = [10, 90, 20, 80, 30, 40, 70, 60]
characters = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']
for char, value in zip(characters, data):
    if value > 50:
        print('{}: {}'.format(char, value))

A: In case you want the elements of the list which are greater than 50, you can simply use a list comprehension:
[el for el in lst if el>50]

where lst is your input list.
If you also wanted the index of those elements, you could:
[(i,el) for (i,el) in enumerate(lst) if el>50]

which would give you a list of tuples (index, element)

A: You want an if loop; if x is greater than one of the numbers, print it?
example:
myList = list(range(0,100))

for numb in myList:
    if numb > 50:
        print numb

Honestly, I'm not sure what OP wants to do. But this is just an example.

A: If you would like to use enumerate(), and you would like to store both the indexes of the numbers above 50 and the values themselves, one way would be to do it like so:
>>> a = [1,2,3,4,5,50,51,3,53,57]
>>> b, c = zip(*[(d, x) for d, x in enumerate(a) if x > 50])
>>> print b
(6, 8, 9)
>>> print c
(51, 53, 57)

Enumerate takes any object that supports iteration, and returns a tuple, (count, value), when the next() method of the iterator is called. Since enumerate() defaults to start its count at 0, and increments the count by one each iteration, we can use it to count the index of the array that the iteration is currently on.
Now, our list comprehension is returning a list of tuples, if we were to print the comprehension we would get:
>>> print [(d, x) for d, x in enumerate(a) if x > 50]
[(6, 51),(8, 53),(9, 57)]

Zip creates a list of tuples when given two arrays, for example:
>>> f = [1, 2, 3]
>>> g = [4, 5, 6]
>>> zipped = zip(f, g)
>>> zipped
[(1, 4), (2, 5), (3, 6)]

When used with the * operator, zip() will "unzip" a list.
So, when we "unzip" the list comprehension, two tuples are returned.
Hope this helps!


Q: rails multiple belongs_to assignments with nested attributes My problem is that how to assign multiple belongs_to associations with nested attributes?
I want to build a issue system. When I create a issue, I also want to create the first comment as the issue body.
So, I have following Models:
class Issue < ActiveRecord::Base
  has_many :comments, as: :commentable

  validates :title, presence: true

  accepts_nested_attributes_for :comments
end

class Comment < ActiveRecord::Base
  belongs_to :user
  belongs_to :commentable, polymorphic: true

  validates :content, :user, presence: true
end

and I have the IssuesController as follow:
class IssuesController < ApplicationController
  before_action :authenticate_user! #devise authentication

  def new
    @issue = Issue.new
    @issue.comments.build
  end

  def create
    @issue = Issue.new(issue_params)
    @issue.save
  end

  private

  def issue_params
    params.require(:issue).permit(:title, comments_attributes: [:content])
  end
end

and the following is my form (using slim template with simple_form and nested_form gems):
= simple_nested_form_for @issue do |f|

  = f.input :title

  = f.fields_for :comments do |cf|
    = cf.input :content

  = f.button :submit

In this case, I don't know how to assign current_user to the comment created by nested attributes.
Any suggestions or other approaches? Thanks!

A: As I wrote in the comments, there's two ways of doing this.
The first way is to add a hidden field in your subform to set the current user:
= simple_nested_form_for(@issue) do |f|
  = f.input :title
  = f.fields_for(:comments) do |cf|
    = cf.input(:content)
    = cf.hidden(:user, current_user)
  = f.submit

If you do not trust this approach in fear of your users fiddling with the fields in the browser, you can also do this in your controller.
class IssuesController < ApplicationController
  before_action :authenticate_user! #devise authentication

  def new
    @issue = Issue.new
    @issue.comments.build
  end

  def create
    @issue = Issue.new(issue_params)
    @issue.comments.first.user = current_user
    @issue.save
  end

  private

  def issue_params
    params.require(:issue).permit(:title, comments_attributes: [:content])
  end
end

This way you take the first comment that is created through the form and just manually assign the user to it. Then you know for the sure that the first created comment belongs to your current user.

A: You could also add user_id as current_user.id when you use params
class IssuesController < ApplicationController
  before_action :authenticate_user! #devise authentication

  def new
    @issue = Issue.new
    @issue.comments.build
  end

  def create
    @issue = Issue.new(issue_params)
    @issue.save
  end

  private

  def issue_params
    params[:issue][:comment][:user_id] = current_user.id
    params.require(:issue).permit(:title, comments_attributes: [:content, :user_id])
  end
end


Q: htaccess not get index file after rewrite rule My htaccess is this :
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^([0-9a-zA-Z-]+)?$ show.php?id=$1 [L]
</IfModule>

So whenever browser get 'any thing' after root folder then it will go show.php and parameter will be  'any thing' .
Note: it will not effect if it have extension or a folder.
But there is index file in my root folder. So browser should take index file first. So that, i added this in .htaccess file :
DirectoryIndex index.php

But not working. So is there anything to do, to show at least index file whenever root folder visited ?

A: You can have your .htaccess like this:
DirectoryIndex index.php

RewriteEngine On

# request is not for a file
RewriteCond %{REQUEST_FILENAME} !-f
# request is not for a directory
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([0-9a-zA-Z-]+)/?$ /show.php?id=$1 [L,QSA]


Q: C# Winform app GUI is not showing run as scheduled task using .BAT file I have created a winform app for sending bulk emails. I have scheduled this app using a .BAT file. The app is running as per the schedule and sending emails, but it is not showing the GUI.
When I search I found this link Winforms app as Scheduled task, As per that I have confirmed that I am using the same user account for scheduling the task and login into the machine. When I double click on the .BAT file, the app is running by showing the GUI. Does anybody knows what is the issue. Here is the content in my .BAT file.
c:

cd\

cd ABC

sendMailApp.exe

A: On your last line, you could try using
call start sendMailApp.exe

I think this might fix it, call will cause start to run a new process and open a new window for the process which should show the GUI.
Docs here:
http://ss64.com/nt/call.html
http://ss64.com/nt/start.html


Q: ImageView on top of another imageview in Android I am having a navigation drawer (sliding menu) with header set in my app. I am trying out the following for the headerView.xml

I am setting a background image to the relativeLayout from a particular URL. Instead I would like to have ImageView like below:
By doing this I can use picasso library even for background image that I receive from an URL. This way the image loading is faster I don't need to save the background to any sd card etc.

Here is what I have right now:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools"
  android:id="@+id/LayoutforbgImage"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:adjustViewBounds="true"
  android:baselineAligned="false"
  android:orientation="horizontal" >

<LinearLayout
    android:id="@+id/LinearLayoutforImage"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:paddingBottom="10dp"
    android:paddingLeft="5dp"
    android:paddingTop="10dp"
    tools:ignore="RtlSymmetry,RtlHardcoded" >

    <ImageView
        android:id="@+id/imageforprofile"
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:src="@drawable/profilepic" />
</LinearLayout>

<TextView
    android:id="@+id/textforprofile"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_toRightOf="@+id/LinearLayoutforImage"
    android:gravity="left"
    android:paddingLeft="5dp"
    android:paddingTop="16dp"
    android:text="My Name My Name"
    android:textColor="#FFFFFF"
    android:textStyle="bold"
    tools:ignore="HardcodedText,RtlHardcoded,RtlSymmetry" />

<TextView
    android:id="@+id/textforprofileemail"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/textforprofile"
    android:layout_toRightOf="@+id/LinearLayoutforImage"
    android:gravity="left"
    android:paddingBottom="10dp"
    android:paddingLeft="5dp"
    android:text="myname@abc.com"
    android:textColor="#FFFFFF"
    android:textStyle="bold"
    tools:ignore="HardcodedText,RtlHardcoded,RtlSymmetry" />

  </RelativeLayout>

I am setting background image to layout for: LayoutforbgImage
using:
headerLayout = (RelativeLayout) header.findViewById(R.id.LayoutforbgImage );
BitmapDrawable background = new BitmapDrawable(decodeBase64(coverimage));
headerLayout.setBackgroundDrawable(background);

headerprofileimage = (ImageView) header.findViewById(R.id.imageforprofile);
Picasso.with(this).load(profileImage).placeholder(R.drawable.profilepic).error(R.drawable.profilepic).into(headerprofileimage);

How do I create the ImageView for background image so that it fits perfectly in the layout specified like above?

A: Try this layout i hope it will help you
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <ImageView
            android:id="@+id/imageView1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"

            android:scaleType="fitXY"
            android:src="@drawable/top_header_bg" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:orientation="horizontal" >

            <ImageView
                android:id="@+id/imageView2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="20dp"
                android:src="@drawable/ic_launcher" />

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:gravity="center"
                android:layout_marginRight="20dp"
                android:orientation="vertical" >

                <TextView
                    android:id="@+id/textView2"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="TextView" />

                <TextView
                    android:id="@+id/textView1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="TextView" />

            </LinearLayout>

        </LinearLayout>

    </RelativeLayout>

</LinearLayout>

A: hi try the following code it will help you i didn't make any changes. i simply add an ImageView to your layout.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LayoutforbgImage"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:adjustViewBounds="true"
    android:baselineAligned="false"
    android:orientation="horizontal" >

    <ImageView
        android:id="@+id/your_image"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:background="@drawable/top_bar" />

    <LinearLayout
        android:id="@+id/LinearLayoutforImage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingBottom="10dp"
        android:paddingLeft="5dp"
        android:paddingTop="10dp"
        tools:ignore="RtlSymmetry,RtlHardcoded" >

        <ImageView
            android:id="@+id/imageforprofile"
            android:layout_width="60dp"
            android:layout_height="60dp"
            android:src="@drawable/images12" />
    </LinearLayout>

    <TextView
        android:id="@+id/textforprofile"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/LinearLayoutforImage"
        android:gravity="left"
        android:paddingLeft="5dp"
        android:paddingTop="16dp"
        android:text="My Name My Name"
        android:textColor="#FFFFFF"
        android:textStyle="bold"
        tools:ignore="HardcodedText,RtlHardcoded,RtlSymmetry" />

    <TextView
        android:id="@+id/textforprofileemail"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textforprofile"
        android:layout_toRightOf="@+id/LinearLayoutforImage"
        android:gravity="left"
        android:paddingBottom="10dp"
        android:paddingLeft="5dp"
        android:text="myname@abc.com"
        android:textColor="#FFFFFF"
        android:textStyle="bold"
        tools:ignore="HardcodedText,RtlHardcoded,RtlSymmetry" />

</RelativeLayout>

A: Try this way hope it will solve your problem
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <RelativeLayout
        android:id="@+id/topBarRelative"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true" >

        <ImageView
            android:id="@+id/imageHeader"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentRight="true"
            android:layout_alignParentTop="true"
            android:adjustViewBounds="true"
            android:cropToPadding="false"
            android:src="@drawable/right_top_bg" />

        <ImageView
            android:id="@+id/imageforprofile"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_centerVertical="true"
            android:layout_marginLeft="9dp"
            android:src="@drawable/ic_launcher" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_marginRight="9dp"
            android:layout_toRightOf="@+id/imageforprofile"
            android:gravity="center"
            android:orientation="vertical" >

            <TextView
                android:id="@+id/textforprofile"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginBottom="3dp"
                android:text="My Name My Name"
                android:textColor="#FFFFFF"
                android:textStyle="bold" />

            <TextView
                android:id="@+id/textforprofileemail"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="myname@abc.com"
                android:textColor="#FFFFFF"
                android:textStyle="bold" />
        </LinearLayout>
    </RelativeLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/topBarRelative"
        android:layout_margin="8dp"
        android:background="@drawable/content_bg"
        android:orientation="vertical" >
    </LinearLayout>

</RelativeLayout>

Screen shot from Eclipse


Q: Real time video player to embed in an Android app I need a library that supports real time video streaming from an RTSP connection to embed in an Android application I've built. It must have a really low latency (1-2s should be fine). I've already tried with a simple VideoView. It works but it has a HUGE latency (more than 10s) because its buffer size cannot be lowered.
Is there any good and reliable solution?
I would prefer not to build my own player from scratch...
ExoPlayer doesn't seem to support RTSP.

A: I have solved using a modified version of Exoplayer (RTSP Exoplayer GitHub pull request). The buffer size can be edited, so I think it's the best choice for this use case.
It works flawlessly!


Q: Does the JVM JIT generate syscall instructions? I am wondering how does Java code make a syscall, does the JIT compiler generate syscall instructions directly, or that it just put calls to libc functions (or other basic library functions)?

A: The Hotspot JVM generates machine code for Java code (which doesn't support making syscalls).
All code which makes syscalls is in a native method.
So when Java wants to make a syscalls, you have to call some native code to do it for you.
There are libraries you can use to wrap native calls. E.g. JNA and JNR-FFI. This allows you call c libraries without writhing native code.


Q: Reading a file with Rust - borrowed value only lives until here I have a function that should read a file and returns it's contents.
fn read (file_name: &str) -> &str {

    let mut f = File::open(file_name)
        .expect(&format!("file not found: {}", file_name));

    let mut contents = String::new();

    f.read_to_string(&mut contents)
        .expect(&format!("cannot read file {}", file_name));

    return &contents;
}

But I get this error:
  --> src\main.rs:20:13
   |
20 |     return &contents;
   |             ^^^^^^^^ borrowed value does not live long enough
21 | }
   | - borrowed value only lives until here
   |

What am I doing wrong?
My Idea of what is happening here is this:

*

*let mut f = File::open(file_name).expect(....); - this takes a handle of a file and tells the OS that we want to do things with it.

*let mut contents = String::new(); - this creates a vector-like data structure on the heap in order to store the data that we are about to read from the file.

*f.read_to_string(&mut contents).expect(...); - this reads the file into the contents space.

*return &contents; - this returns a pointer to the vector where the file data is stored.
Why am I not able to return the pointer that I want?
How do I close my file (the f variable)? I think that rust will close it for me after the variable goes out of scope, but what If I need to close it before that?

A: You are correct about the file handle being closed automatically when its variable goes out of scope; the same will happen to contents, though - it will be destroyed at the end of the function, unless you decide to return it as an owned String. In Rust functions can't return references to objects created inside them, only to those passed to them as arguments.
You can fix your function as follows:
fn read(file_name: &str) -> String {
    let mut f = File::open(file_name)
        .expect(&format!("file not found: {}", file_name));

    let mut contents = String::new();

    f.read_to_string(&mut contents)
        .expect(&format!("cannot read file {}", file_name));

    contents
}

Alternatively, you can pass contents as a mutable reference to the read function:
fn read(file_name: &str, contents: &mut String) { ... }


Q: ffmpeg -r option I am trying to use ffmpeg (under linux) to add a small title to a video. So, I use:
ffmpeg -i hk.avi -r 30000/1001 -metadata title="SOF" hk_titled.avi

The addition of title seems to work, but, the problem is the output file is about a 1/3rd of the file size of the input file and I was wondering why this is? Is this at the expense of quality of the video? I am unsure.. How do I preserve the same quality/size as the input file?
The main point I am unable to figure out is the use of -r option. Going through the ffmpeg docs, it seems to suggest that -r is frames per second (The input video is 23.9fps). At the moment, (30000/1001) works out to 29 fps, but I was unsure if I should be using this value.
Thanks for your time.

A: The default settings for ffmpeg do not always provide a good quality output when you encode, but this depends on your output format and the available encoders. With your output ffmpeg will use the default of -b 200k or -b:v 200k.
However, you can tell ffmpeg to simply copy the input streams without re-encoding and this is recommended if you just want to add or edit metadata. These examples do the same thing but use different syntax depending on your ffmpeg version:
ffmpeg -i hk.avi -vcodec copy -acodec copy -metadata title="SOF" hk_titled.avi
ffmpeg -i hk.avi -c copy -metadata title="SOF" hk_titled.avi


Q: Slice a list into batches based on byte size Haven't found a similar question
I want to slice an array into smaller batches based on byte size limit. This is my implementation which is a little slow. In particular I want to know if there is a build-in functionality that can get me this, or maybe I can enhance my approach below.
When i accumulated the size of individual items it didn't correlate correctly to the size of the batch. probably extra metadata on the stream itself..
private static List<List<T>> SliceLogsIntoBatches<T>(List<T> data) where T : Log
{
    const long batchSizeLimitInBytes = 1048576;

    var batches = new List<List<T>>();

    while (data.Count > 0)
    {
        var batch = new List<T>();

        batch.AddRange(data.TakeWhile((log) =>
            {
                var currentBatchSizeInBytes = GetObjectSizeInBytes(batch); // this will slow down as takewhile moves on
                return (currentBatchSizeInBytes < batchSizeLimitInBytes);
            }));

        batches.Add(batch);
        data = data.Except(batch).ToList();
    }

    return batches;
}

private static long GetObjectSizeInBytes(object objectToGetSizeFor)
{
    using (var objectAsStream = ConvertObjectToMemoryStream(objectToGetSizeFor))
    {
        return objectAsStream.Length;
    }
}

A: You keep recalculating the size of the batch you are creating. So you are recalculating the size of some data items a lot.
It would help if you would calculate the data size of each data item and simply add that to a variable to keep track of the current batch size.
Try something like this:
long batchSizeLimitInBytes = 1048576;
var batches = new List<List<T>>();
var currentBatch = new List<T>();
var currentBatchLength = 0;
for (int i = 0; i < data.Count; i++)
{
    var currentData = data[i];
    var currentDataLength = GetObjectSizeInBytes(currentData);
    if (currentBatchLength + currentDataLength > batchSizeLimitInBytes)
    {
        batches.Add(currentBatch);
        currentBatchLength = 0;
        currentBatch = new List<T>();
    }

    currentBatch.Add(currentData);
    currentBatchLength += currentDataLength;
}

As a sidenote, I would probably only want to convert the data to byte streams only once, since this is an expensive operation. You currently convert to streams just to check the length, you may want ot have this method actually return the streams batched, instead of List<List<T>>.

A: I think that your approach can be enhanced using the next idea: we can calculate an approximate size of the batch as sum of sizes of data objects; and then use this approximate batch size to form an actual batch; actual batch size is a size of list of data objects. If we use this idea we can reduce the number of invocations of the method GetObjectSizeInBytes.
Here is the code that implements this idea:
private static List<List<T>> SliceLogsIntoBatches<T>(List<T> data) where T : Log
{
    const long batchSizeLimitInBytes = 1048576;

    var batches = new List<List<T>>();
    var currentBatch = new List<T>();

    // At first, we calculate size of each data object.
    // We will use them to calculate an approximate size of the batch.
    List<long> sizes = data.Select(GetObjectSizeInBytes).ToList();

    int index = 0;
    // Approximate size of the batch.
    long dataSize = 0;

    while (index < data.Count)
    {
        dataSize += sizes[index];

        if (dataSize <= batchSizeLimitInBytes)
        {
            currentBatch.Add(data[index]);
            index++;
        }

        // If approximate size of the current batch is greater
        // than max batch size we try to form an actual batch by:
        // 1. calculating actual batch size via GetObjectSizeInBytes method;
        // and then
        // 2. excluding excess data objects if actual batch size is greater
        //    than max batch size.
        if (dataSize > batchSizeLimitInBytes || index >= data.Count)
        {
            // This loop excludes excess data objects if actual batch size
            // is greater than max batch size.
            while (GetObjectSizeInBytes(currentBatch) > batchSizeLimitInBytes)
            {
                index--;
                currentBatch.RemoveAt(currentBatch.Count - 1);
            }

            batches.Add(currentBatch);

            currentBatch = new List<T>();
            dataSize = 0;
        }
    }

    return batches;
}

Here is complete sample that demostrates this approach.


Q: libcurl fails (response code 0 - host not found) in program (built with MinGW) if using bundled libcurl-4.dll I've ported an application over to windows using MinGW and want to distribute it with all the dlls it needs to run.
The app requires libcurl for some ssl (https) requests it makes.
To distribute it I copied all the .dlls & put them alongside the .exe.
That runs fine but whenever it attempts to make a request in curl it gets a 0 response (as in host not found - not zero okay).
The program works fine if I don't use my copy of libcurl-4.dll but instead use the one bundled with msys2.
Why does this happen? I checked in process explorer and the only difference between it working or not is if it uses my copy of libcurl-4.dll (all other dependencies of curl copied fine).

^ that's when it works (using git for window's .dll -- if I copied that dll to next to the program it'd fail)

A: If your libcurl function invoke actually returns zero, then it was invoked fine and there's no problem with your DLLs or similar, but sounds like like you need to tweak your libcurl usage.

A: I've found the reason but I don't know a decent solution.
The bundled libcurl-4.dll only works for https requests if you also bundle the ssl folder that contains certificates. I feel like this is something where it should be using the OS' certs (Windows) but I don't know how to do that.


Q: MPMoviePlayer loading the video but never enters readyToPlay state I have been trying to get a video to play using MPMoviePlayerController for about a week with very little success! I have finally got it to the stage where it loads the video (or at least I presume it does as it can tell me the video duration).
However, my video never becomes playable therefore I am just presented with a black square.
My code is as follows:
  - (void)loadMovieWithURL:(NSURL *)movieURL
{
    NSLog( @"Video URL = '%@'", [movieURL path]);
    NSData *data = [NSData dataWithContentsOfURL:movieURL];
    [[NSNotificationCenter defaultCenter] addObserver:self  selector:@selector(moviePlayerPlaybackStateDidChange:)  name:MPMoviePlayerPlaybackStateDidChangeNotification  object:nil];

    MPMoviePlayerController *mp = [[MPMoviePlayerController alloc] init];
    self.moviePlayer = mp;
    [self.moviePlayer.view setFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
    [self addSubview:self.moviePlayer.view];
    [self.moviePlayer setContentURL:movieURL];
    self.moviePlayer.movieSourceType = MPMovieSourceTypeFile;

    [self.moviePlayer setFullscreen:NO];
    [self.moviePlayer setScalingMode:MPMovieScalingModeFill];
    [self.moviePlayer setControlStyle:MPMovieControlStyleNone];

    //[self.moviePlayer setShouldAutoplay:YES];

    [self.moviePlayer prepareToPlay];
    [self.moviePlayer play];

}

I am printing out a lot of the values to NSLog just to check them, so thought I should provide them below too just to give a better idea of what I'm seeing:
2013-01-07 15:33:39.858 WildMap_iOS[9887:16703] Video URL = '/Users/elliott/Library/Application Support/iPhone Simulator/6.0/Applications/A233395A-3E8F-4E35-BF42-09D9B743EA33/test.3gp'
    2013-01-07 15:33:40.100 WildMap_iOS[9887:16703] [MPAVController] Autoplay: Disabling autoplay for pause
    2013-01-07 15:33:40.101 WildMap_iOS[9887:16703] [MPAVController] Autoplay: Disabling autoplay
    2013-01-07 15:33:40.176 WildMap_iOS[9887:16703] [MPAVController] Autoplay: Enabling autoplay
    2013-01-07 15:33:40.179 WildMap_iOS[9887:16703] [MPAVController] Autoplay: Likely to keep up or full buffer: 0
    2013-01-07 15:33:40.180 WildMap_iOS[9887:16703] [MPAVController] Autoplay: Skipping autoplay, not enough buffered to keep up.
    2013-01-07 15:33:40.181 WildMap_iOS[9887:16703] [MPAVController] Autoplay: Likely to keep up or full buffer: 0
    2013-01-07 15:33:40.182 WildMap_iOS[9887:16703] [MPAVController] Autoplay: Skipping autoplay, not enough buffered to keep up.
    2013-01-07 15:33:40.259 WildMap_iOS[9887:16703] [MPCloudAssetDownloadController] Prioritization requested for media item ID: 0
    2013-01-07 15:33:40.401 WildMap_iOS[9887:16703] [MPAVController] Autoplay: Enabling autoplay
    2013-01-07 15:33:41.344 WildMap_iOS[9887:16703] Is ready to display 0
    2013-01-07 15:33:41.344 WildMap_iOS[9887:16703] Duration: 45.267000

I did setup a notification to check for MPMoviePlayerLoadStateDidChangeNotification but it never changes. Has anyone had a similar issue, or know what could be wrong with my code? If you need anymore information feel free to ask.
EDIT 1 (Testing danh's code)
When using the following:
    NSLog( @"Video URL = '%@'", [movieURL path]);
self.moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:movieURL];
self.moviePlayer.view.frame = self.bounds;
[self addSubview:self.moviePlayer.view];
[self.moviePlayer prepareToPlay];

//NSData *data = [NSData dataWithContentsOfURL:movieURL];
[[NSNotificationCenter defaultCenter] addObserver:self  selector:@selector(moviePlayerPlaybackStateDidChange:)  name:MPMoviePlayerPlaybackStateDidChangeNotification  object:nil];

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(moviePlayerLoadStateChanged:)
                                             name:MPMoviePlayerLoadStateDidChangeNotification object:nil];

My logs are:
2013-01-08 12:08:16.105 WildMap_iOS[705:16703] [MPAVController] Autoplay: Disabling autoplay for pause
2013-01-08 12:08:16.105 WildMap_iOS[705:16703] [MPAVController] Autoplay: Disabling autoplay
2013-01-08 12:08:16.138 WildMap_iOS[705:16703] [MPAVController] Autoplay: Skipping autoplay, disabled (for current item: 1, on player: 0)
2013-01-08 12:08:16.144 WildMap_iOS[705:16703] [MPAVController] Autoplay: Enabling autoplay
2013-01-08 12:08:16.153 WildMap_iOS[705:16703] [MPAVController] Autoplay: Likely to keep up or full buffer: 0
2013-01-08 12:08:16.153 WildMap_iOS[705:16703] [MPAVController] Autoplay: Skipping autoplay, not enough buffered to keep up.
2013-01-08 12:08:16.157 WildMap_iOS[705:16703] [MPCloudAssetDownloadController] Prioritization requested for media item ID: 0
2013-01-08 12:08:16.177 WildMap_iOS[705:16703] [MPAVController] Autoplay: Enabling autoplay
2013-01-08 12:08:17.244 WildMap_iOS[705:16703] Is ready to display 0
2013-01-08 12:08:17.244 WildMap_iOS[705:16703] Duration: 45.267000

So it seems to be the same as the original code where moviePlayerLoadStateChanged is never called. However, I'm still confused as to how the MPMoviePlayerController can pick up the duration of the video if it is unable to load it? Could this be a codec issue? Is there any way to check whether or not the video will work at all after downloaded?
EDIT 2:
Okay this looks like a possible codec issue. I have now tried it with 2 similar URLs, 1 mov / 1 3gp, and the mov one will play with sound but no video whilst the 3gp briefly shows "loading" on the video screen but never changes to the loaded state when this disappears. Can anyone suggest a way of getting this working, or another movie player with more types supported?

A: Try replacing all of your setup code with this:
// get the url as moveURL
self.moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:movieURL];
self.moviePlayer.view.frame = self.view.bounds;
[self.view addSubview:self.moviePlayer.view];
[self.moviePlayer prepareToPlay];

// notice what notification we subscribe to...
[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(moviePlayerLoadStateChanged:)
                                             name:MPMoviePlayerLoadStateDidChangeNotification object:nil];

Log state changes in moviePlayerLoadStateChanged:.  If that doesn't work, it's probably the url that's the problem.


Q: Python equivalent of Go Struct and Unmarshal So I'm working with some JSON data in Python. Its basically a wrapper for an API though I want to have dot access to my values like data.size, I've done a bit of research but I couldn't find the desired results.
I was using json.loads to parse my data so I tried object hooks but that isn't what I want.
Here's an example Go code that I want to replicate.
type dat struct {
    ResponseTime int
    Body body
}

type body struct {
    Day int
    Month int
    Year int
}

var h dat
// e here is my json
data = json.Unmarshal(e, &h)

My results in Python were similar but they were instances of the same class.
My aim is to be able to parse nested dicts and I want to be able to define which dict assigns to which object... not sure if u understand but theres the Go code for you.

A: Using dataclass and dacite
from dataclasses import dataclass
import dacite

@dataclass
class Body:
    day:int
    month:int
    year:int

@dataclass
class Dat:
    response_time: int
    body: Body
data = {'response_time':12, 'body':{'day':1,'month':2,'year':3}}

dat: Dat = dacite.from_dict(Dat,data)
print(dat)

output
Dat(response_time=12, body=Body(day=1, month=2, year=3))

A: Using pymarshaler (Which is close to to golang approach)
import json

from pymarshaler.marshal import Marshal

class Body:
    def __init__(self, day: int, month: int, year: int):
        self.day = day
        self.month = month
        self.year = year

class Dat:
    def __init__(self, response_time: int, body: Body):
        self.response_time = response_time
        self.body = body

marshal = Marshal()

dat_test = Dat(3, Body(1, 2, 3))
dat_json = marshal.marshal(dat_test)
print(dat_json)

result = marshal.unmarshal(Dat, json.loads(dat_json))
print(result.response_time)

see https://pythonawesome.com/marshall-python-objects-to-and-from-json/

A: So turns out it wasn't that hard, I just didn't want to try.
For anyone with the same problem here's the code.
class Typs(object):
    def __init__(self):
        self.type = int
        self.breed = str

class Deets(object):
    def __init__(self):
        self.color = str
        self.type = Typs()

class Base(object):
    def __init__(self):
        self.name = str
        self.details = Deets()

d = {
    "name": "Hello",
    "details": {"color": "black", "type": {"type": 2, "breed": "Normal"}},
}

h = Base()

def unmarshal(d, o):
    for k, v in d.items():
        if hasattr(o, k):
            if isinstance(v, dict):
                unmarshal(v, getattr(o, k))
            else:
                setattr(o, k, v)

    return o

x = unmarshal(d, h)


Q: Image resizing script is not returning a proper stream for further handling Current project:

*

*ASP.NET 4.5.2

*MVC 5

I am trying to leverage the TinyPNG API, and if I just pipe the image over to it, it works great. However, since the majority of users will be on a mobile device, and these produce images at a far higher resolution than what is needed, I am hoping to reduce the resolution of these files prior to them being piped over to TinyPNG. It is my hope that these resized images will be considerably smaller than the originals, allowing me to conduct a faster round trip.
My code:
public static async Task<byte[]> TinyPng(Stream input, int aspect) {
  using(Stream output = new MemoryStream())
  using(var png = new TinyPngClient("kxR5d49mYik37CISWkJlC6YQjFMcUZI0")) {
    ResizeImage(input, output, aspect, aspect); // Problem area
    var result = await png.Compress(output);
    using(var reader = new BinaryReader(await (await png.Download(result)).GetImageStreamData())) {
      return reader.ReadBytes(result.Output.Size);
    }
  }
}
public static void ResizeImage(Stream input, Stream output, int newWidth, int maxHeight) {
  using(var srcImage = Image.FromStream(input)) {
    var newHeight = srcImage.Height * newWidth / srcImage.Width;
    if(newHeight > maxHeight) {
      newWidth = srcImage.Width * maxHeight / srcImage.Height;
      newHeight = maxHeight;
    }

    using(var newImage = new Bitmap(newWidth, newHeight))
    using(var gr = Graphics.FromImage(newImage)) {
      gr.SmoothingMode = SmoothingMode.AntiAlias;
      gr.InterpolationMode = InterpolationMode.HighQualityBicubic;
      gr.PixelOffsetMode = PixelOffsetMode.HighQuality;
      gr.DrawImage(srcImage, new Rectangle(0, 0, newWidth, newHeight));
      newImage.Save(output, ImageFormat.Jpeg);
    }
  }
}

So the ResizeArea is supposed to accept a stream and output a stream, meaning that the TinyPNG .Compress() should work just as well with the output as it would with the original input. Unfortunately, only the .Compress(input) works -- with .Compress(output) TinyPNG throws back an error:
400 - Bad Request. InputMissing, File is empty

I know TinyPNG has its own resizing routines, but I want to do this before the image is sent out over the wire to TinyPNG so that file size (and therefore transmission time) is reduced as much as possible prior to the actual TinyPNG compression.

A: …Aaaaand I just solved my problem by using another tool entirely.
I found ImageProcessor. Documentation is a royal b**ch to get at because it only comes in a Windows *.chm help file (it’s not online… cue one epic Whisky. Tango. Foxtrot.), but after looking at a few examples it did solve my issue quite nicely:
public static async Task<byte[]> TinyPng(Stream input, int aspect) {
  using(var output = new MemoryStream())
  using(var png = new TinyPngClient("kxR5d49mYik37CISWkJlC6YQjFMcUZI0")) {
    using(var imageFactory = new ImageFactory()) {
      imageFactory.Load(input).Resize(new Size(aspect, 0)).Save(output);
    }
    var result = await png.Compress(output);
    using(var reader = new BinaryReader(await (await png.Download(result)).GetImageStreamData())) {
      return reader.ReadBytes(result.Output.Size);
    }
  }
}

and everything is working fine now. Uploads are much faster now as I am not piping a full-sized image straight through to TinyPNG, and since I am storing both final-“full”-sized images as well as thumbnails straight into the database, I am now not piping the whole bloody image twice.
Posted so that other wheel-reinventing chuckleheads like me will actually have something to go on.


Q: d3.js gantt chart issue var taskTypes = ["slot1", "slot2", "slot3","slot4","slot1","slot2","slot6"];

when
var y = d3.scale.ordinal()
    .domain(taskTypes)
    .rangeRoundBands([ 0, height - margin.top - margin.bottom ], .1);

I was doing
var rectTransform = function(d) {
    return "translate(" + x(d.termStartDate) + "," + y(d.slotName) + ")";
    };

and it was coming proper, but now I am taking
var y = d3.scale.ordinal()
     .domain(d3.range(0, taskTypes.length))
     .rangeRoundBands([ 0, height - margin.top - margin.bottom ], .1);

and now
var rectTransform = function(d) {
    return "translate(" + x(d.termStartDate) + "," + y(d.slotName) + ")";
    };

where d.slotName = slot1, or slot2 or slot3 or any other value, y(d.slotName) is returning undefined, any suggestions How to make it work?

A: As per this answer, the domain for the y scale is the array indices of taskTypes. That means that:
y("slot3") = undefined
y(taskTypes.indexOf("slot3")) = 54 // Or some valid value

You need to determine the index of d.slotName in the array. Using indexOf won't behave well for repeated values (like "slot1"). If the item is present more than once, the indexOf method returns the position of the first occurence.