How to get the Edit text position from Recycler View adapter using Text Watcher in android

Question: I want to know how to get position of Edit Text from Recycler View adapter.I used
Card View with in that horizontal Linear Layout has three view TextView,EditText view and TextView.
I want to get particular EditText Position from Textwatcher in Recycler View Adapter.
Adapter:
public class CartlistAdapter extends RecyclerView.Adapter < CartlistAdapter.ViewHolder > {

    private ArrayList < CartItemoriginal > cartlistadp;
    private ArrayList < Cartitemoringinaltwo > cartlistadp2;
    DisplayImageOptions options;
    private Context context;
    public static final String MyPREFERENCES = "MyPrefs";
    public static final String MYCARTPREFERENCE = "CartPrefs";
    public static final String MyCartQtyPreference = "Cartatyid";
    SharedPreferences.Editor editor;
    SharedPreferences shared,
    wishshared;
    SharedPreferences.Editor editors;
    String pos,
    qtyDelete;
    String date;
    String currentDateandTime;
    private static final int VIEW_TYPE_ONE = 1;
    private static final int VIEW_TYPE_TWO = 2;
    private static final int TYPE_HEADER = 0;
    private Double orderTotal = 0.00;
    DecimalFormat df = new DecimalFormat("0");
    Double extPrice;
    View layout,
    layouts;
    SharedPreferences sharedPreferences;
    SharedPreferences.Editor QutId;

    boolean flag = false;

    public CartlistAdapter() {

    }
    public CartlistAdapter(ArrayList < CartItemoriginal > cartlistadp, Context context) {

        this.cartlistadp = cartlistadp;
        this.cartlistadp2 = cartlistadp2;
        this.context = context;
        options = new DisplayImageOptions.Builder().cacheOnDisk(true).cacheInMemory(true).showImageOnLoading(R.drawable.b2)
            .showImageForEmptyUri(R.drawable.b2).build();
        if (YelloPage.imageLoader.isInited()) {
            YelloPage.imageLoader.destroy();
        }
        YelloPage.imageLoader.init(ImageLoaderConfiguration.createDefault(context));
    }

    public int getItemViewType(int position) {

        if (cartlistadp.size() == 0) {
            Toast.makeText(context, String.valueOf(cartlistadp), Toast.LENGTH_LONG).show();
            return VIEW_TYPE_TWO;
        }
        return VIEW_TYPE_ONE;

    }

    @Override
    public CartlistAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int position) {

        ViewHolder viewHolder = null;
        switch (position) {
            case VIEW_TYPE_TWO:
                View view2 = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.activity_cart, viewGroup, false);
                viewHolder = new ViewHolder(view2);
                // return view holder for your placeholder
                break;
            case VIEW_TYPE_ONE:
                View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.cartitemrow, viewGroup, false);
                viewHolder = new ViewHolder(view);
                // return view holder for your normal list item
                break;
        }
        return viewHolder;

    }

    @Override
    public void onBindViewHolder(CartlistAdapter.ViewHolder viewHolder, int position) {
        viewHolder.productnames.setText(cartlistadp.get(position).getProductname());
        viewHolder.cartalisname.setText(cartlistadp.get(position).getAliasname());
        viewHolder.cartprice.setText("Rs" + " " + cartlistadp.get(position).getPrice());
        viewHolder.cartdelivery.setText(cartlistadp.get(position).getDelivery());
        viewHolder.cartshippin.setText(cartlistadp.get(position).getShippincharge());
        viewHolder.cartsellername.setText(cartlistadp.get(position).getSellername());
        viewHolder.Error.setText(cartlistadp.get(position).getError());
        viewHolder.qty.setTag(cartlistadp.get(position));
        if (cartlistadp.get(position).getQty() != 0) {
            viewHolder.qty.setText(String.valueOf(cartlistadp.get(position).getQty()));
        } else {
            viewHolder.qty.setText("0");
        }
        YelloPage.imageLoader.displayImage(cartlistadp.get(position).getProductimg(), viewHolder.cartitemimg, options);
        viewHolder.qty.setTag(R.id.quantity, position);

    }

    @Override
    public int getItemCount() {
        return cartlistadp.size();
    }

    public long getItemId(int position) {
        return position;
    }
    public Object getItem(int position) {
        return cartlistadp.get(position);
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        private TextView productnames, cartalisname, cartprice, cartdelivery, cartshippin, cartsellername, Error, total;
        private ImageView cartitemimg;
        private ImageButton wishbtn, removebtn;
        private LinearLayout removecart, movewishlist;
        private CardView cd;
        private EditText qty;
        private ImageView WishImg;

        public ViewHolder(final View view) {
            super(view);
            productnames = (TextView) view.findViewById(R.id.cartitemname);
            cartalisname = (TextView) view.findViewById(R.id.cartalias);
            cartprice = (TextView) view.findViewById(R.id.CartAmt);
            cartdelivery = (TextView) view.findViewById(R.id.cartdel);
            cartshippin = (TextView) view.findViewById(R.id.shippingcrg);
            cartsellername = (TextView) view.findViewById(R.id.cartSellerName);
            cartitemimg = (ImageView) view.findViewById(R.id.cartimg);
            Error = (TextView) view.findViewById(R.id.error);

            removecart = (LinearLayout) view.findViewById(R.id.removecart);
            movewishlist = (LinearLayout) view.findViewById(R.id.movewishlist);

            WishImg = (ImageView) view.findViewById(R.id.wishimg);

            qty = (EditText) view.findViewById(R.id.quantity);

            String pid, qid;

            sharedPreferences = view.getContext().getSharedPreferences(MYCARTPREFERENCE, Context.MODE_PRIVATE);
            QutId = sharedPreferences.edit();
            Log.d("Position checking1 ---", String.valueOf(getAdapterPosition()));
            MyTextWatcher textWatcher = new MyTextWatcher(view, qty, getAdapterPosition());
            //  qty.addTextChangedListener(new MyTextWatcher(view,getAdapterPosition()));
            qty.addTextChangedListener(textWatcher);

            qty.setOnKeyListener(new View.OnKeyListener() {
                @Override
                public boolean onKey(View v, int keyCode, KeyEvent event) {
                    qty.setSelection(qty.getText().length());
                    return false;
                }
            });

            wishshared = view.getContext().getSharedPreferences(MyPREFERENCES, context.MODE_PRIVATE);
            editors = view.getContext().getSharedPreferences(MyPREFERENCES, context.MODE_PRIVATE).edit();

            shared = view.getContext().getSharedPreferences(MYCARTPREFERENCE, context.MODE_PRIVATE);
            editor = view.getContext().getSharedPreferences(MYCARTPREFERENCE, context.MODE_PRIVATE).edit();

            cd = (CardView) view.findViewById(R.id.cv);
            productnames.setSingleLine(false);
            productnames.setEllipsize(TextUtils.TruncateAt.END);
            productnames.setMaxLines(2);

            totalPrice();

            view.setClickable(true);

        }
        public class InputFilterMinMax implements InputFilter {

            private int min, max;

            public InputFilterMinMax(int min, int max) {
                this.min = min;
                this.max = max;
            }

            public InputFilterMinMax(String min, String max) {
                this.min = Integer.parseInt(min);
                this.max = Integer.parseInt(max);
            }

            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                try {
                    int input = Integer.parseInt(dest.toString() + source.toString());
                    if (isInRange(min, max, input))
                        return null;
                } catch (NumberFormatException nfe) {}
                return "";
            }

            private boolean isInRange(int a, int b, int c) {
                return b > a ? c >= a && c <= b : c >= b && c <= a;
            }
        }

        private class MyTextWatcher implements TextWatcher {
            private View view;
            private EditText editText;
            //private int position;
            private MyTextWatcher(View view, EditText editText, int adapterPosition) {
                this.view = view;
                this.editText = editText;
                // this.position = adapterPosition;

                //  cartlistadp.get(position).getQty() = Integer.parseInt((Caption.getText().toString()));
            }

            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                //do nothing
            }
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                EditText qtyView = (EditText) view.findViewById(R.id.quantity);
                int position = (int) qtyView.getTag(R.id.quantity);
                Log.i("editextpostion", String.valueOf(position));

            }
            public void afterTextChanged(Editable s) {

                DecimalFormat df = new DecimalFormat("0");
                String qtyString = s.toString();
                int quantity = qtyString.equals("") ? 0 : Integer.valueOf(qtyString);
                String quty = String.valueOf(quantity);

                EditText qtyView = (EditText) view.findViewById(R.id.quantity);
                CartItemoriginal product = (CartItemoriginal) qtyView.getTag();

                Log.d("postion is qtytag", "Position is: " + product);
                qtyView.setFilters(new InputFilter[] {
                    new InputFilterMinMax(product.getMinquantity(), product.getMaxquantity())
                });

                if (product.getQty() != quantity) {

                    Double currPrice = product.getExt();
                    Double price = Double.parseDouble(product.getPrice());
                    int maxaty = Integer.parseInt(product.getMaxquantity());
                    int minqty = Integer.parseInt(product.getMinquantity());

                    if (quantity < maxaty) {
                        extPrice = quantity * price;
                    } else {
                        Toast.makeText(context, "Sorry" + " " + " " + "we are shipping only" + " " + " " + maxaty + "  " + " " + "unit of quantity", Toast.LENGTH_LONG).show();
                    }
                    Double priceDiff = Double.valueOf(df.format(extPrice - currPrice));

                    product.setQty(quantity);
                    product.setExt(extPrice);

                    TextView ext = (TextView) view.findViewById(R.id.CartAmt);

                    if (product.getQty() != 0) {
                        ext.setText("Rs." + " " + df.format(product.getExt()));
                    } else {
                        ext.setText("0");
                    }

                    if (product.getQty() != 0) {
                        qtyView.setText(String.valueOf(product.getQty()));
                    } else {
                        qtyView.setText("");
                    }

                    totalPrice();
                }

                return;
            }
        }

        private void totalPrice() {
            int price = 0;
            for (int j = 0; j < cartlistadp.size(); j++) {
                price += Integer.parseInt(cartlistadp.get(j).getPrice()) * (cartlistadp.get(j).getQty());
                String totalprice = String.valueOf(price);
                String count = String.valueOf(cartlistadp.size());
                CartItems.Totalamt.setText(totalprice);
                CartItems.cartcount.setText("(" + count + ")");
                CartItems.carttotalcount.setText("(" + count + ")");
            }
        }

    }

}

Thanks in Advance.
Comment: in onBindViewHolder() method of your adapter contains the position, u can pass that to ur textwatcher through interface call back..
Answer: In onBindViewHolder method of your Adapter, set tag for your EditText like this:
holder.editText.setTag(position);

And in your ViewHolder, add TextWatcher to your EditText
public static class ViewHolder extends RecyclerView.ViewHolder {

    EditText editText ;

    public ViewHolder(View itemView) {
        super(itemView);
        editText = itemView.findViewById(R.id.editText);
        MyTextWatcher textWatcher = new MyTextWatcher(editText);
        editText.addTextChangedListener(textWatcher);
    }
}

And here is your TextWatcher:
public class MyTextWatcher implements TextWatcher {
    private EditText editText;

    public MyTextWatcher(EditText editText) {
        this.editText = editText;
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        int position = (int) editText.getTag();
        // Do whatever you want with position
    }

    @Override
    public void afterTextChanged(Editable s) {

    }
}

NOTE: Make sure you call setTag method from your EditText before calling setText method, else it will throw NullPointerException. Or alternatively you can add null check when calling getTag method.

UPDATE 1
If your EditText already has another tag set, use ID to identify tags. e.g. when setting tag use this:
holder.editText.setTag(R.id.editText, position);

where R.id.editText is valid id of any of your resources (See documentation for details).
And also when getting value:
int position = (int) editText.getTag(R.id.editText);

Comment: i couldn't use viewholder.editext in View Holder class
Comment: I edited that already but Rehan got error like this  java.lang.ClassCastException: com.journaldev.navigationdrawer.Model.CartItemoriginal cannot be cast to java.lang.Integer
                                                                                at com.journaldev.navigationdrawer.Adapter.CartlistAdapter$ViewHolder$MyTextWatcher.onTextChanged(CartlistAdapter.java:329)
Comment: for that error its show this line   viewHolder.qty.setText(String.valueOf(cartlistadp.get(position).getQty()));\
Comment: It may be because you have set another tag for your `EditText`. Let me update the answer for you.
Comment: ok, Your are right i set two tag   viewHolder.qty.setText(String.valueOf(cartlistadp.get(position).getQty())); second  i set like this   viewHolder.qty.setTag(position);
Comment: @hem Check the update. And tell if you have any confusion.
Comment: Got new error   Attempt to invoke virtual method 'int java.lang.Integer.intValue()' on a null object reference in this line OnbindViewholder in this line    viewHolder.qty.setText(String.valueOf(cartlistadp.get(position).getQty()));
Comment: I will send my adapter here can u check for this why i am getting error like this
Comment: I sent my adapter above seperately pls let u check that Where is did mistake over there
Comment: @hem You missed the **NOTE** I think. Re-read it in the answer and move this line `viewHolder.qty.setTag(R.id.quantity, position);` above this check `if (cartlistadp.get(position).getQty() != 0) {` to fix the issue.
Comment: i put inside chiking null condiiton but get error from activity
Comment: java.lang.ClassCastException: com.journaldev.navigationdrawer.Model.CartItemoriginal cannot be cast to java.lang.Integer in that line int position = (int) editText.getTag(R.id.editText);
Answer: Assume you use the following CustomViewHolder
public static class CustomViewHolder extends RecyclerView.ViewHolder {
    private TextView textView;
    private TextView textView2;
    private EditText editText;
    private int position;
    public CustomViewHolder (View view) {
        super(view);
        textView = (TextView) view.findViewById(R.id.text_view);
        textView2 = (TextView) view.findViewById(R.id.text_view2);
        editText = (EditText) view.findViewById(R.id.edit_text);
        editText.addTextChangedListener(new CustomWatcher(this));
    }
}

and use the following CustomWatcher
public static class CustomWatcher implements TextWatcher {
    private int CustomViewHolder holder;
    public CustomWatcher(CustomViewHolder holder){
        this.holder = holder;
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
    }

    @Override
    public void afterTextChanged(Editable s) {

    }

    public int getPosition(){
        return holder.position;
    }
}

Then, in your onBindViewHolder
@Override
public void onBindViewHolder(final CustomViewHolder holder, final int position) {
    holder.position = position;
}

Comment: @Rehan I forgot the CustomViewHolder may be resued by RecyclerView. I have edited the answer.
Comment: Don't you think it will add multiple TextWatchers to the same `EditText` every time when adapter calls the `onBindViewHolder` method for the same view again?
Comment: Just for sake of knowledge, there are several methods for position in `RecyclerView.ViewHolder` as well. Check the [link](https://developer.android.com/reference/android/support/v7/widget/RecyclerView.ViewHolder.html#getAdapterPosition()) :)
Comment: @Rehan `getAdapterPosition` is different from `position` because I tried recently. `getAdapterPosition` is more like position on screen.
Comment: Well that's `getLayoutPosition` not `getAdapterPosition`. I never experienced problem using this (so far). Even the documentation says **Returns the Adapter position of the item represented by this ViewHolder.** for `getAdapterPosition` and **Returns the position of the ViewHolder in terms of the latest layout pass** for `getLayoutPosition`


Excel VBA MACBOOK - Delimited Row Values to stacked 2-Column

Question: I've been looking for an answer to this all over and found multiple solutions that don't work for my version of Excel for Mac (v16.33 2020)
 1. Using Power Query which is not compatible
 2. I followed this link here: LINK which uses Scripting.Dictionary  but when using it, I keep getting the error: "Runtime Error '429'Active X can't create object
 3. I downloaded the updated Dictionary.cls and KeyValuePair.cls from http://www.sysmod.com/Dictionary.zip
  4. After updating the code to: Set dAttributes = New Dictionary
Set dValues = New Dictionary I get an error as k is blank for: For Each k In dic

Issue:
I have a 2-column list of delimited values, and I have to put them into a stacked column on excel. The identifier to be kept on the left column. The reason for doing it is the program we're using needs the item ID title, and one row for each pertaining product URL.
For example:
Column A| Column B
Item 1 | a.jpg, b.jpg, c.jpg
Item 2 | a.jpg, b.jpg, c.jpg
Needs to be:
Column A| Column B
Item 1 |a.jpg
Item 1| b.jpg
Item 2| a.jpg
Item 2| b.jpg
The values for the items and images are all different. There are hundreds of rows and values, so copy paste to transpose manually isn't a viable option.
Currently the code I have is here:  I'm stuck.  Please comment with steps to fix this.  I've tried the suggested links and nothing is working.
Sub ttt()
 Dim dic As Object:
 Set dAttributes = New Dictionary
    Set dValues = New Dictionary
    Dim x&, cl As Range, rng As Range, k, s
    Set rng = Range([C1], Cells(Rows.Count, "C").End(xlUp))
    x = 1 'used as a key for dictionary and as row number for output
    For Each cl In rng
        For Each s In Split(cl.Value2, ",")
            dic.Add x, Cells(cl.Row, "A").Value2 & "|" & _
                        Cells(cl.Row, "B").Value2 & "|" & LTrim(s)
            x = x + 1
    Next s, cl
    For Each k In dic
        Range(Cells(k, "A"), Cells(k, "C")).Value2 = Split(dic(k), "|")
    Next k
End Sub

Comment: You don't need a dictionary for this - split the value from ColB and loop over the array: for each element write out the value from ColA and the element value to a new row.  BTW your code sample uses ColC which is not in your example data.
Comment: I feel silly.  You are amazing.
I was pulling my hair out!! Thank you so SO very much Tim
Answer: You don't need a dictionary for this - split the value from ColB and loop over the array: for each element write out the value from ColA and the element value to a new row.
Dim rw As Range
Dim ws As Worksheet, arr, e, c As Range
Set ws = ActiveSheet
Set c = ws.Range("H1") '<< start of output

'loop over input rows
For Each rw In ws.Range("A1").CurrentRegion.Rows
    arr = Split(rw.Cells(2).Value, ",")
    For Each e In arr
        c.Resize(1, 2).Value = Array(rw.Cells(1).Value, Trim(e))
        Set c = c.Offset(1, 0) 'next output row
    Next e
Next rw


A possible new mistake in K&R (second edition) that doesn't appear in any errata?

Question: I think I found  a new mistake in K&R (second edition).

At page 164, it is written that "feof" returns non-zero if "end of file" has occurred.
At page 170, it is written that "read" returns 0 when it reaches "end of file".
At page 176 K&R, there is written the definition of "feof".
At page 178 K&R, I think that the two conditions marked with red underscore in the definition of "_fillbuf" should be opposite.

Am I right?
Comment: Copyright violation? Nah, Fair Use. http://fairuse.stanford.edu/overview/fair-use/what-is-fair-use/ Also, it takes a bold man to call K&R off topic in a C group ;)
Comment: Looks good to me. read() returns 0, which is decremented to -1 before testing (--fp->cnt < 0). So if read() returns 0, fillbuf() sets EOF. Remember that read() returns -1 on error, which becomes -2 in fillbuf's test
Comment: @BjornA.External links can go bad. There should be enough information in the actual question here so nobody is required to click external links and so the question is useful even if they go bad. Even so, this is an extremely narrow question that's unlikely to help anyone with a real problem.
Comment: p.164 is correct. `feof` returns non-zero if EOF has occured (to be clear, if EOF condition exists as a result of the prior read). p.170 is correct in the sense that if you've read all the data from the file and try to read again (for the first time after reading all the data), the return of `read` will be 0. p.176 defines `feof` as indicating that the `_EOF` flag is present in the flags. And p.178 says that if `read` returns 0, then `--fp->cnt` will be -1, so `flags` will be set to `_EOF` since EOF condition is present. If `read` returns -1 (error), then _ERR. I don't see an inconsistency.
Comment: @RetiredNinja OP posted excellent links to copies of relevant parts of the book.
Comment: I'm voting to close this question as off-topic because that book is outdated since more than 18 years and we are neither the authors nor the publisher
Comment: You might actually ask a question about the issue you think you've found that may reference the book but doesn't actually require someone to read the book.
Comment: @BjornA.: Possibly violating copyright laws. Nevertheless the question is OT, see ^
Comment: @BjornA.: US copyright laws are not worldwide applicable. Although Disney & co would like to. And I did not say K&R per se is OT, but the post is. Please read comments carefully. Not ever question about a programming book/tool is on-topic per se.
Answer: I agree with both Bjorn A's comment and with lurker's comment — I don't see a problem with the code.
The specification of feof() on p164 corresponds to what the C standard says — although I've linked to the POSIX specification, it is intended to match the C standard.  The specification says that read() returning 0 indicates EOF; if it returns -1, then there was an error rather than simply EOF.  That much is non-controversial.
Note that what's on p176 is an implementation of feof(); it is not the implementation of feof().  There are other implementations that differ in detail from this one, though the net result is very much the same.
#define feof(p)  (((p)->flag & _EOF) != 0)

The macro is unexceptionable; it returns 1 if the _EOF bit is set in the flags, and 0 otherwise — that meets the expectations (requirements).
That leaves the sample implementation of _fillbuf() on p178.  The relevant code is:

fp->cnt = read(fp->fd, fp->ptr, bufsize);
if (--fp->cnt < 0) {
    if (fp->cnt == -1)
        fp->flag |= _EOF;
    else
        fp->flag |= _ERR;
    fp->cnt = 0;
    return EOF;
}
return (unsigned char)*fp->ptr++;

There are three cases to consider:

read() returns a positive number
read() returns zero
read() returns a negative number

In the first case, the code decrements fp->cnt which will be at least 0 so the final return is executed; a character is returned, correctly cast to unsigned char to ensure that the value is positive.
In the second case (EOF handling), the code decrements fp->cnt from 0 to -1, and enters the body of the outer if statement.  Since fp->cnt is currently -1, it sets the _EOF bit in fp->flag and the count back to zero and reports EOF.  This is correct.
In the third case (error handling), the code decrements fp->cnt from -1 to -2, and enters the body of the outer if statement.  Since fp->cnt is not -1, it sets the _ERR bit in fp->flag and the count back to zero and reports EOF.  This too is correct.
So, the code in K&R 2nd Edition is correct — you have not found a previously unreported erratum.


How could i place fire on top of every similar block in a large area? Bedrock

Question: In Bedrock Edition, I am making a dungeon full of traps, enemies, and puzzles. One obstacle I've been struggling to make is a fire trap.
The design I'm going for is a 2x2 tile of ancient debris that lights on fire and extinguishes on a cycle. I know that this is possible to create, but I am looking for a way to make it into a couple of command blocks that spread worldwide.
I've tried hiding entities around the blocks the fire trap but it never worked. I've tried making individual systems for every trap, but it takes up too much time and effort for the amount I want to include, and creates lag and delay between the traps.
Would there be a command system that can detect for every block in an area AND place fire above them? Thanks.
Answer: While I'm not aware of a command-based system that would achieve your objective the way you describe, it would certainly be possible to do this using entities and execute commands. The method I would use for this is below. I hope you find that it works for you and if you have any questions, please post a comment.
Method

First, put armour stands on top of the blocks you want the fire to appear on top of. Don't worry: You won't see them in the end result. I'm using end stone in my example but the block you use doesn't matter, since it's the armour stands that we're using to execute the commands (in fact, you could use the same block as the floor underneath your armour stands, making the fire trap totally invisible).

Next, you'll need to copy these commands into two command blocks. I'm activating them with a piston and a redstone block, but you can activate them however best suits your needs. I'll also explain how all of the commands in the method work at the end of my answer in case you don't know and want to but the commands you need are below.

Fire on: /execute @e[type=armor_stand, name=firetrap] ~ ~ ~ setblock ~ ~ ~ fire

Fire off: /execute @e[type=armor_stand, name=firetrap] ~ ~ ~ setblock ~ ~ ~ air

You may have noticed name=firetrap in the command. For the system to work, we need to name a name tag, 'firetrap' using an anvil and name all of the armour stands with it, so that they are all called 'firetrap'.

Finally, we need to do two things. We need to use the commands below to give our armour stands fire resistance so they don't burn and obviously invisibility.

Fire resistance: /effect @e[type=armor_stand, name=firetrap] fire_resistance 100000 255 true

Invisibility: /effect @e[type=armor_stand, name=firetrap] invisibility 100000 255 true

What the commands do

/execute @e[type=armor_stand, name=firetrap] ~ ~ ~ setblock ~ ~ ~ fire

Execute a command as all the armour stands within 100 blocks of this command block which are called 'firetrap'. Execute the command to set the block they are standing in as fire on behalf of them.

/effect @e[type=armor_stand, name=firetrap] fire_resistance 100000 255 true

Give all of the armour stands within 100 blocks which are called 'firetrap' fire resistance for 100000 seconds (normally it would be this number of seconds but the number 100000 means indefinitely) and with 255 intensity. Set hide particles to true.

Result


Create an iPhone app for personal use without using Xcode or going through the App Store

Question: I want to make a little app just for me. I don't want to distribute it, and don't want to make any money from it, I just need to have this app with me.
I don't have a Mac capable of running Xcode, and I don't want to waste any money on the developer license.
Is there a way I can make an app for only my personal iPhone 4s, without going through the App Store or using Xcode? My iPhone is jailbroken.
Comment: If the app is simple and you can spend some money, you can get it done on a freelancer site
Answer: A web app might be a better solution.
Comment: No, you can build an app with HTML5
Comment: I didn't know that, thank you! With [this](http://sixrevisions.com/web-development/html5-iphone-app/) little tutorial I think I will be able to do it!
Answer: The short answer is no. You would need a Mac/Xcode to compile/build the application for you. As @Thalecress suggested you might be better off building a web app.
Answer: Also check PhoneGap, with it you can deploy your web app in several platforms (including iOS, Android and WP7). Phonegap also offers a build service that you can use to wrap the final web app as a native app to run it on a device (PhoneGap:Buld).


Google Chrome Extensions Manifest 2 update

Question: I'm just wondering if there is a new way in manifest 2 to rewrite a sample app like this one.
http://developer.chrome.com/extensions/samples.html#4e35caa9742fb82dbd628892d23a781614f6eff6
I started to convert this into a manifest 2 app and ran into some issues.
bgPage.oauth.authorize(function() {
Uncaught TypeError: Cannot call method 'authorize' of undefined
  if (!bgPage.docs.length) {
    gdocs.getDocumentList();
  } else {
    gdocs.renderDocList();
  }
  util.scheduleRequest();
});

bgPage.oauth.sendSignedRequest(url, gdocs.processDocListResults, params);

For some reason in manifest2 the bgPad.oauth call is not valid anymore.
Is there a way to make this work again?
Comment: What error are you seeing in the console?
Comment: Uncaught TypeError: Cannot call method 'authorize' of undefined
Answer: I ran into this same problem when I converted my own app to manifest version 2. Firstly, I just want to make sure you're aware that you need to remove all inline code, and place it inside separate script includes. For example, popup.html has a whole lot of inline code; I moved it inside a popup.js and put that where the inline code was. (This must be done on background.html, popup.html, and chrome_ex_oauth.html
Secondly, due to Google's further tightening of permissions allowed within apps and extensions, you'll need to add this in your manifest:
"web_accessible_resources": [
  "chrome_ex_oauth.html"
]

I've zipped up my modified version of the extension for your edification:
https://dl.dropbox.com/u/73603348/gdocs.zip


Excel VBA - Looping to count cell values larger than / smaller than specific value

Question: I'm currently working with a large amount of contract lists. Each list is in a separate worksheet for each year's quarter and it needs to stay that way. E.g.: 2007_Quarter1, 2007_Quarter2, etc. I have 10 years of data, so 40 quarter report worksheets.
Now I need to code a vba routine that would do the following, in the specified order:

In each quarter report worksheet, run through the column containing contract values; then
Count all values between 0 and 10,000; then
Count all values between 10,001 and 25,000; and so on
Then, when there are no more contract values in the range (which will vary from sheet to sheet), go to the next worksheet and repeat the procedure.

All results should be returned in a worksheet (let's call it Worksheets("Report")) in a table where rows are for value intervals (e.g. 0 to $10,000) and columns are for quarters (e.g. 2007 Q1, 2007 Q2, etc.).
One particular aspect of my problem is that, for practical reasons, I'd prefer to set the control intervals' min and max values in a table contained in another worksheet ("Variables"), where, for example, I'd have all minimum values in range C4 down and all maximum values in range D4 down.
For each contract value, an "If" condition should look like:
If ContractVal > Worksheets("Variables").Range("C4").Value And
If ContractVal < Worksheets("Variables").Range("D4").Value Then ...

So far I'm having no success at coding this efficiently. I suspect some loop would work but I can't find a way to make it happen. A loop would do:
In 2007_Quarter1 ws:
For each cell from A4 down to the end, count values included between Range("C4").Value and Range("D4").Value
Then for each cell from A4 down to the end, count values included between Range("C5").Value and Range("D5").Value
... and so on, then repeat for 2007_Quarter2, 2007_Quarter3, and so on.
I need rescue! Thanks in advance!
Comment: Would the worksheet formula COUNTIF not suffice for this?
Answer: If it is ok to you to prepare the resulting matrix manually (intervals in rows and quarters in columns) you could write a macro that read the right file and count the contracts in the right range for every cell in the matrix.
If you want to build the matrix automatically you should tell the macro the year range. Then you can write a loop that read the ranges and for every range you write a loop to read every file in the right order.


Error trying to create a custom tag with Jakarta EE 10 and Jakarta Faces 4

Question: In the book "The Definitive Guide to Jakarta Faces in Jakarta EE 10: Building Java-Based Enterprise Web Applications" there is an example for creating a template using a custom tag and a .xhtml but when I try to run this example using Wildfly 27 and Jakarta faces 4, it throws this error:
Caused by: java.lang.RuntimeException: java.lang.RuntimeException: com.sun.faces.config.ConfigurationException: CONFIGURATION FAILED! Cannot invoke "org.w3c.dom.Document.getDocumentElement()" because "document" is null
    at firstname.lastname@example.com//io.undertow.servlet.core.DeploymentManagerImpl.deploy(DeploymentManagerImpl.java:257)
    at email@example.com//org.wildfly.extension.undertow.deployment.UndertowDeploymentService.startContext(UndertowDeploymentService.java:105)
    at firstname.lastname@example.com//org.wildfly.extension.undertow.deployment.UndertowDeploymentService$1.run(UndertowDeploymentService.java:87)
    ... 8 more
Caused by: java.lang.RuntimeException: com.sun.faces.config.ConfigurationException: CONFIGURATION FAILED! Cannot invoke "org.w3c.dom.Document.getDocumentElement()" because "document" is null
    at email@example.com//com.sun.faces.config.ConfigureListener.contextInitialized(ConfigureListener.java:247)
    at email@example.com//io.undertow.servlet.core.ApplicationListeners.contextInitialized(ApplicationListeners.java:187)
    at email@example.com//io.undertow.servlet.core.DeploymentManagerImpl$1.call(DeploymentManagerImpl.java:219)
    at email@example.com//io.undertow.servlet.core.DeploymentManagerImpl$1.call(DeploymentManagerImpl.java:187)
    at firstname.lastname@example.com//io.undertow.servlet.core.ServletRequestContextThreadSetupAction$1.call(ServletRequestContextThreadSetupAction.java:42)
    at email@example.com//io.undertow.servlet.core.ContextClassLoaderSetupAction$1.call(ContextClassLoaderSetupAction.java:43)
    at firstname.lastname@example.com//org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1430)
    at firstname.lastname@example.com//org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1430)
    at email@example.com//org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1430)
    at firstname.lastname@example.com//org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1430)
    at email@example.com//org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1430)
    at firstname.lastname@example.com//io.undertow.servlet.core.DeploymentManagerImpl.deploy(DeploymentManagerImpl.java:255)
    ... 10 more
Caused by: com.sun.faces.config.ConfigurationException: CONFIGURATION FAILED! Cannot invoke "org.w3c.dom.Document.getDocumentElement()" because "document" is null
    at email@example.com//com.sun.faces.config.ConfigManager.initialize(ConfigManager.java:319)
    at firstname.lastname@example.com//com.sun.faces.config.ConfigureListener.contextInitialized(ConfigureListener.java:179)
    ... 21 more
Caused by: java.lang.NullPointerException: Cannot invoke "org.w3c.dom.Document.getDocumentElement()" because "document" is null
    at email@example.com//com.sun.faces.config.processor.FaceletTaglibConfigProcessor.process(FaceletTaglibConfigProcessor.java:222)
    at firstname.lastname@example.com//com.sun.faces.config.ConfigManager.initialize(ConfigManager.java:310)
    ... 22 more

11:58:12,227 ERROR [org.jboss.as.controller.management-operation] (Controller Boot Thread) WFLYCTL0013: Operation ("add") failed - address: ([("deployment" => "jakartaee-hello-world.war")]) - failure description: {"WFLYCTL0080: Failed services" => {"jboss.deployment.unit.\"ROOT.war\".undertow-deployment" => "java.lang.RuntimeException: java.lang.RuntimeException: com.sun.faces.config.ConfigurationException: CONFIGURATION FAILED! Cannot invoke \"org.w3c.dom.Document.getDocumentElement()\" because \"document\" is null
    Caused by: java.lang.RuntimeException: java.lang.RuntimeException: com.sun.faces.config.ConfigurationException: CONFIGURATION FAILED! Cannot invoke \"org.w3c.dom.Document.getDocumentElement()\" because \"document\" is null
    Caused by: java.lang.RuntimeException: com.sun.faces.config.ConfigurationException: CONFIGURATION FAILED! Cannot invoke \"org.w3c.dom.Document.getDocumentElement()\" because \"document\" is null
    Caused by: com.sun.faces.config.ConfigurationException: CONFIGURATION FAILED! Cannot invoke \"org.w3c.dom.Document.getDocumentElement()\" because \"document\" is null
    Caused by: java.lang.NullPointerException: Cannot invoke \"org.w3c.dom.Document.getDocumentElement()\" because \"document\" is null"}}

First, I created the file apollo.taglib.xml in WEB-INF folder with this content:
<?xml version="1.0" encoding="UTF-8"?>
<facelet-taglib xmlns:="https://jakarta.ee/xml/ns/jakartaee"
                xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
                xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee
                https://jakarta.ee/xml/ns/jakartaee/web-facelettaglibrary_4_0.xsd"
                version="4.0">
  <namespace>com.saukisoft.apollo.tags</namespace>
  <short-name>a</short-name>
  <tag>
    <description>Vertical box.</description>
    <tag-name>vbox</tag-name>
    <source>tags/vbox.xhtml</source>
    <attribute>
      <description>The space between items.</description>
      <name>gap</name>
      <required>false</required>
      <type>java.lang.String</type>
    </attribute>
  </tag>
  <tag>
    <description>Horizontal box.</description>
    <tag-name>hbox</tag-name>
    <source>tags/hbox.xhtml</source>
    <attribute>
      <description>The space between items.</description>
      <name>gap</name>
      <required>false</required>
      <type>java.lang.String</type>
    </attribute>
  </tag>
</facelet-taglib>

then I created two templates in WEB-INF/tags:
hbox.xhtml
<ui:composition xmlns:ui="jakarta.faces.facelets">

    <ui:insert/>

</ui:composition>

vbox.xhtml
<ui:composition xmlns:ui="jakarta.faces.facelets">

    <ui:insert/>

</ui:composition>

and finally, added the context-param in web.xml file describing the new taglib.xml file:
...
  <context-param>
    <param-name>jakarta.faces.FACELETS_LIBRARIES</param-name>
    <param-value>/WEB-INF/apollo.taglib.xml</param-value>
  </context-param>
...

When starting Wildfly, the following error is thrown:
11:58:12,227 ERROR [org.jboss.as.controller.management-operation] (Controller Boot Thread) WFLYCTL0013: Operation ("add") failed - address: ([("deployment" => "jakartaee-hello-world.war")]) - failure description: {"WFLYCTL0080: Failed services" => {"jboss.deployment.unit.\"ROOT.war\".undertow-deployment" => "java.lang.RuntimeException: java.lang.RuntimeException: com.sun.faces.config.ConfigurationException: CONFIGURATION FAILED! Cannot invoke \"org.w3c.dom.Document.getDocumentElement()\" because \"document\" is null
    Caused by: java.lang.RuntimeException: java.lang.RuntimeException: com.sun.faces.config.ConfigurationException: CONFIGURATION FAILED! Cannot invoke \"org.w3c.dom.Document.getDocumentElement()\" because \"document\" is null
    Caused by: java.lang.RuntimeException: com.sun.faces.config.ConfigurationException: CONFIGURATION FAILED! Cannot invoke \"org.w3c.dom.Document.getDocumentElement()\" because \"document\" is null
    Caused by: com.sun.faces.config.ConfigurationException: CONFIGURATION FAILED! Cannot invoke \"org.w3c.dom.Document.getDocumentElement()\" because \"document\" is null
    Caused by: java.lang.NullPointerException: Cannot invoke \"org.w3c.dom.Document.getDocumentElement()\" because \"document\" is null"}}

Environment:

Java 17
Wildfly 27
Jakarta EE 10
Jakarta Faces 4
Answer: Reading the Jakarta Faces 4.0 documentation, in the examples they doesn't use the xmlns attributes in the taglib.xml file. So, when I removed those attributes from the root tag, it started to work and the war artifact was deployed without problems. It's weird but the solution was to remove all xmlns attributes from the facelet-taglib root tag:
  <namespace>apollo.tags</namespace>
  <short-name>a</short-name>
  <tag>
    <description>Vertical box.</description>
    <tag-name>vbox</tag-name>
    <source>tags/vbox.xhtml</source>
    <attribute>
      <description>The space between items.</description>
      <name>gap</name>
      <required>false</required>
      <type>java.lang.String</type>
    </attribute>
  </tag>
  <tag>
    <description>Horizontal box.</description>
    <tag-name>hbox</tag-name>
    <source>tags/hbox.xhtml</source>
    <attribute>
      <description>The space between items.</description>
      <name>gap</name>
      <required>false</required>
      <type>java.lang.String</type>
    </attribute>
  </tag>
</facelet-taglib>

Now it's up and running.


Django - get_object_or_404() takes at least 1 argument (0 given)

Question: I'm trying to create a page where I can delete an article using class based views. There is one problem, I am getting an error which says :
id() takes exactly one argument (0 given)

here is the code :
views.py
class DeleteView(View):
    def post(self, request, *args, **kwargs):
        article = get_object_or_404(Article, id=id)
        article.delete()
        return HttpResponseRedirect('/')

    def get(self, request, *args, **kwargs):
        article = Article.objects.get(id=kwargs['id'])
        context = {"article": article}
        return render_to_response("delete.html", context, context_instance=RequestContext(request))

template.html

<form action="{% url 'DeleteView' article.id %}" method="POST">
    {% csrf_token %}
    <input type="hidden" value="{{ article.views.id }}">
    <input type="submit" value="Delete">
</form>

urls.py
url(r'^delete/(?P<id>\d+)/$', DeleteView.as_view(), name="DeleteView"),

The faults are problably on : the views : line 3 | the template : line 2
I am missing something but I couldn't figure it out. How can I get through this problem?
Comment: where is `article_id` defined in the form?
Comment: @Pynchia I edited my post, I replaced it with `article = get_object_or_404(Article, id=id)` and it gets me another error
Comment: In `post` method `article = get_object_or_404(Article, id=id)` you are passing Python built-in `id` not from kwargs.
Answer: You need to pass the model class, so that the function knows what type of object it is trying to get.
article = get_object_or_404(Article, id=request.POST.get('article_id', ''))

Comment: I've already tried it but `article = get_object_or_404(Article, id=id)` gets me an error that says **id() takes exactly one argument (0 given)**
Comment: You still need to pass out the value of the id, just as you did originally.
Comment: I should've use kwargs['id'] insted of built in id, thanks for your help.
Answer: The problem is with your post method of DeleteView, there you are passing id which is a python built-in function rather you need to get the id from kwargs:
Problem:
class DeleteView(View):
    def post(self, request, *args, **kwargs):
        article = get_object_or_404(Article, id=id) # <--------

Solution:
class DeleteView(View):
    def post(self, request, *args, **kwargs):
        article = get_object_or_404(Article, id=kwargs['id']) # <--------

Answer: In post(), you're not passing the id kwarg, but you're passing the built-in function id. You need to use kwargs['id'] instead, as you did in get().


Aframe 3D Model not being rendered in Django project using static urls

Question: I wish to render .obj and .mtl files in my Django project using Aframe. What I am trying to achieve is to take some user input such as "Apple" and then an apple object is rendered on the screen. Now whenever I hardcode my url for the static file, I get the rendered object. But when I pass url in the dictionary after appending the input to the url, the object is not being displayed. Query is for eg: Apple. My dictionary is of the following format:
dict = {0 :['education/Apple.obj','education/Apple.mtl']}

My views.py :
from django.http import HttpResponse
from django.template import loader

def viser(request):
    template = loader.get_template('education/viser.html')
    context = {}
    context[0] = []
    context[0].append("'education/Apple.obj'")
    context[0].append("'education/Apple.mtl'")
    query = request.POST.get('inputquery', False)
    if query:
        template2 = loader.get_template('education/DOG.html')
        return HttpResponse(template2.render(context, request))
return HttpResponse(template.render(context, request))

Hardcoded DOG.html:

    {% load static %}

Dynamic DOG.html

    {% load static %}
    {% for classlabel, value in context.items %}

    {% endfor %}

One peculiar thing I observed during debugging was that whenever I tried a for loop in the hardcoded DOG.html file it did not let the browser render the object, but when I got rid of the for and the endfor tags, I got the rendered object. Is the for loop causing any problem in the program?
Peculiar DOG.html : Does not render the object

    {% load static %}
    {% for index, value in context.items %}

    {% endfor %}

Peculiar DOG.html after removal of for and endfor: Renders the object

    {% load static %}

Comment: `value[0]` and `value[1]` are not valid in Django template language. Just use `value.0` and `value.1`.
Comment: I tried doing that but no 3D object (Apple) is being rendered on the browser. But when I hardcode the path in the static 'education/Apple.obj', it's getting rendered without any problem. What am I doing wrong?
Comment: In that case, [edit] your question and show your updated code. I would also tryviewing the source of the rendered html in your browser, and see what the difference is between hardcoding the value and using the static tag.
Comment: @Alasdair I have updated the question as you asked sir. Any pointers, suggestions or help would be immensely appreciated.
Answer: You are getting some of the basics of Django templates wrong. Before you try to get your aframe code or the static tag to work, make sure that you can access the variables in your context dictionary correctly.
You have are rendering a template with a context:
context = {0 :['education/Apple.obj','education/Apple.mtl']}

You shouldn't use 0 as a context variable name. Change it to something else, e.g. obj_list.
From your code, it looks as if you are going to have lots of  tags, so you actually want a list of lists.
context = {}
context['obj_list'] = []
context['obj_list'].append(['education/Apple.obj', 'education/Apple.mtl'])

This will give you a context dictionary like:
context = {'obj_list' :[['education/Apple.obj','education/Apple.mtl']]}

Next, you don't use context in the template itself, you use the keys of the context dictionary. In this case you dictionary has a single key obj_list, so your loop can be something like:
{% for item obj_list %}
    {{ item.0 }}
    {{ item.1 }}
{% endfor %}

Once you have that working, you can start using the variables with the static tag and aframe.
Comment: One last question, You mentioned that I am going to have multiple  tags in my Template. That's true, but what if I enter something like "Apple and Strawberry" then my dictionary would look something like this 'dict ={'obj_list':[['apple.obj','apple.mtl'],['strawberry.obj','strawberry.mtl']]}' then can I use item.2 to give me 'strawberry.obj' and If I can't is there another way or a better way of doing so? And if I have multiple keys, what will the for loop look like?
Comment: You can either use `{{ obj_list.1.0 }}` and `{{ obj_list.1.1 }}` to access the values from the second list `['strawberry.obj','strawberry.mtl']`. Or, you can loop through the list with `{% for item in obj_list %}` and use `{{ item.0 }}` and `{{ item.1 }}` inside the loop. On the second loop, `item` will be list `['strawberry.obj','strawberry.mtl']`.


Range Not working correctly

Question: I am trying to use [Range(1f,3f)] in front of my int in unity so that I can get a slider in my inspector. But it gives an error that says "The namespace name Range could not be found. Are you missing a using directive or assembly reference". With every example I find no one does it different then me, could it be because I use an older version of Unity? And how can I make it possible in this version or is that impossible?
using UnityEngine;
using System.Collections;

[ExecuteInEditMode]
public class AssignMaterial : MonoBehaviour {

    public bool assignMaterial;
    [Range(1, 3)] public int matId;

    void Update()
    {
        if(assignMaterial)
        {
            switch(matId)
            {
                case 1:
                this.renderer.material = Resources.Load("NodeMaterial" + matId.ToString()) as Material;
                break;
                case 2:
                this.renderer.material = Resources.Load("NodeMaterial" + matId.ToString()) as Material;
                break;
                case 3:
                this.renderer.material = Resources.Load("NodeMaterial" + matId.ToString()) as Material;
                break;
            }
        DestroyImmediate(this);
        }
    }
}

Comment: Why are you trying to limit a `int` with `floats` ? And do you have `using UnityEngine;` In the top of the script?
Comment: O sorry my mistake no I am using ints wasnt thinking when I typed it here, but yes I have using UnityEngine; in the top
Comment: old version of unity? Which version exactly?
Answer: I think it might be the case that this is a not supported in the version you are using.
The lowest version I could confirm myself with the range attribute implemented was unity 4.2
Alternatively to the range attribute you could make a editor script instead. With a line saying something like:
AssignMaterial.matID = (int)EditorGUILayout.Slider(AssignMaterial.matID, 0, 3);

small side note
You might want to get some try/catches in there. As it is right now, if there is no renderer attached to the object. You will freeze up unity for a bit, while it is better to catch this error and dispose of the process if this is not assigned.

Range Not working correctly


how do I make pyinstaller use python 2.7 when I also have 3.5?

Question: It seems to automatically use the latest version, and I haven't been able to find the answer in the pyinstaller documentation. It complains that my python2 code has incorrect syntax but it does not.
    Traceback (most recent call last):
      File "/usr/bin/pyinstaller", line 11, in <module>
        load_entry_point('PyInstaller==3.2', 'console_scripts', 'pyinstaller')()
      File "/usr/lib/python3.5/site-packages/PyInstaller/__main__.py", line 90, in run
    run_build(pyi_config, spec_file, **vars(args))
  File "/usr/lib/python3.5/site-packages/PyInstaller/__main__.py", line 46, in run_build
    PyInstaller.building.build_main.main(pyi_config, spec_file, **kwargs)
  File "/usr/lib/python3.5/site-packages/PyInstaller/building/build_main.py", line 788, in main
    build(specfile, kw.get('distpath'), kw.get('workpath'), kw.get('clean_build'))
  File "/usr/lib/python3.5/site-packages/PyInstaller/building/build_main.py", line 734, in build
    exec(text, spec_namespace)
  File "<string>", line 16, in <module>
  File "/usr/lib/python3.5/site-packages/PyInstaller/building/build_main.py", line 212, in __init__
    self.__postinit__()
  File "/usr/lib/python3.5/site-packages/PyInstaller/building/datastruct.py", line 178, in __postinit__
    self.assemble()
  File "/usr/lib/python3.5/site-packages/PyInstaller/building/build_main.py", line 413, in assemble
    priority_scripts.append(self.graph.run_script(script))
  File "/usr/lib/python3.5/site-packages/PyInstaller/depend/analysis.py", line 144, in run_script
    self._top_script_node = super(PyiModuleGraph, self).run_script(pathname)
  File "/usr/lib/python3.5/site-packages/PyInstaller/lib/modulegraph/modulegraph.py", line 888, in run_script
    co_ast = compile(contents, pathname, 'exec', ast.PyCF_ONLY_AST, True)
  File "/home/chuck/Pictures/testpics/photoresize.py", line 59
    print "incorrect options please choose from d(irectory),s(ize),e(xtension),r(ecursive) or use defaults"
                                                                                ^
SyntaxError: invalid syntax

Comment: have you tried setting the path locally to python 2?
Comment: no I dont know how to do this but i like this idea better than reinstalling python2 in a virtual env to avoid python3 conflicts. I will google 'how to set the path locally to python2' and then I guess I just change it back when I'm done? I'm not sure how this would affect other programs or the OS
Answer: Perhaps use virtualenv, or
virtualenvwrapper
With virtualenv it's possible to create separate environments with different versions of Python.
virtualenvwrapper is wrapper for virtualenv some how easier to work with.
Comment: I may need to do this but I really just want one program to run using python2.7 one time, so, seems like a lot of installing just for one time use
Comment: That is how I did installation:
Comment: **sudo apt-get install python-pip**, **sudo pip install --upgrade virtualenv**. Man page for virtualenv [here](http://manpages.ubuntu.com/manpages/trusty/man1/virtualenv.1.html). Take a note of -p and --system-site-packages.
Comment: sorry I should have mentioned I'm using arch linux so I dont have apt-get I have pacman. I also would prefer to not dive into virtual environments for a one time use
Answer: Since you're not willing to install a virtual environment as you commented, an easy workaround would be:

locate the path where python 2.x is installed ex: (not sure): /usr/local/lib/python2.7
open a console
type PATH=/usr/local/lib/python2.7:$PATH
type python --version just to check that it says V2 something not V3
run your pyinstaller executable with the python prefix

That doesn't affect system path (local to the console), so no need to revert back to previous path settings. Just close the console when you're done.
Also, don't use sudo as it's not needed and it changes/resets the path, which was your problem as you confirmed.
Comment: /usr/bin/python2.7
/usr/lib/python2.7
/usr/include/python2.7
Comment: check the directory you're targetting: it must exist (of course!) and must contain an executable file named `python`
Comment: doesn't seem to work :(

[chuck@PSYCH testpics]$ PATH=/usr/bin/python2.7:$PATH
[chuck@PSYCH testpics]$ sudo pyinstaller photoresize.py
[sudo] password for chuck:
47 INFO: PyInstaller: 3.2
48 INFO: Python: 3.5.2
48 INFO: Platform: Linux-4.8.13-1-ARCH-x86_64-with-arch
Comment: what does `python --version` gives you? Oh, the `sudo` part may be a problem since it changes the path. Are you sure you need `sudo` prefix?
Comment: interesting, I did not know that sudo changes the path. you're right I don't need to use sudo and it worked fine without it. thank you.
Comment: I'm on arch linux so python --version gives 3.5 and python2 --version gives 2.7 fyi


Does it make a difference how many of the Emperor's bonus objectives you complete?

Question: Tie Fighter extended on X-Wing in that it had not only primary and secondary objectives, but also bonus objectives, given out by an advisor of the Emperor.
Unlike the other ones, the bonus objectives are mostly hidden in their explicit form ("Identify freighter X") until completed. You pretty much had to derive them from the briefing and the debriefing (these usually contained some spoilers, assuming you failed the mission). The only hard value you could see was the number of these objectives ("you completed 1/6 bonus objectives").
I find it often quite hard to figure them all out and complete them all. Yet I do try to complete at least some of them and I do rise in the Emperor's ranks.
Does that mean the game only keeps track of you completing at least one on each mission? (Or how many necessary for the advisor to give you a positive debriefing.) Do you rise in the ranks faster if you complete more? Is it worth going through the extra effort to do them all?
Note: of course I am aware that you do not get any real in-game benefits from working for the Emperor at all. The game is from a time when gamers could still be motiviated without these cheap tricks. ;) The cutscenes are the reward, I guess.
Answer: I am playing the game now and I can tell you that user7429 is correct. The hooded figure gives you the secondary objectives in most cases and the bonus are still shrouded in mystery.
I also believe that the ranks you get with the emperor are tied to your total score and not bonus objectives. The more bonus objectives you find the higher your score, however. I remember the last time I played through the game I never achieved full rank with the emperor because my cumulative score was not very high as using reinforcements decreases your score.
EDIT: Also dying without being recovered by the empire will destroy your score.
Answer: In my experience, it appears that progress in the Emperor's ranks is in fact based purely on score, but the score requirements provided in the doc Jason links too are not accurate (they are too high - I just got initiated into the fourth circle with just over 400,000 points).
With regards to bonus objectives, these were not provided by the emperor's advisor (a.k.a the cloaked figure). The "cloaked figure" provided you with the secondary objectives, and the flight officer provided you with the primary objectives. You would get a positive debriefing from the flight officer only if you completed ALL the primary objectives, and a positive debriefing from the "cloaked figure" only if you completed ALL the secondary objectives.
I think the only thing completing bonus objectives got you was a small red-and-gold medal in each mission where you completed all of them. There was usually no obvious way to determine what the bonus objectives were from the mission briefings. You'd basically have to guess or happen upon them by chance. That being said, after successfully completing a mission you could replay it in the combat simulation chamber, where all bonus objectives would be displayed up front. You could then use this knowledge in your second playthrough of the game to get them all ;)
Comment: Good thinking with the combat simulation chamber, that's really a good way to find them all. I believe you're wrong about primary and secondary objectives, though.
Answer: I searched and I searched, but I just could not find an answer to this question, and I wish I had the time to play TIE Fighter again, in order to do some original research, but ...
Anyway, the best information I could find is here, near the end of the document.  If this is correct, it would indicate that promotions in the Emperor's ranks occur due to your cumulative score, but there is no indication as to whether you must complete a bonus objective in each mission in order to receive a promotion, or if only completing a single bonus objective (in order to start the process) is enough.
If your rank is based on your score, then completing more bonus objectives will cause you to rise in the Emperor's ranks faster, as each objective completed increases your score for that mission.
Comment: Interesting, I wonder how many bonus objectives are needed to reach the highest rank at the end of the campaigns.


In Mercenaries mode, is there a way to see how many tasks a mercenary has completed?

Question: In Hearthstone's Mercenaries mode, each mercenary has 18 tasks that they can complete for rewards. When a mercenary is visiting your campfire, you can see their current task and make progress toward it. However, when a mercenary is not at your campfire I don't see any way to see how many of their 18 tasks they have completed.
Is there a way to see how many tasks a mercenary has completed? Is there a way to see which mercenaries have completed all 18 of their tasks?
Answer: I don't know if anyone else would be looking for the answer for that question, but just in case:
At the fireplace screen, you can switch tab to see current personal quest of each mercenary. Simply scroll down for the list of those grayed-out mercs with all quests finished.


How to enable php extension intl programmatically

Question: I have to convert the amount in words in Yii2. I used
<code>Yii::$app->formatter->asSpellout('125');
</code>
to convert. I have enabled intl extension in the php.ini file. The same thing I want to use in the server too. Is there any way to enable the intl extension via code?
Answer: If you have enabled the extension in php.ini it is available to you on your server.
If by server you mean a different server (you local PC is also a server in this case), you cannot enable extension programmatically and will have to contact your hosting provider for the same.


Do green numbers on icons in the dock mean I should be doing something?

Question: I just now upgraded from Ubuntu 22.10 to Ubuntu 23.04 using the GUI upgrade tool.
Since the upgrade, little green circles with numbers have appeared in the upper right corner of some of the icons in the Dock. For example:

The Files icon has a green circle with '3' in it, even when I don't have a Files folder open.
Firefox does not have any green circle/number on it when it is not open, but when I run a single instance of Firefox a green '2' appears.
Calculator does not have any green circle/number on it at any time, whether it is open/running or not.

In a search, I have not been able to find documentation of this.
The behaviour is a little like what is described in this user's question: What do the RED numbers on the Gnome Files Dock Icon mean?
...but the numbers are not consistent with the number of GUI windows I have open and are not shown at all for some apps.
Please could the community advise:

What do these numbers mean?
If they mean I'm supposed to do something, then what do I do to address that 'something'?
If they are not useful, how do I turn them off?

Thanks for your time!
Answer: Those are notifications.
Click on the date/time to see them.
Comment: @OrganicMarble I had one saying that the SD card drive was removed.
Comment: Thank you!! Following your advice I discovered old notifications for USB storage devices being removed (the File notifications) and a notification that Snap wanted me to close Firefox to do an update. Once I'd cleared those notifications, the green circles/numbers went away as would be expected.
Comment: What "notifications" does the file manager give?
Comment: Great example!!
Comment: Where is the date/time? In the Dock? When I open the Files program? I don't see any more green circles when I open the Files application.
Comment: Thanks. After clicking on the date/time, I saw that there was a "Do Not Disturb" switch. I turned it on, and hey presto: no more green circles!
Comment: Also there is a button to clear notifications.
Comment: You know it's confusing UX when you end up on "askubuntu"..... they should at least have a tooltip to say what it is!


Cucumber6 witn Java11 Datatable transformation into List of Enums

Question: I updated project from Cucumber4 > Cucumber6 and from JDK8 > JDK11. Problem is with a couple of tests that I have. I have scenario:
    Then Relevant link on Checkout page is valid
    # LinkType enum
    | LOGO | LOGIN | TERMS | PRIVACY_POLICY | CONTACT | FAQ |

Code implementation is:
    @Then("^Relevant link on Checkout page is valid$")
    public void relevantLinkOnCheckoutPageIsValid(DataTable dataTable) {
    List<LinkType> links = dataTable.asList(LinkType.class);

And this was working until update. Problem is that old transformation is not working anymore and I didn't found how to add new transformer so I can transform dataTable to list of enums that I have.
Can someone suggest something or maybe link for some documentation where I can check what to implement?
Comment: Did you define a datatable type for the enum? https://github.com/cucumber/cucumber-jvm/tree/main/java#data-table-type
Comment: And what is the error you get?
Comment: Hi @M.P.Korstanje, error that I'm getting is

`Step failed
io.cucumber.datatable.UndefinedDataTableTypeException: Can't convert DataTable to List.
Please review these problems:

 - There was no table entry or table row transformer registered for ch.tamedia.model.constants.LinkType.
   Please consider registering a table entry or row transformer.`

Problem is that I don't have datatable type for this enum. It is not clear to me what and how to return values from that method? Should I just rerutn enum value from provided string?
Answer: https://github.com/cucumber/cucumber-jvm/tree/main/java#data-table-type
Something like this should do the trick:
@DataTableType
public LinkType linkType(String cell) {
    return LinkType.valueOf(cell);
}

@Then("^Relevant link on Checkout page is valid$")
public void relevantLinkOnCheckoutPageIsValid(@Transpose List<LinkType> links) {

}

The data table type will transform each table cell into a instance of a LinkType enum. Then in the step definition the @Transpose annotation will transpose the table so that it is now a vertical list rather then a horizontal one. Then Cucumber will use the data table type to transform the individual cells into a List<LinkType>.
You can also use:
List<LinkType> links = dataTable.transpose().asList(LinkType.class);

Comment: This one is problem solver. Just to mark that annotation is @Transpose, but it is trivial change. Thanks a lot for helping :beer:


Microservices and maven structure

Question: I'm really confused how someone would build some micro-services with Maven. I've seen a lot of project using the multi-module strategy

Is that a valid strategy? wouldn't that couple the whole project? because I will need to build the project from root (parent pom.xml)? and everything is related to everything I think

Should I just build everything in their own?

firstapplication

seconddapplication

thirdapplication

Any help is really appreciated.
I'm really lost on how this works
<code>[ parentpom.xml ]
|
|___first-application
|   |
|   |__ data-layer
|   |   |__ pom.xml
|   |
|   |__ services
|   |   |__ [[ USES message-queue:producer ]]
|   |   |
|   |   |__ pom.xml
|   |
|   |__ domain
|   |   |__ pom.xml
|   |
|   |__ application (REST)
|   |   |__ pom.xml
|   |
|   |__ pom.xml
|
|___second-application
|   |
|   |__ data-layer
|   |   |__ pom.xml
|   |
|   |__ services
|   |   |__ pom.xml
|   |
|   |__ domain
|   |   |__ pom.xml
|   |
|   |__ application (REST)
|   |   |__ pom.xml
|   |
|   |__ pom.xml
|
|___third-application
|   |
|   |__ data-layer
|   |   |__ pom.xml
|   |
|   |__ services
|   |   |__ [[ USES message-queue:consumer ]]
|   |   |
|   |   |__ pom.xml
|   |
|   |__ domain
|   |   |__ pom.xml
|   |
|   |__ application (REST)
|   |   |__ pom.xml
|   |
|   |__ pom.xml
|
|
|___message-queue (as wrapper of kafka/rabbit/etc)
|   |
|   |__ configuration_of_message_queue
|   |   |__ pom.xml
|   |
|   |__ consumer
|   |   |
|   |   |__ [[ USES message:queue:configuration ]]
|   |   |
|   |   |
|   |   |__ pom.xml
|   |
|   |__ producer
|   |   |
|   |   |__ [[ USES message:queue:configuration ]]
|   |   |
|   |   |
|   |   |__ pom.xml
|   |
|   |__ pom.xml
|
|
|___ commonlibrary (some projects use this, some others dont)
    |__ pom.xml
</code>
<code><parentpom>
  <modules>
    <module>first</module>
    <module>second</module>
    <module>third</module>
    <module>message-queue</module>
    <module>commonlibrary</module>
  </modules>
</parentpom>
</code>
Comment: I think this will help you.
Answer: What you are signalling is at if monorepo is a good strategy or multi- repo (repo per service/library).
Note:

Each independent repo or same repo can be itself multimodule project itself.

There is already a huge debate on mono vs multi repo.
Both are good fit for microservices.
Lots of things become influencing factor for this decision.

How are you going to write devops pipelines.
how you want to structure your builds.
Team requirements - is it okay for multiple teams/members committing in same repo for per microservice/team structure.

If you are going for monorepo(single repository all microservices+ libs)

You see all code at one place.
Easy to collaborate as codebase is same.
Easy to build and fix if any issues as its single codebase
Easy to control build lifecycle - ie libs will be built in order first then microservices.
Sometimes you will run in conflicts and issues if multiple teams are committing in same codebase.
However, all teammates must follow some standards, practices and guidlines when many people are working on same repo. It is very essential to have proper procedure for commit, build and release.

If you are going for multi repo(repository per ms and libs)

You need to ensure you build separate project with dependencies in order you want.
Build pipelines will be configured separately and cross dependencies will be there.
You will have additional overhead to maintain separate projects.
Debugging can be little difficult sometimes.
Teams/members will collaborate and have responsibility to maintain their own repository. If that repo breaks, that repo and its build breaks.
You need to ensure you publish your dependencies first and build them then work on your microservices.
Its good if you have enough bandwidth to maintain multiple repositories.

Essentially both are good approaches depending on your team structure, maturity and model that you feel comfortable.
I am following monorepo for our services, following is the structure.
<code>├── README.md
├── db
│   └── create-dbs.sh
├── docker-compose.yaml
├── docs
│   ├── 1. Prerequisites.md
│   ├── 2. Documentation.md
│   ├── 3. Running services.md
├── pom.xml
├── services
│   ├── books-service
│   └── products-service
├── shared
│   ├── archunit-tests
│   ├── auditing-utils
│   ├── project-bom
│   ├── event-publisher
│   ├── logging-utils
│   ├── rest-clients
│   └── utils
└── templates
    └── azure-template
</code>
Few recommendations for you:

You can have a bill of materials for all services(bom) in libraries.
You can have separate folder for services, libraries, documentation and so on.
The parent pom can build whole project with libraries first then services.
All folders need not be maven project, can be just simple folders.

Microservices and maven structure


Unable to run notify-send from cronjob

Question: In my Kubuntu 22.04, a script run by my crontab uses notify-send. However, it doesn't work: there is no pop-up appearing. If I redirect the output (stderr in particular) of the script to a file, this error is printed:
Error calling StartServiceByName for org.freedesktop.Notifications: Timeout was reached

If instead I run notify-send directly from a cronjob,
0 * * * * env DISPLAY=:0.0 notify-send --expire-time=0 --app-name="Test" 'Test text' 1>/tmp/out1 2>/tmp/out2

out1 and out2 are empty; however, this doesn't work as before. The pop-up does not appear.
Is there a way to make notify-send work as expected?
Answer: I guess for notify-send to work in a cron job you have to copy the environment variable DBUS_SESSION_BUS_ADDRESS from your current desktop session and set it in the cron job. Also, notify-send must run as the same user who is currently logged in to the desktop session.
At least that works for me.
Comment: The user is the same. After also setting `DBUS_SESSION_BUS_ADDRESS` it works. Thank you!

Unable to run notify-send from cronjob


Boot directly to Windows instead of Windows Boot Manager

Question: I have installed Ubuntu 16.10 alongside Windows 10, both systems on one physical SSD. Grub has detected both systems, but the problem is, Windows is not booted directly.
I have to choose "Windows Boot Manager" option, then the pc is restarted and Windows booting sequence start.
What I want, is to skip the "restarting" part. I tried adding Windows 10 to grub manually but I am sure I did it wrong.
Any advice how to do it correctly?
Output of fdisk -l
Device         Start       End   Sectors   Size Type
/dev/sda1       2048    206847    204800   100M EFI System
/dev/sda2     206848    239615     32768    16M Microsoft reserved
/dev/sda3     239616 437651455 437411840 208,6G Microsoft basic data
/dev/sda4  499093504 500117503   1024000   500M Windows recovery environment
/dev/sda5  437651456 482492415  44840960  21,4G Linux filesystem
/dev/sda6  482492416 499093503  16601088   7,9G Linux swap

I tried adding it manually but I am not sure which options are correct, this was just trial and error
set root=(hd0,3)
chainloader +1

And this one is for Windows Boot Manager (this one is generated by grub so it works)
insmod part_gpt
insmod fat
set root='hd0,gpt1'
if [ x$feature_platform_search_hint = xy ]; then
  search --no-floppy --fs-uuid --set=root --hint-bios=hd0,gpt1 --hint-efi=hd0,gpt1 --hint-baremetal=ahci0,gpt1  A68D-8D4A
else
  search --no-floppy --fs-uuid --set=root A68D-8D4A
fi
chainloader /EFI/Microsoft/Boot/bootmgfw.efi

Comment: First of all, your PC doesn't "restart", Grub chainloads the Windows Boot Manager as expected and that's all. Secondly, you need to understand UEFI and stop retrofitting old methods that are applicable to the old Legacy/BIOS only. With UEFI you can boot any installed OS directly from UEFI settings by changing the boot order.
Comment: I know I can change boot order in UEFI but I want grub to start loading windows directly if that's possible. If it uses windows boot manager it show my loading screen (Acer logo) first, and that's unnecesary delay when booting
Comment: Please read and understand this before anything else: https://help.ubuntu.com/community/UEFI . Now that you do understand it please use the technologies as they were/are designed instead of retrofitting. For your case you should boot Windows directly from the UEFI boot menu entry for Windows in order to avoid Grub. Doing anything else is overcomplicating something that's so simple and it may have unintended results.
Comment: Ok then, guess I'll just reinstall both systems and choose bios instead of uefi.
Comment: I advise against re-installing both OSes; that's a lot of hassle and creates new opportunities for new things to go wrong. Without knowing *how* the boot to Windows is failing, it's hard to be sure what's wrong; but see my answer below for my initial guess and suggested fixes.
Answer: You don't say what happens when you try booting using the auto-generated Windows entry in the GRUB menu, but my suspicion is that you're running into the following long-standing bug:
https://bugs.launchpad.net/ubuntu/+source/grub2/+bug/1091464
If so, there are a couple of relatively simple workarounds:

Disable Secure Boot. How to do this varies from one computer to another, but it's usually pretty simple once you know how. See this page of mine for a few illustrated examples.
Install rEFInd. My rEFInd boot manager does a better job of launching Windows than GRUB, and so may be helpful. One caveat is that you'll need to jump through some hoops with EFI Secure Boot key installation to get rEFInd to start up with Secure Boot active.
Comment: I'll look into it soon. I wouldn't say it's a bug, for me it's just inconvenient way to boot to windows. On my old Sony notebook with BIOS it showed GRUB where I have option to boot to ubuntu or windows. By choosing windows, It starts booting windows. On my new Acer notebook with UEFI, It shows Acer logo then grub appears with options for ubuntu and windows boot manager, When I choose Windows, it shows acer logo again and starts booting windows. It just looks like restarting. That's what I want to get rid of


Table design Cassandra

Question: I am persisting data from a machine which lets say has different sensors.
CREATE TABLE raw_data (
    device_id uuid,
    time timestamp,
    id uuid,
    unit text,
    value double,
    PRIMARY KEY ((device_id, unit), time)
)

I need to know which sensor was using when the data was sent. I could add an field "sensor_id" and store sensor related data in an other table. Problem about this approach is that i have to store the location of the sensor (A,B,C) which can change. Changing the location in the sensor table would invalidate old data.
I have a feeling that im still thinking to much in the relational way. How would you suggest to solve this?
Answer: Given your table description, I would say that device_id is the identifier (or PK) of the device,
but this  is not what you apparently are  thinking...
And IMHO this is the root of your problem.
I don't want to look pedant, but I often see that people forget (or do not know) that in relational model, a relation is not (or not only) a relation between tables, but a relation between attributes, ie. values taken in  "domain values", including the PK with the PK (cf the relational model definition of Codd that you can easily find on the net).
In relational model a table is a relation,  a query (a SELECT in SQL, including joins) is also a relation.
Even with NoSQL,  entities should (IMHO) follow at least the first 3 normal forms (atomicity and dependence on pk for short) which are more or less minimal common sense modeling.
About PK, in the relational model, there are flame debates on natural versus subrogates (unnatural calculated) primary keys.
I would tend to natural, and often composite,  keys, but this is just an opinion, and of course it depends on context.
In you data model unit should not (IMHO) be part of PK : it does not identify the device, it is a characteristic of the device.
The PK must uniquely identify the device, it is not a position or location, a unit or any other characteristic of the device. It is a unique id, a serial number, a combination of other characteristics with is unique for the device and does not change in time or any other dimension.
For example in the case of cars with embedded devices, you have the choice of giving an opaque  uuid PK for each embedded device with a reference table to retrieve additional information about the device, and a composite PK which could be given by : car maker, car serial number (sno), device type , device id .
like for  example :
CREATE TABLE raw_data (
    car_maker text,
    car_sno text,
    device_type text,
    device_id text,
    time timestamp,
    id uuid,
    unit text,
    value double,
    PRIMARY KEY ((car_maker, car_sno, device_type, device_id), time)
)

example data :
( 'bmw', '1256387A1AA43', 'tyrep', 'tyre1', 'bar', 150056709xxx, 2.4 ),
( 'bmw', '1256387A1AA43', 'tyrec', 'tyre1', 'tempC',150056709xxx, 150 ),
( 'bmw', '1256387A1AA43', 'tyrep', 'tyre2', 'bar', 150056709xxx,2.45 ),
( 'bmw', '1256387A1AA43', 'tyrec', 'tyre2', 'tempC', 150056709xxx, 160),
( 'bmw', '1256387A1AA43', 'tyrep', 'tyre3', 'bar', 150056709xxx,2.5 ),
( 'bmw', '1256387A1AA43', 'tyrec', 'tyre3', 'tempC', 150056709xxx, 150 ),
( 'bmw', '1256387A1AA43', 'tyre', 'tyre4', 'bar', 150056709xxx,2.42 ),
( 'bmw', '1256387A1AA43', 'tyre', 'tyre4', 'tempC', 150056709xxx, 150 ),

This is a general thought and must align to your problem. Sometimes, uuids and calculated keys are best.
With Cassandra the difficulty is that you have to design your model around your queries, because the first part of the PK  is the partition key and you cannot query (or it is difficult, you have to paginate or use other system like spark) between multiple partitions.
Don't think relational too much, don't be afraid to duplicate.
And I would  suggest that you also have look at Chebotko diagrams for Cassandra who can help you design your Cassandra schema around queries here or here .
best,
Alain
Comment: Thanks. Maybe i expressed myself not clearly enough. In my example "raw_data" is the table for incoming sensor data. I added "unit" as part of the primary key, because currently the data is queried by "deviceId" AND "unit". I see that for queries by "deviceId" only i would replicate the data to an other table having "deviceId" as the only PK

Table design Cassandra


Best practices for doing accounting in Python

Question: I am writing a web2py application that requires summing dollar amounts without losing precision.  I realize I need to use Decimals for this, but I've found myself having to wrap every single number I get from the database with:
Decimal(str(myval))
Before I go crazy adding that to all of my code, is there a better way?  I'm new to Python, so it's very possible that I am overlooking something obvious.
Edit: My database is MS SQL Server and I'm storing the amounts in SQL Server money fields (I believe the implementation is analogous to Decimal, ie integer math, not floating point).
I am connecting to the db through the web2py framework (which uses pyodbc for SQL Server connections).  I believe web2py has some support for decimal types. For example, my web2py field definitions look like: Field('Amount','decimal(19,4)')  However, when I return a value from the database using web2py's .executesql method it returns the value as a float and not a Decimal.
Edit: This appears to be an issue with FreeTDS and MS SQL Server.  As Massimo stated in the comments, web2py supports this properly and returns a Decimal (if it can).  It turns out this is only an issue in my production environment (Linux).  I am using the FreeTDS driver to connect to MS SQL and it appears to be translating the MS SQL money type to a python float.
I think Alex Martelli's answer is pointing in the right direction.  Does anyone have any experience with FreeTDS, MS SQL, and python?  I think this probably warrants its own question, so I'll move this discussion... (new question posted here: FreeTDS translating MS SQL money type to python float, not Decimal)
Update:  There was in fact a bug in FreeTDS.  This was fixed in the CVS head of FreeTDS as of August 4, 2010.
Comment: Please bring this up on the web2py mailing list. It should return a decimal not a float. Either some setting is wrong or there is a bug to be fixed. Either case we can resolve it in 24hrs if you bring it up there and help us with testing.
Comment: I double checked the source code and confirm that on mssql 'decimal' is mapped into NUMERIC(...) and on retrieval it does return a decimal.Decimal (it check the return value from the db).
Comment: Massimo, you are correct.  This works fine for me in my development environment (Windows) but breaks in my production environment (Linux).  The problem appears to be FreeTDS, not pyodbc or web2py.
Answer: First, keep all numbers in decimal form in the database -- you don't mention what DB engine you're using, but every engine supports such functionality, e.g., here is MySQL's DECIMAL type documentation.  I hope you're already doing that, but, if you aren't, it's still worth the pain of a schema change.
Then, you need to ensure the type conversion to and from the DB matches the database's decimals with Python's.  Unfortunately there is no standard way to do it across DB-API implementations, but most do offer a way; for example, with MySQLDB you need to pass a conv= parameter in connect, known as a "type converters dictionary" -- the default is a copy of MySQLdb.converters.conversions but of course you can enrich it to do the right thing with decimals.  If you tell us which DB you're using, and what DB-API connector package you prefer for it, we may be able to give you more detailed help on this subject.
Edit: @unutbu remarks in a comment that the current MySQLdb converter already does translate decimals correctly, so, unless you're stuck with a very old release of MySQLdb, you should be fine as long as you do correctly keep all the numbers as decimal in the DB (yay!).
Comment: MySQLdb's default converter `MySQLdb.converters.conversions` automatically converts data of MySQL Decimal type to Python decimal.Decimals.
Comment: @unutbu, that's good news -- it didn't when I last used MySQLdb, but then that was a pretty old release and might have needed to avoid such conversion to support very old Python releases.
Comment: Is there a pyodbc equivalent to the MySQLDB conv= parameter and MySQLdb.converters.conversions?
Answer: You could write a function which both gets the number from the database and then converts it to decimal. Then just use that in your code.


If i start a new Application then this error is showing. How i can resolve it

Question: Error:Execution failed for task ':app:preDebugAndroidTestBuild'.

Conflict with dependency 'com.android.support:support-annotations' in project ':app'. Resolved versions for app (26.1.0) and test app (27.1.1) differ. See https://d.android.com/r/tools/test-apk-dependency-conflicts.html for details.
Comment: Did the link in the error message itself not help? If you do not write tests (bad),  you can just delete the test app. Otherwise, make sure they use the same version. Post your gradle files for more specific advices
Comment: open you build.gradle( app) and check the version of buildToolversion & support library, both should be same.
Answer: Add this into your AndroidManifest.xml file the <application> tag.
<meta-data
        android:name="android.support.VERSION"
        android:value="26.1.0"
        tools:replace="android:value" />

You can also provide other version e.g. 27.1.1
Comment: its not resolving
Comment: please post your `build.gradle(app)` file here
Answer: You can force the annotation library to test using in build.gradle:
androidTestCompile 'com.android.support:support-annotations:26.1.0'

Another solution is to use this in the top level file:

configurations.all {
    resolutionStrategy.force 'com.android.support:support-annotations:26.1.0'
}

use any of one in Above two options, I hope it may useful to you.


How to do merge image layers like imagick does in libvips

Question: I am using libvips php library i want to merge image layers using libvips. Does any method in libvips for merge the image layers like imagick has as below
$img = $img->mergeImageLayers(Imagick::LAYERMETHOD_FLATTEN);

Answer: You can use ->flatten() to squash the alpha out of an image. Docs here:
https://libvips.github.io/php-vips/docs/classes/Jcupitt.Vips.ImageAutodoc.html#method_flatten
Unfortunately, phpdoc doesn't let you document optional arguments, so you need to refer to the C docs to see the extra controls:
https://libvips.github.io/libvips/API/current/libvips-conversion.html#vips-flatten
You can remove bands with unset, so you can drop alpha from an RGBA image with eg. unset($image[3]).
Comment: Is there any way to call direct this method vips_addalpha in php?
Comment: Just do `$image[] = 255;` to append an extra band which is solid 255.


nodejs - cannot use module from imported package

Question: I create an npm package https://www.npmjs.com/package/vue-top-down-test, which just exports two objects VueTopDown and VueTopDownItem.
import { VueTopDown } from './vue-top-down'
import { VueTopDownItem } from './vue-top-down-item'

module.exports = {
  VueTopDown,
  VueTopDownItem
}

However, I failed to use (even just print) them in my demo https://github.com/MoYummy/vue-top-down/tree/master/docs/demo-node.
import * as VTD from 'vue-top-down-test'
import Vue from 'vue'

console.log(Vue)
console.log(VTD)

Could anybody give me some clue? Thanks.
Answer: Set output.libraryTarget as umd in your webpack.config.js. Default libraryTarget is set var. The return value is assigned to a variable, it cannot be used inside module
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: '[name].js',
    library: 'VueTopDown',
    libraryTarget: 'umd',
    umdNamedDefine: true
  }

Multiple target
Although webpack does not support multiple strings being passed into the target property, you can create an isomorphic library by bundling two separate configurations: Multiple Targets
const path = require('path');
const serverConfig = {
  target: 'node',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'lib.node.js'
  }
  //…
};

const clientConfig = {
  target: 'web', // <=== can be omitted as default is 'web'
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'lib.js'
  }
  //…
};

module.exports = [ serverConfig, clientConfig ];

Modified webpack.config.js for your reference
const path = require('path');
const webpack = require('webpack');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');

const serverConfig = {
  mode: 'production',
  target: 'node',
  entry: {
    'vue-top-down': './src/index.js',
    'vue-top-down.min': './src/index.js'
  },
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: '[name].js',
    library: 'VueTopDown',
    libraryTarget: 'umd'
  },
  module: {
    rules: [{
      test: /\.js$/,
      loader: 'babel-loader',
      query: {
        presets: ['env']
      }
    }]
  },
  stats: {
    colors: true
  },
  devtool: 'source-map',
  optimization: {
    minimizer: [
      new UglifyJsPlugin({
        test: /\.min\.js$/
      })
    ]
  },
  plugins: [
    new CleanWebpackPlugin([
      path.resolve(__dirname, 'dist')
    ]),
  ]
};

const clientConfig = {
  mode: 'production',
  target: 'web',
  entry: {
    'vue-top-down': './src/index.js',
    'vue-top-down.min': './src/index.js'
  },
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: '[name].web.js',
    library: 'VueTopDown'
  },
  module: {
    rules: [{
      test: /\.js$/,
      loader: 'babel-loader',
      query: {
        presets: ['env']
      }
    }]
  },
  stats: {
    colors: true
  },
  devtool: 'source-map',
  optimization: {
    minimizer: [
      new UglifyJsPlugin({
        test: /\.min\.js$/
      })
    ]
  },
  plugins: [
    new CleanWebpackPlugin([
      path.resolve(__dirname, 'dist')
    ]),
  ]
};

module.exports = [serverConfig, clientConfig];

Comment: Great, thanks! But call in browser will fail: `https://moyummy.github.io/vue-top-down/docs/demo-browser-script.html`. Do I need to build separate two js?
Comment: Updated answer for multiple target
Answer: Finally make it: https://github.com/MoYummy/vue-top-down/tree/v0.0.1
The key is to build commonjs, umd and esm for each runtime environment.
npm: https://firstname.lastname@example.com/dist/
use: https://moyummy.github.io/vue-top-down/example/


Extend UserProvider for FOS UserBundle

Question: I am building a site using Symfony2 and it will be a white-label type of site, where multiple domains map to the same server.  So coolsite.customer1.com and aservice.customer2.com would map to the same site, but would need to appear different to the end user.  I already solved for the domains, and loading the unique configurations as a service.
With the FOS UserBundle setup and running with a custom user (that has the domain_id stored in it), registration, login, etc works fine except that users from domain1 can login to domain2 also.  This is expected in the FOS UserBundle.  I need to make modifications to the bundle so that it only will authenticate users on the domain they are assigned to.
I have created a userProvider that extends the original userProvider in FOS and have overridden the loadUserByUsername method to also check the domain.  See below:
use FOS\UserBundle\Security\UserProvider as FOSProvider;
use Symfony\Component\DependencyInjection\ContainerInterface;
use FOS\UserBundle\Model\UserManagerInterface;
use Me\CoreBundle\Models\Core;

class UserProvider extends FOSProvider {

    /**
     *
     * @var ContainerInterface
     */
    protected $container;

    public function __construct(UserManagerInterface $userManager, ContainerInterface $container) {
        parent::__construct($userManager);
        $this->container = $container;
    }

    /**
     * {@inheritDoc}
     */
    public function loadUserByUsername($username)
    {
        $core = $this->container->get('me_core');
        /* @var $core Core */

        $user = $this->findUserBy(array(
            'username'=>$username,
            'domain_id'=>$core->getDomainMap()->getId(),
        ));

        if (!$user) {
            throw new UsernameNotFoundException(sprintf('Username "%s" does not exist.', $username));
        }

        return $user;
    }

    public function findUserBy(array $criteria) {
        return $this->userManager->findUserBy($criteria);
    }

}

I have configured the service with the following.
services:
  me.security.authentication.userprovider:
    class:  Me\UserBundle\Security\UserProvider
    arguments:
      - @fos_user.user_manager
      - @service_container

My security.yml looks like this:
security:
    providers:
        me.security.authentication.userprovider:
            id: fos_user.user_provider.username

    encoders:
        FOS\UserBundle\Model\UserInterface: sha512

    firewalls:
        main:
            pattern: ^/
            form_login:
                provider: fos_userbundle
                csrf_provider: form.csrf_provider
            logout:       true
            anonymous:    true

    access_control:
        - { path: ^/login$, role: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/register, role: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/resetting, role: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/_wdt, role: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/public, role: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/admin/, role: ROLE_ADMIN }
        - { path: ^/, role: ROLE_USER }

    role_hierarchy:
        ROLE_ADMIN:       ROLE_USER
        ROLE_SUPER_ADMIN: ROLE_ADMIN

What happens when I try to access the site is an exception.  "ServiceNotFoundException: The service "security.authentication.manager" has a dependency on a non-existent service "security.user.provider.concrete.fos_userbundle"."
I based my modifications on This Cookbook Recipe
Any ideas?  I am thoroughly stumped on this.
Comment: Well I was able to get the changed name of the provider to function, because I forgot to update the provider in the firewalls/main/form_login section.  Now the login process is working exactly the same as if I made no changes, and the provider I specified is not being called.  I was able to verify it was not being called by dropping an echo and an exit command in the constructor.
Comment: Well I was able to solve it.  I am not able to answer my question for 8 hours though, so I will mark it solved at that point and post how i solved it.
Answer: I was able to get it to work.  Turns out I needed to make the "id" the same as the name of the service I was using.  The commented lines are the originals that came with the bundle.
security:
    providers:
        me.security.authentication.userprovider:
            id: me.security.authentication.userprovider
        #fos_userbundle:
            #id: fos_user.user_provider.username

Extend UserProvider for FOS UserBundle


Blender Icon in the main menu not working when i clicking

Question: Blender icon in main menu,when i clicked it nothing happend.
but i launch via terminal it is opening.
I'm tried with .desktop file but its also confusing about path of exec= and icon=
Exec=blender %f
Icon=${SNAP}/blender.svg

The above mentioned in snap folder ,i confused whether i create a .desktop file in .local or anything?
Comment: This question needs to be more focused. We need to know what you even mean. What Blender icon, what main menu, clicking what, and what are you even trying to acheive?
Comment: @AlexFullinator it looks like OP needs help making a .desktop file for Blender
Answer: To make a .desktop file appear in your shell and app menus, you have to put it  in ~/.local/share/applications, with execute permissions.
Comment: I done it yesterday but it disappeared after a night


Brightness control is not working AMD (Ubuntu 21.04)

Question: got the problem with not working brightness control (Ubuntu 21.04). Tried updating grub but no result from this post.
Graphics card AMD radeon Vega 11.
Thanks beforehand
Comment: Which solution from the linked question did you try that didn't work?
Answer: I've had that problem on my old Thinkpad. It is an acpi problem, which I could solve by activating the brightness control of my device (named thinkpad-acpi)
Since my hardware is different from yours just take it as a rough guide:
Created file /etc/modconf.d/brightness.conf
options thinkpad-acpi brightness_mode=1

So you should check your sys files for more information, about whether you have a vendor acpi which you could use. There is an excellent article that might shed some light.