augment the factory pattern in java

Question: I am trying to use a factory pattern to create a QuestionTypeFactory where the instantiated classes will be like MultipleChoice, TrueFalseQuestion etc.
The factory code looks something like this
class QuestionFactory {
    public enum QuestionType {
        TrueFalse,
        MultipleChoice,
        Essay
    }

public static Question createQuestion(QuestionType quesType) {
    switch (quesType) {
        case TrueFalse:
            return new TrueFalseQuestion();
        case MultipleChoice:
            return new MultipleChoiceQuestion();
        case Essay:
            return new EssayQuestion();
    }
    throw new IllegalArgumentException("Not recognized.");
}
}

This works ok for now. If I want to add another question type I will need to modify the factory class and I do not want to do that.
How can I set it up so that each question class registers itself with the Factory so that when I add a new question type, I do not have to change the code for the factory? I am a bit new to java and am not sure how to do this.
Edit
Additional Information
All the question classes implement an IQuestion interface. I am looking for a way to implement a method like
public static void registerType(QuestionType quesType, Class<IQuestion> ques)

so that I can call this method from a static block from my classes so that when I add a new question type, I will not have to change or add any code in the Question Factory. I know I would have to change the current implementation to make it generic. I am not sure the method that I wrote above is correct in terms of its arguments syntactically or not but it shows what I want in concept.
Comment: ... this is a case for XML, annotations, and reflections *grin*
Comment: I think you mean "augment" the factory pattern
Comment: I thought of two good solutions, but Java's lack of both Real Life-Sized Generics™ and closures made them worthless :(. I think you're stuck with manual labor, or some code template wizardry, or reflection.
Comment: @TP: probably the second parameter should be `Class`, no? You want to say the class to create, not an instance of it (because, if you already have an instance, you don't need a factory).
Comment: @ Martinho Fernandes
That might be what I need for the parameter. I am new to java so I am not aware of the exact syntax to achieve these kind of things
Comment: @Martinho

I am trying to achieve this to eliminate the dependency of the factory on the questionType classes. Is there any other better way to do this? In the current implementation, the factory class would need to know what all types of classes exist at compile time but a generic register method would rid it of that
Comment: @R.MartinhoFernandes It should be `Class` otherwise only `IQuestion.class` would be allowed as parameter
Answer: You can probably do that with the register method you've shown, through the Reflection API (that Class thingy).
I am not proficient enough with Java Reflection to write a more helpful answer, but if you look for some getConstructor method or something you'll probably get there.
To call that method you should do something like (note the .class syntax):
QuestionFactory.registerType(QuestionType.TrueFalse, TrueFalseQuestion.class);

EDIT Ah, whatever, I have the time to investigate. Try this:
public class QuestionFactory {
    static final Map<QuestionType, Constructor<? extends Question>> map =
        new HashMap<QuestionType, Class<? extends Question>>();

    public static void registerType(QuestionType quesType, Class<? extends Question> ques) {
        map.put(quesType, ques.getConstructor());
    }

    public static Question createQuestion(QuestionType quesType) {
        return map.get(quesType).newInstance();
    }
}

I haven't compiled this, but it should work, or at least guide you in the right direction. For this to work the Question implementations must have a constructor without arguments.
Because you're using a static factory (aka, object-oriented global variables) you can make questions register themselves in their static initializer.
public class TrueFalseQuestion implements Question {
    static {
        QuestionFactory.registerType(QuestionType.TrueFalse, TrueFalseQuestion.class);
    }
    // Whatever else goes here
}

Comment: The static block is not run until I actually instantiate a TrueFalseQuestion. How can I work around that?
Comment: @TP: Inside a static initialization block in the question class, e.g.:

    public class TrueFalseQuestion implements Question
    static {
        QuestionFactory.registerType(QuestionType.TrueFalse, TrueFalseQuestion.class);
    }
Comment: and where should I call the static register method in the question class?
Comment: If you want to remove the dependency from the static factory on the questions, you can do it the other way: have the questions depend on the static factory, i.e, register themselves. Probably in the static initializer.
Comment: that is exactly what I am trying to achieve. To let the questions register themselves. I am not sure where to place the code that registers the question class with the factory.
Comment: @TP: Yes, static initializers run when you first use the type. I don't know how you can get around that, other than explicitly touch the types yourself on main, or (maybe) using a special class loader. Maybe you should ask another question for that issue. It will gather more minds. I'm sure someone else will be able help.
Answer: One possibility:
public enum QuestionType {
    TrueFalse(TrueFalseQuestion.class),
    MultipleChoice(MultipleChoiceQuestion.class),
    Essay(EssayQuestion.class)

    private final Class<? extends Question> implementationType;
    QuestionType(Class<? extends Question> implementationType) {
       this.implementationType = implementationType;
    }

    public Question createQuestion() {
       return implementationType.newInstance();
    }
}

Of course, this gets rid of the factory and assumes all your questions have no-args constructors, but as far as I can tell, it covers all the cases of the code sketch above. If construction for the particularly classes is more complicated, you can always setup something like:
public enum QuestionType {
    TrueFalse { public Question createQuestion() { /* construction logic goes here */ } }
    public abstract Question createQuestion();
}

Comment: But this still doesnt solve the problem of dependency. I would still have to update the enum when I create a new question class. Is there any way to get rid of the dependency with this method?
Comment: Yes, yes, inside the enum is much better! This is probably the main Java feature I'd love to see in C#.
Comment: and how would I use it in the main method to actually create an instance of a particular question type?
Comment: @TP: `Question foo = QuestionType.TrueFalse.createQuestion();`.
Comment: @TP: No, this doesn't solve the problem of dependency. The only way to do that is to get rid of the enum using something like what Martinho suggested. For a small number of question types, I think the enum is quite elegant, but for unlimited options, you really need to switch to something a little more verbose.
Answer: I'm pretty sure you just want to create a method on your enum type which will return the appropriate Question object. So anytime someone adds an enum value to QuestionType they will also have to update the method. Doesn't solve your problem of having to update that method though...
Comment: But presumably, the Factory can decided to create an alternative implementation for a given type (i.e. an implementation that neither the enum, nor the calling code need to know about).

augment the factory pattern in java


JQuery UI tabs: How do I navigate directly to a tab from another page?

Question: JQuery UI tabs are implemented by named anchors in an unordered list. When you hover over one of the tabs you can see this in the link shown at the foot of the browser:
http://mysite/product/3/#orders

Above would be the "orders" tab for example. JQuery obviously intercepts the click to this anchor and opens the tab instead.
However if I bookmark the link above or link to it from elsewhere in the site the page does not open on the specific tab.
In the tab initialisation block I was considering putting in some code that looks for a named anchor in the URL and, if it finds one, does an index lookup of the tabs and calls the select on it. This would mean it will still work with JS switched off.
But is there an easier/nicer/better way?
Comment: The JS tab control would not work with JS turned of since it's all js
Comment: Interesting - 1.3.2. Been meaning to upgrade for a while but I'm going by the "ain't broke don't fix it" policy. Sounds like I've got a good reason to upgrade now (though I'm not looking forward to the retest)
Comment: @Hunter - no the tabs wouldn't work but the behaviour would still be correct. If JS was switched off the link would take you to the correct part of the page.
Comment: jQuery 1.3.2 or jQueryUI 1.3.2?
Comment: looks like I'm on the stable release so I'll probably stick with the coded solution, thanks though
Answer: Found this example here:
if(document.location.hash!='') {
    //get the index from URL hash
    tabSelect = document.location.hash.substr(1,document.location.hash.length);
    $("#my-tabs").tabs('select',tabSelect-1);
}

Comment: One thing this does not do is retain hash information between tabs. So if I got from www.page.com#1 to www.page.com#2 from within the same page it will not change the tab.
Comment: I was looking for a solution to a specific problem related to this answer. I don't think there's anything wrong with belated comments and questions considering everyone still receives notifications.
Comment: perfect, I've wrapped this up in a helper function and called it from the load event of the tabs control, thanks
Comment: @Zach - where were you last year?
Comment: That's an odd question, what do you mean?
Comment: Look at the date from this question/answer. Over 1 year ago.
Comment: I didn't say anything was wrong with it. You could certainly add functionality to do what you're saying by snagging all anchor tags with a hash tag and manipulating the tabs accordingly.
Comment: Asked the question here. http://stackoverflow.com/questions/6934875/jquery-post-ui-tabs-not-linking-properly-with-page-anchors
Answer: As of version 1.8 jQuery UI supports this functionality. See example here:

Second tab active by default
Third tab active by default
Comment: thanks, gone with the stable release for the time being but I'll upgrade when I can
Comment: BTW jQueryUI 1.8 is the current stable release (see section *What about jQuery UI 1.7?*).   http://blog.jqueryui.com/2010/03/jquery-ui-18/
Comment: strange, they haven't updated the front page yet: Latest (1.8: jQuery 1.4+) Stable (1.7.2: jQuery 1.3+) - I'm using jquery 1.3 also so I would be upgrading both at the same time.
Comment: the links are no longer valid
Comment: Unfortunately it doesn't work when content is loaded via AJAX.
Comment: @DamianNowak Not really sure what you mean.
Answer: In versions of jQuery UI prior to 1.8 (not inclusive) that's pretty much the way you would have to do it.  The tab extension (AFAIK) doesn't know to switch based on which anchor it is initialized with (when the page loads) so you have to do that bit manually (in the ready event, of course).
As another answer indicates, the new version of the tabs in jQuery UI 1.8 supports bookmarking out of the box.
Comment: thanks, just wanted to be sure I wasn't missing anything obvious. Must be a common requirement
Comment: FWIW the demo they have on the jQuery UI site seems to initialize properly on anchor.
Comment: @R0MANARMY - I suggest you add an answer saying "this works in the latest version". I could mark you up then
Answer: I use the Session plugin to accomplish this in a custom tab class


Save state of achievements in Angry Birds after deleting and re-installing app?

Question: I want to delete Angry Birds from my phone, but keep my score and state, so that if i install it again later, and sign in, it will preserve my current achievements. Is that possible?
Comment: What platform? Android? iOS? Mac? PSN?
Comment: Really not sure about this one, but I think (on iOS) game center will keep your achievements (or you'll be prompted).
Comment: If you have an Android phone, this QA could help: http://android.stackexchange.com/questions/2432/how-to-backup-angry-birds-saves-data
Answer: On iOS, the actual GameCenter achievements are stored on Apple's servers.  You don't need to back them up.  The progress is saved in private/var/mobile/Applications/<Angry Birds>/Documents/highscores.lua, so you can back up and restore that file.  Here's easy instructions for it.
On Android there are no achievements but for backing up progress, there's an app for that.  If you have root, you can also manually back up /data/data/com.rovio.angrybirds or use an app like Titanium Backup.
I would expect similar options to be available for other platforms.  (See How can I move my progress from one machine to another on Chrome Angry Birds? as well).
Answer: if you have a PC try this little app http://birds-scores.en.softonic.com/


JSON Deserialization exception with a Map>

Question: This question has already been answered by
https://stackoverflow.com/users/218833/rnov
Thanks for the help!
I was coding something that can serialize any object into a JSON, and I used a Map<String,Map<String, Integer[]>> to do the properties... Basically, if you name that map map, I should be able to get the map with the fields using map.get("fields"), this will return a Map<String, Integer[]>... The String is for the name of the field, the Integer[] is an array of bytes that where outputted when serializing the object using ByteArrayOutputStream and ObjectOutputStream... But for some reason the Jackson JSON parser (Version 2.2.3) (I'm also using Maven) throws this exception when it comes to deserializing the array of integers:
Exception Header
com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.util.LinkedHashMap out of START_ARRAY token
Whole Exception (Except the JSON text, that will be down below)
com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.util.LinkedHashMap out of START_ARRAY token
at [Source: (String)"<JSON TEXT DOWN BELOW>"; line: 3, column: 9] (through reference chain: net.qava.util.UtilsParsedJson["fields"])

JSON Text generated by code.
{
"fields":{
"hey" : [-84, -19, 0, 5, 116, 0, 4, 72, 101, 121, 33],
"u" : [-84, -19, 0, 5, 112]
}
}

The net.qava.util.UtilsParsedJson class
public class UtilsParsedJson {
    public Map<String, Map<String, Integer[]>> fields = null;
}

The JSON creator
default String createJson(){
        String json = "{\n";

        // Build Fields
        json = json + "\"fields\":{\n";

        for (Field field : this.getClass().getFields()){
            try {
                field.setAccessible(true);
                String name = field.getName();
                Object thing = field.get(this);
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                ObjectOutputStream oos = new ObjectOutputStream(baos);
                oos.writeObject(thing);
                byte[] bytes = baos.toByteArray();
                json = json+"\""+field.getName()+"\" : "+Arrays.toString(bytes)+",\n";
            } catch (Exception e){
                e.printStackTrace();
            }
        }

        json = json.substring(0, json.length() - 2);

        json = json + "\n}\n}";

        System.out.println(json);

        return json;
    }

The JSON decoder
default UtilsJsonOutput decodeJson(String json){
        try {
            ObjectMapper mapper = new ObjectMapper();
            UtilsParsedJson upj = mapper.readValue(json, UtilsParsedJson.class);

            Map<String, Object> fields = new HashMap<>();
            for (Map.Entry<String, Integer[]> entry : (upj.fields.get("fields")).entrySet()){
                byte[] bytes = new byte[entry.getValue().length + 1];
                int p=0;
                for (int i : entry.getValue()){
                    byte b = (byte) i;
                    bytes[p] = b;
                    p++;
                }

                ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
                ObjectInputStream ois = new ObjectInputStream(bais);
                Object object = ois.readObject();
                ois.close();
                bais.close();

                fields.put(entry.getKey(), object);
            }

            UtilsJsonOutput ups = new UtilsJsonOutput();
            ups.output.put("fields", fields);

            return ups;
        } catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

Thanks for reading!
Answer: Just change Map<String, Map<String, Integer[]>> fields to Map<String, Integer[]> fields. Your fields property has only one level of nesting.
Or, alternatively, you can remove your UtilsParsedJson class altogether and just use Map<String, Map<String, Integer[]>> instead of it.


How to visually and interactively represent deeply nested physical objects?

Question: I'm in the process of trying to represent storage of physical items in potentially complex, deeply nested locations, let's say up to 5 levels deep.
We want to do this in a visual way that approximates an accurate visual representation of the physical storage unit they are interacting with.
As an example of the complexity, we might have a set of storage shelves with five shelf surfaces that can hold products. Let's just look at one shelf: If it is just products on the shelf, lined up horizontally, not a real problem:

If, however, there are stacked bins on the shelf with different products in each one, that produces more complexity:

Now say that one of those bins is actually a long drawer with multiple compartments, each of which can hold a discrete product:

And finally, to play devil's advocate (and this is not an edgy-case scenario), let's say one compartment in that drawer unit has a divider and thus that one compartment can contain four tiny products:

If one had a full set of shelves with this level of complexity, and one needed to provide both a full visual planogram ALONG WITH a table view of all the objects in each of those locations (to display more info about products, to sort and filter and interact with in a more tabular way, but still show the equivalent location in the visual) - how might you consider representing that, and how would you represent the coordinates of, say, an object at the lowest level? How might you break this up differently to present it for users to interact with best? How might you handle the visual planogram when there are more products on a shelf than the viewport can accommodate?
For the record I have MANY of my own possible solutions in flight, still to discuss with my team, but I need to see what other people's brains hold and how other perspectives might approach or solve this.
Thanks for any ideas or insights you might want to share!
Answer: Looking at these, I can't even figure out if it's a top view or a front view of the shelf so I would incline toward making it match the real aspect of the shelves rather than focusing on the nesting by watching shelve systems in real life, drawing it, looking at how things are disposed in boxes within boxes and try to represent that.
Of course, I don't have any context on your limitations, restrictions and ultimately purpose of having this represented in the UI but at a glance it seemed that you are complicating things in trying to represent a hierarchy when the shelves are designed to do just that including the expected labeling of the shelves, boxes, etc.
My sketch tries to visually show the shelve and show at what level is the box being placed and inside the box a summary of it's contents & on hover (or click or when the user searches for a specific item in the table, different interactions possible to meet the user where he needs it) shows an expanded view inside that box ( that if you know how things are laid in the box can be represented even more visually accurate.
Excuse the ugly sketch.
Comment: First of all, apologies for the slim context - it is a very complex scenario and I wanted to see what people might propose based on a first pass at the situation rather than go deep. Second, that was meant to represent a screen view of physical spaces that might vary between front-facing (e.g. shelves) and top-down (like a drawer unit placed on a shelf). I very much appreciate your solution offering - a hover/popover/tooltip option is one we've considered, but I like the "expand in place" direction you show. Definitely a potential part of our eventual solution.
Answer:
We want to do this in a visual way that approximates an accurate visual representation

I would like to understand why? The physical setup sounds like a large room, and why should that be squeezed into a few-inch monitor? I.e., which tasks are to be supported? Do users need to search the location of products, do they need to see which products are stored at a certain location, do they need to find an empty location to put something inside, ... These are tasks coming to my mind, but none of them really requires an approximate representation of the physical room. So I'm interested to hear about your use case(s).
Even if you need an approximate representation, a caveat from experience: How do you ensure changes in the physical layout will be reflected in your design? I once created a design showing work progress at several stations on a shop floor, but before the design was going live, the company had the need to squeeze in an additional work station, rendering the design useless (because changing the shop floor layout had not been in the use case description, and thus being neither designed nor implemented :-(

potentially complex, deeply nested locations, let's say up to 5 levels deep

The boring (abstract, non-approximate) representation for this would be a tree (table, if you need additional properties to show), and depending on your user population, this can be manageable. There are examples of deeper nesting, most notably on your own file system.

I have MANY of my own possible solutions in flight

It would be interesting (and help our understanding) if you shared the two "best" ones with some commentary why they are considered good, or what their drawbacks are. Maybe you can give us some inspiration as well (esp. considering the capitalized "many", I'm curious).


How did we know that X must be equal to 1?

Question: I did not understand the solution to this problem
Comment: The solution is four paragraphs long.  If you ask a more specific question about **what part** is confusing to you, you will get more helpful answers.  Without it, you'll just get recapitulations of the solution you already have.
Answer: Consider the expression
$$
Y + 10 Z = 89 X
$$
where $X, Y$ and $X$ are all single non-zero digits, or they can only be $1, 2, 3, 4, 5, 6, 7, 8$ or $9$. What can the value of $X$ be? We know that $Y+10Z$ can at it maximum be $9 + 90 = 99$, so certainly the right-hand side cannot be more than $99$. Therefore the only sensible value for $X$ is $X=1$.
Comment: As $X,Y$ and $Z$ each represent a different-digit, shouldn't $Max(Y+10Z)=8+9\cdot 10=98.$
Answer: It is already explained after $Y+10Z=89X$. The left hand side maximum value is $98$. The right hand side is a multiple of $89$, so it can be $89$, $2\cdot89=178$, $3\cdot89=267$,... Obviously the only good value is $89$, which corresponds for $X=1$


Inferred type does not conform to upper bound(s)?

Question: I have a generic method that checks if an array is sorted. However, when I write in my main Generic.isSorted(arr), I immediately get an error.
main:
public static void main(String[] args) {
        Integer [] arr = {1,3,8,4,2};
        Generics.isSorted(arr); //error

    }

Generic method:
    public class Generics()
    {
       public static <T extends Comparable<? super T>> boolean isSorted(T[] arr)
       {
           if (arr == null || arr.length <= 1)
               return true;
           for (int i = 0; i < arr.length - 1; i++)
           {    if (arr[i].compareTo(arr[i+1]) > 0)
                { return false;}

           }
           return true;
       }

    }

error:
  method isSorted in class Generics cannot be applied to given types;
      required: T[]
      found: Integer[]
      reason: inferred type does not conform to upper bound(s)
        inferred: Integer
        upper bound(s): Comparable<? super Integer>
      where T is a type-variable:
        T extends Comparable<? super T> declared in method <T>isSorted(T[])

Comment: Compiles and runs on Javas 5-7.
Comment: @sp00m It's not the syntax problem. `>` is the right way to do it.
Comment: Which version of Java are you using?
Comment: Do you have your own `Integer` class?
Comment: I don't know if these will solve your problem, but **1)** you have syntax problems (e.g. `public class Generics()`), **2)** `>` would probably be enough, **3)** you have to loop until `arr.length - 2`, and **4)** an array can contain `null`s, so be aware of NPEs `;)`
Comment: @rgettman Wouldn't `{1,3,8,4,2};` fail?
Comment: @RohitJain I meant the `public class Generics()` part (an example where new lines in comments would be great)
Comment: @SotiriosDelimanolis You're right.  If there is a custom `Integer` class, then `Integer [] arr = {1,3,8,4,2};` would have a compiler error also, as autoboxing would no longer apply.
Answer: Have you tried
public static <T extends Comparable<? extends T>> boolean isSorted(T[] arr)

or simply
public static <T extends Comparable> boolean isSorted(T[] arr)

?
Comment: You've changed the bounds of the type variable.
Comment: @SotiriosDelimanolis Yes and to me it seems even more meaningful.
Comment: Edit your answer and explain that.


vDSO: why does linux use them only for time-related functions?

Question: Just searched the Linux kernel for vdso hooks (e.g. found this at kernel.org), and it seems to be currently used mostly for time-related system calls. This brings two questions to mind:

Are there any other system calls that are planned to use vDSO interface soon?
Were clock_gettime() really becoming a large enough bottleneck to motivate the design of vDSO? Is there any particular kind of application for which this was helpful? If so, what kind of application and by how much?

It just seemed odd to design a new kernel syscall interface for just time lookups. I am guessing it helps high-performance servers for things like timestamping request-responses and logs. But I want to know if anybody here has more concrete details than just guesses.
Answer: Reasons Behind the vDSO
The vDSO manual page has this to say about the reason for creating this special library:

Why does the vDSO exist at all?  There are some system calls the
kernel provides that user-space code ends up using frequently, to
the point that such calls can dominate overall performance.  This
is due both to the frequency of the call as well as the context-
switch overhead that results from exiting user space and entering
the kernel.

Further reading will tell you of the various strategies used to make it possible to share data between the kernel and user space. Especially:

This information is also not secret—any application
in any privilege mode (root or any unprivileged user) will get
the same answer.

Note: Emphasis mine.
That tells us that the data offered through that vDSO interface has to be public, something that any process running on the system would anyway have access to. This is obviously very important.
So to recap we have two reasons/constraints for adding functions to the vDSO:

The functions must be providing information which is not secret
The functions must be used so much that it is really worth moving to the vDSO

Available Functions
If you look further in the vDSO manual page, you will notice lists of functions supported by various implementations (See the *ARCHITECTURE-SPECIFIC NOTES section). This gives us another piece of information: the Linux version when such and such was implemented/accessible. The very first available implementation was in Linux 2.5 (late 2001, note also that was a development version, so the first user available version was 2.6.1 in 2003).
We find the following functions in the vDSO:
sigreturn
rt_sigreturn
sigtramp
sigtramp32
sigtramp_rt32
sigtramp_rt64

syscall_via_break
syscall_via_epc
vsyscall
get_syscall_map
lws_entry
linux_gateway_entry

gettimeofday
clock_gettime
clock_gettime64
clock_getres
time

getcpu
get_tbfreq
sync_dicache
sync_dicache_p5
flush_icache

getpid
getppid
set_tid_address
set_thread_pointer
datapage_offset

So overall we see calls for:

Signal
System/Kernel
Time
CPU/Cache
Processes

For x86 processors, it is mostly limited to Time and CPU. In i386, there are signal related functions too.


Can't access full iteration of dictionary outside of for loop python

Question: The problem
I am trying to access my tag_dict dictionary variable outside of a for loop so I can use that dictionary to learn how to insert that data into sqlite. (First Sqlite project)
If I print the tag_dict inside of the for loop it gives me all the data.
Here is the code:
import os
import subprocess
from tinytag import TinyTag
import sqlite3
import json

tag = ''
extf = ['$RECYCLE.BIN','System Volume Information']
for root, dirs, files in os.walk(r'\\Vgmstation\\e\\', followlinks=True):
    dirs[:] = [d for d in dirs if d not in extf]
    for name in files:
        if name.endswith(".mp4"):
            musiclist=str(os.path.join(root, name))
            tag = TinyTag.get(musiclist)
            tag_dict = tag.as_dict()
            #print tag_dict   - This prints everything but I want this outside of the for loop...or how am I going to insert this into my sqlite database?

#print tag_dict   - This prints only one iteration when I need all the data so I can pass it over to an INSERT command in sqlite.... I think

Here is the result if I add a print tag_dict to the for loop:
{'comment': u"Shoot 'em up", 'album': u'Aerostar', 'audio_offset': None, 'title': u'Stage 7', 'track': None, 'disc_total': None, 'artist': u'Dota Ando', 'track_total': None, 'channels': 2, 'genre': u'8-Bit', 'albumartist': u'Dota Ando', 'filesize': 160102674L, 'composer': u'Dota Ando', 'year': u'1991', 'duration': 99.9999, 'samplerate': 48000, 'bitrate': 294651.393, 'disc': None}
{'comment': u'Platformer', 'album': u'Aladin', 'audio_offset': None, 'title': u'Track 10', 'track': None, 'disc_total': None, 'artist': u'Steve Rockett', 'track_total': None, 'channels': 2, 'genre': u'8-Bit', 'albumartist': u'Steve Rockett', 'filesize': 302885452L, 'composer': u'Steve Rockett', 'year': u'2000', 'duration': 180.04653333333334, 'samplerate': 48000, 'bitrate': 294651.393, 'disc': None}
{'comment': u'Platformer', 'album': u'Aladin', 'audio_offset': None, 'title': u'Track 11', 'track': None, 'disc_total': None, 'artist': u'Steve Rockett', 'track_total': None, 'channels': 2, 'genre': u'8-Bit', 'albumartist': u'Steve Rockett', 'filesize': 302791162L, 'composer': u'Steve Rockett', 'year': u'2000', 'duration': 180.04653333333334, 'samplerate': 48000, 'bitrate': 294651.393, 'disc': None}
#there is over 6000 more tracks to get through

Here is the result if I add a print tag_dict to the outside of the for loop:
{'comment': u'Action-adventure', 'album': u'Spawn Armageddon', 'audio_offset': None, 'title': None, 'track': '9', 'disc_total': None, 'artist': u'Rik Schaffer', 'track_total': '0', 'channels': 2, 'genre': None, 'albumartist': u'Rik Schaffer', 'filesize': 75479673L, 'composer': u'Rik Schaffer', 'year': u'2003', 'duration': 49.11573333333333, 'samplerate': 48000, 'bitrate': 294651.393, 'disc': None}
#and that's it. where is the rest of my data? :(
>>>

Any ideas would be appreciated.
Thank you for your time,
Answer: On each iteration of the inner loop, tag_dict = tag.as_dict() is setting tag_dict to a new value. So, after the loop is finished, the variable only has the final value, and none of the previous values.
If you want to keep all of the values, you could use a list instead, and append tag.as_dict() to that list within the loop.
Comment: `tag_dict` is a dictionary and not a list, so you can't call `append` on it. What I'm recommending is doing something like adding `tag_dicts = []` above the loops, and then replacing your current `tag_dict = tag.as_dict()` line with `tag_dicts.append(tag.as_dict())`. Then you'll have a list of all the dictionaries instead of just a single dictionary.
Comment: I tried doing this and I got an error `AttributeError: 'dict' object has no attribute 'append'`. I tried following this link:https://www.kite.com/python/answers/how-to-append-elements-to-a-list-while-iterating-over-the-list-in-python but it didn't help much. Do you know how to use append? I have never used this and it doesn't seem to work for dictionaries.
Comment: I "think" this is the answer so I am going to mark it as correct. The reason I "think" its the answer is because when I tried to run the script, its been frozen for while. I have over 6000 songs, I think turning that metadata from an object, then into a dictionary, then into a list is going to take a while.
Comment: hmm that's weird, I wouldn't expect that changing it to use a list would slow it down at all
Comment: Actually your code works, its just that big. hahaha I stopped the code and changed the link to a specific director path instead so I had less results and it totally came up in seconds. lol


Drop down button in flutter not switching values to the selected value

Question: I've recently started programming using dart and flutter and everything has been going smoothly for my app, although recently i wanted to add drop down menu to provide the user with multiple options to pick from. everything worked as planned however when i pick a value from the list it doesn't change the value in the box, it goes back to the hint or an empty box. any help would be appreciated!
here is my code for the dropdownbutton:
Widget buildDropdownButton() {
String newValue;

return new Padding(
  padding: const EdgeInsets.all(24.0),
  child: new Column(
    mainAxisAlignment: MainAxisAlignment.start,
    children: <Widget>[
      new ListTile(
        title: const Text('Frosting'),
        trailing: new DropdownButton<String>(
            hint: Text('Choose'),
            onChanged: (String changedValue) {
              newValue=changedValue;
              setState(() {
                newValue;
                print(newValue);
              });
            },
            value: newValue,
            items: <String>['None', 'Chocolate', 'Vanilla', 'ButterCream']
                .map((String value) {
              return new DropdownMenuItem<String>(
                value: value,
                child: new Text(value),
              );
            }).toList()),
      ),
    ],
  ),
);
}

Comment: could you put your stateful widget?
Answer: The error is because you are declaring a method variable newValue you must declare that  variable as global inside your StatefulWidget.
   String newValue;

  Widget buildDropdownButton() {
  return new Padding(
    padding: const EdgeInsets.all(24.0),
    child: new Column(
      mainAxisAlignment: MainAxisAlignment.start,
      children: <Widget>[
        new ListTile(
          title: const Text('Frosting'),
          trailing: new DropdownButton<String>(
              hint: Text('Choose'),
              onChanged: (String changedValue) {
                newValue=changedValue;
                setState(() {
                  newValue;
                  print(newValue);
                });
              },
              value: newValue,
              items: <String>['None', 'Chocolate', 'Vanilla', 'ButterCream']
                  .map((String value) {
                return new DropdownMenuItem<String>(
                  value: value,
                  child: new Text(value),
                );
              }).toList()),
        ),
      ],
    ),
  );
  }

Comment: Hello! I want to ask you, why can't we declare a variable inside the method? Why should we declare a variable globally?
Comment: @datafile4 because that global value gonna be kept if you change. If you define it locally then its value gonna be null if you return your widget out
Answer: Faced same issue and none of the answers worked. Then, I found the solution in one of my old projects.
I was using it in a AlertDialog here.
So, Change DropdownButton to DropdownButtonFormField
and add onSaved exactly as onChanged:
onSaved: (value) {
    setState(() {
        _selectedValue = value;
    });
}

That's it. It will start working.
Comment: This the only solution worked for me, thanks Lalit, it did work after changing DropdownButton to DropdownButtonFormField even with onChange
Comment: This was the solution for me. In my case the `DropdownButton` was inside a `FutureBuilder`, and its `value` was initialized using the future fetched value. The reason why the DropdownButtonFormField wasn't changing was because every time I called `setState` from inside `DropdownButton.onChanged`, it was rebuilding the entire widget, fetching the old value again.
Comment: Thanks. It worked for me.
Comment: In my scenario, dropdown is just a field in a dialogue I need to collect some info, but setting a state is not looks good as it will re build whole widget state, which have many other things as well. Switching from DropdownButton to DropdownButtonFormField works for me. Thanks
Comment: But why Onchanged is not working with us?
Comment: You can set `onClick` in the `DropDownMenuItem` and update the value there.
Answer: wrap dropdown button with StatefulBuilder and initialise newValue outside build method.
  StatefulBuilder(
          builder: (context, setState) => AlertDialog(
            title: Text("Change Status"),
            content: Container(
              padding: EdgeInsets.symmetric(horizontal: 8.0),
              decoration: BoxDecoration(
                  border: Border.all(color: Colors.grey, width: 1),
                  borderRadius: BorderRadius.circular(5)),
              child: DropdownButtonHideUnderline(
                child: DropdownButton(
                    hint: Text('Choose'),
                    onChanged: (String changedValue) {
                      setState(() {
                        newValue = changedValue;
                        print(newValue);
                      });
                    },
                    value: newValue,
                    items: <String>[
                      'None',
                      'Chocolate',
                      'Vanilla',
                      'ButterCream'
                    ].map((String value) {
                      return new DropdownMenuItem<String>(
                        value: value,
                        child: new Text(value),
                      );
                    }).toList()),
              ),
            ),

          ),
        ));

Answer: I had this problem although I was already using the solution above.
for anyone who has this problem and the above solution does not work, try separating FutureBuilder from the dropdown. this is how your final code should look like:
class TheFuture extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: myFuture(),
      builder: (ctx, snp) {
        if (!snp.hasData) return LoadingLine();
        return TheBuilder(snp.data);
      },
    );
  }
}

class TheBuilder extends StatefulWidget {
  const TheBuilder(this.mp);
  final Map<String, dynamic> mp;
  @override
  _MessageUSScreenFilterBodyState createState() =>
      _MessageUSScreenFilterBodyState();
}

class _MessageUSScreenFilterBodyState extends State<MessageUSScreenFilterBody> {
  int _selectedId;

  @override
  Widget build(BuildContext context) {
    return DropdownButton<int>(
      selectedItemBuilder: (context) =>
          widget.mp['myData'].map((e) => Text(e.type)).toList(),
      items: widget.mp['myData']
          .map(
            (e) => DropdownMenuItem(
              child: Text(e.type),
              value: e.id,
            ),
          )
          .toList(),
      value: _selectedId,
      onChanged: (int _id) {
        setState(() {
          _selectedId = _id;
        });
      },
    );
  }
}


Load external js file, modify something in it then execute it normally

Question: I want to 1) load an external js file programmatically via js code, 2) replace some literal values in it and only that 3) execute it normally.
Namely, instead of this single step

I want something to do 3 steps:

How to do that?
Comment: I think you can do it..but you don't have to do this. because of security reasons
Comment: @tajara - better way? sure. Use **your** server to request the script, make the changes on the server ... then you just need to `
Comment: download it using XMLHttpRequest/Fetch, modify the response text, add it in an inline script
Comment: This is pretty dubious, to be honest, there's a reason this isn't really done - its unsafe and you could be loading _any_ code right into your website that way... If its an API, it should provide appropriate calls to do this, otherwise you have to replace using `Regex`, and you c an never be 100% certain this keeps working.
Comment: @Bravo right. Is there a better way?
Comment: @ParthRaval I'm not asking  your opinion regarding security
Answer: Download the script using fetch/XMLHttpRequest, then modify the text in the response, then add it as an inlilne script
fetch("https://external_domain1.com/script1.js")
.then(response => response.text())
.then(text => {
  const s = text.replace('foo', 'bar');
  script.textContent = s;
  const script = document.createElement('script');
  document.body.appendChild(script);
});

No need for async flag here, and just append it to the document.body

Alternative

Have some resource on your server which, when accessed does the following

reads https://external_domain1.com/script1.js
modifies the content
sends the modified content as the response

lets assume this script is written in PHP, lives in the folder /path-to-script and is called magicScript.php - then in HTML you'd just have


Combine different types of jQuery functions?

Question: Is there a way to combine these jQuery calls? No real reason other than to tidy up my code a little.
$("#myForm input").blur(function() {
    saveForm();
});
$("#myForm :radio, #myForm :checkbox").click(function() {
    saveForm();
});

Comment: Use `change` event on `input` elements.
Comment: And how do you think these could be chained? The selected elements are different...
Comment: I'm not sure, hence the question. I just want to see if there's a single way of calling `saveForm()` rather than with these two seperate functions.
Comment: Thanks @Tushar, as you suggested, `change` event is the way to go.  `$("#myForm input, #myForm :radio, #myForm :checkbox").change(function() { saveForm(); });`
Comment: `.change(saveForm)` is a lot tidier. There's no need for the anonymous function if all it does is call `saveForm()` with no arguments.
Comment: Thanks @nnnnnn! In that case, I have a lot of tidying up to do!
Answer: use like below for click and blur
$('#myForm input, #myForm :radio, #myForm :checkbox').on('click blur', function () {
    saveForm();
});

Comment: Thanks Mani, @Tushar made a similar suggestion in the comments to my original question which is a bit cleaner than this solution.


Porting WinDbg plugin to Visual Studio 2019 extension

Question: I wrote a WinDbg plugin to assist my developers in debugging our applications.  More specifically, it helps in running special diagnostics on the data structures found in our application, and prevents that developers have to manually check lots of data structure information.
I am now considering porting this WinDbg to Visual Studio 2019 (as a VSIX extension), but I don't know where to start.  I can investigate how to write such an extension, but I don't know where to start looking for the debugger-related API in Visual Studio.

Is there a simple way to reuse a WinDbg plugin in Visual Studio 2019?  That would make it very easy for me?
If not, what is the API in Visual Studio to get debugging information?  Think about: reading memory, getting symbols, getting the address of a vtable, searching memory, getting the call stack, getting generic information?  I can do all of this in WinDbg via the IDebug... COM interfaces, but where do I start in Visual Studio 2019?
Comment: iirc the  complete functionality has been removed from vs earlier one could use !load ext.dll  and then call !peb etc  in the immediate window  the Command Window can provide a subset of these methods like Debug.ListMemory  dont tknow if it is scriptable
Comment: The last version of VS which had this feature built-in was VS 2010. More recent versions of VS required the WDK to be installed. The last WDK version which supports this feature is WDK for Windows 10 1507 ([MSDN](https://learn.microsoft.com/en-us/windows-hardware/drivers/debugger/setting-up-user-mode-debugging-in-visual-studio))
Comment: @ThomasWeller, thanks for the information.  So simply reusing my WinDbg plugin in Visual Studio doesn't seem to be an option anymore.  Any ideas on where to find information regarding the Visual Studio debugging API (similar to IDebugControl, … from WinDbg)?
Answer: @Patrick  i was googling after i wrote the comment but forgot to update
it appears vs has its set of own IDebugInterfaces called IDebugEngine1,2 etc
i never coded a vs extension but is trying to cobble one will update when i get time
in the meanwhile you may read through this documentation
it appears to be c#  and again that isnt my strong point either
<code>Requirements

Header: Msdbg.h

Namespace: Microsoft.VisualStudio.Debugger.Interop

Assembly: Microsoft.VisualStudio.Debugger.Interop.dll
</code>
there are two samples provided  which you can refer to here
i downloaded this sample but haven't given it enough time
and it appears the apis are completely different wrt windbg a sample Attach looks like below
<code>/* static */
DebuggedProcess^ Worker::AttachToProcess(ISampleEngineCallback^ callback, int processId)
{
    ASSERT(Worker::MainThreadId != Worker::CurrentThreadId);

    HANDLE hProcess = Win32HandleCall( ::OpenProcess(
        PROCESS_ALL_ACCESS,
        FALSE,
        processId
        ));

    String^ nameFromHandle = GetProcessName(hProcess);

    String^ processName = System::IO::Path::GetFullPath(nameFromHandle);

    Win32BoolCall( ::DebugActiveProcess(
        processId
        ) );

    DebuggedProcess^ process = gcnew DebuggedProcess(Attach, callback, hProcess, processId, processName);

    return process;
}
</code>
Comment: Thanks, this is a great starting point.  Next things on my todo-list are now: first: getting a sample working, second: extending the sample to include some simple logic, third: add full debugging logic.  Many thanks.


What are some recommended cordless trimmers/weed-eaters?

Question: I'm looking to pick up a cordless trimmer/weed-eater.  I have a bit of an anti-noise bias, so I'm hoping to find something that's electric cordless, not a gas-powered one.
Are there any trimmers of that sort that have decent power and battery life?  Or is the very nature of the tool such that a cordless electric version won't be satisfactory?
For what it's worth, I have a fairly small yard ~ 1/3 acre.
Edit
Gave the Black and Decker a whirl, and it was perfect - one battery on full charge, and I didn't even run it down doing the whole yard.
Answer: I own this cordless string trimmer: Black and Decker NST2018 ($100)
It comes with two batteries, so if the first one goes dead, you can pop in the second one and keep going.  (Always keep the spare one in the charger!)
I am happy with its performance.  My lot is 0.35 acres.  I use it to trim along my driveway, sidewalk, swing set, and a few flower beds.  I don't have a fence around my lot, or anything that requires extended use.  My usual trimming routine takes ~30 minutes, not counting cleanup.  I can usually finish the trimming in a single battery charge.  If I have neglected the yard for a while, it might take 1.5 battery charges to do everything.
It has an auto-string feed, which hasn't failed me yet.
You can rotate the trimmer 90 degrees to do edging work.  I do this along the edge of my sidewalk and driveway.  Makes a really "sharp" line, which looks nice.
It is pretty convenient to use.  No cords to drag around the yard, no engine to service.
However the battery does have its limits.  It starts out with decent power, but as the battery starts to wear down in the last few minutes, the motor RPMs will decrease.  It will still trim, just not as well.  If I had a larger lot, or a fence, or more things to trim around (garden, lots of landscaping features, etc), I would probably need something more powerful.  If your trimming routine is similar to mine, it should be OK for you.
My string trimmer is part of a larger Black and Decker 18V Yard System.  I also own the hedge trimmer and leaf blower from the set.  Since the batteries are interchangeable, I have plenty of spares and chargers.  Do you need other yard power tools?  If so, consider getting a set with interchangeable batteries.
When I got my yard tools, the Lithium Battery stuff was still pretty new, and no one was offering an interchangeable set.  Now there are at least a few on the market, so you may want to consider them over what I have.  Have never used one though, so I can't make a specific recommendation.
Comment: It's good to see a different perspective - I think your answer more suits the OP's question +1
Comment: I had a cordless back in the day when the batteries were big, heavy, expensive lead-acid affairs that never held a charge for more than 30 minutes and usually only lasted 1-2 years.  Li-Ion definitely sounds promising.  :)
Comment: This was one I was looking at.  I think I'll pick it up this afternoon and give it a try...
Answer: I picked up a basic Craftsman model at Sears a few months ago and have been very happy with it.  The battery still holds enough charge to do the whole yard twice.  Much easier to throw a battery on a charger for a couple hours than to have to mess around with a liquid fuel source.  It's also quite light.  Not as powerful as a gas model of course, but it gets the job done just fine!
Answer: I've never used a cordless trimmer, but from the reviews that I read online, I decided against the cordless option. Problems I've read about include a short battery life and not enough power. If you've got a long fence line like I do, the battery life is a big drawback. (Just for reference, I've got ~1/2 acre, mostly fenced.) And if you tend to let your grass get a little long between mowings, then the power issue is a big drawback. On the other hand, most consumer-use gas trimmers are in the $200+ range (some in the $100's) and I've seen corded or cordless electric trimmers for $40. So I guess it boils down to cost vs. performance.
I recently purchased an Echo SRM-225 after quite a bit of research, so I might be a little bit biased, but I'm not in the least bit disappointed by it. I did spring for a nicer gas powered trimmer, so you might not see as much of a difference between a cheap gas powered one and an electric one.
Comment: At your size of lot, especially with lots of fencing to trim around, I don't think my Black and Decker cordless trimmer (see my answer) would be able to handle it.  Not sure amount the new Lithium ones though.
Answer: I've found that electric (and especially coordless) trimmers arn't powerful enough to do the kind of edging I want (and especially since I don't cut the grass often enough). I don't like the noise (or the extra pollution from the two cycle engine that burns the oil and gas) but it was the only option . . . until now!
My next trimmer will be propane powered!  I saw a Craftsman version but I really like the ones y Lehr (although I don't like how they use the "eco" branding . . . looks too much like Echo, the maker of my current trimmer).
Comment: I agree. I had an electric and then bought a $50 2-stroke weed wacker. not the same tool. I've got to wear pants while using the thing whereas before I got away with shorts. Will have to check out the propane option if the one I have goes bad.


How To Download APT And All It's Dependencies?

Question: I'm trying to download APT and all it's dependencies so I can use dpkg to install APT offline. Since you can't simply use apt-get download apt the approach I've taken is trying to generate a list of dependencies which I can then manually use apt-get download package-name to retrieve.
I've tried these:
apt-cache showpkg package-name

Source: How can I check dependency list for a deb package

apt-cache depends packagename

Source: How to find top-level dependencies in a list of deb packages?

dpkg -I pkg-name1_version.deb

Source: How to find all dependent (dependency walker) packages before installing a .deb file?

They don't work properly. I need a way to list not only the dependencies of APT, but also the dependency dependencies; the entire tree. According to "sudo apt-get install apt --reinstall" APT has 302 depenencies+sub-depenencies. The lists generated using the answers I've found appear only to list the first level of dependencies, because they are too short.
Comment: http://stackoverflow.com/questions/13756800/how-to-download-all-dependencies-and-packages-to-directory
Answer: Either I am gravely mistaken, or there's something fundamentally wrong with apt having 302 dependencies + sub-dependencies. How can any distribution claim to lightweight if it depends on apt, then? At least, in my laptop, reinstalling apt doesn't mention any dependencies at all, so I am not sure where you got that figure from. I cooked up a script to check. On Ubuntu 14.04, I get 24 dependencies:
dpkg gcc-4.8-base gcc-4.9-base gnupg gpgv install-info libacl1 libapt-pkg4.12 libattr1 libbz2-1.0 libc6 libgcc1 liblzma5 libpcre3 libreadline6 libselinux1 libstdc++6 libtinfo5 libusb-0.1-4 multiarch-support readline-common tar ubuntu-keyring zlib1g

I then learned about apt-rdepends: http://xmodulo.com/2013/07/how-to-check-package-dependencies-on-ubuntu-or-debian.html
I installed and ran it, filtered the dependencies, sorted and compared to find the same list I got with the script. So I can safely conclude that these are all the packages you need to install apt. I think one of those gcc-4.[89] can be ignored depending on which one you want to install. Note that this list has trimmed down from Ubuntu 12.04, on which running this script (on a server) gave me 28 dependencies:
coreutils debconf dpkg gcc-4.6-base gnupg gpgv install-info libacl1 libapt-pkg4.12 libattr1 libbz2-1.0 libc6 libc-bin libgcc1 liblzma5 libreadline6 libselinux1 libstdc++6 libtinfo5 libusb-0.1-4 multiarch-support perl-base readline-common tar tzdata ubuntu-keyring xz-utils zlib1g

Presumably the packages have been trimmed down. The lack of dependency on coreutils and debconf is startling, I must say.
On a side note, I agree with this bug given in apt-rdepends man page:
  apt-rdepends exists.  This functionality should really reside in apt-
   cache itself.

The apt-cache tool provides four relevant commands that Braiam, unorthodox-grammar and I have discussed:

depends: List the (forward) dependencies. This also includes all the packages that are recommended, and also includes packages in the Breaks, Conflicts and Replaces sections. We just need to look at the Depends and Pre-Depends packages.
rdepends: There's an unfortunate naming clash with apt-rdepends. Both apt-rdepends and my aforementioned script check for dependencies recursively, whereas the apt-cache command is looking for reverse dependencies - packages which depend on the package in consideration. Use this command to check for potentially breakages caused by a package depending on a specific version of the one you are going got change.
showsrc: This command gives information about the source package that was use to build a package. A single source package can be used to build multiple binary packages - each of which may or may not depend on the others. apt, for example, depends on libapt-pkg, but not on libapt-inst, both of which are provided by the apt source package. Use this command to gain some insight into other packages you should install, which may not be dependencies, but which may be needed for greater utility,
showpkg: This command, among other things, lists both reverse and forward dependencies. The reverse dependencies are listed in a straightforward list, but the forward ones are a bit of a jumble - I still am not sure what the numbers mean. In any case, the individual commands depends and rdepends are clearer.

Thus, if we need to look at all the packages that a package might depend on directly or indirectly, apt-rdepends is what we need.
Comment: "apt-rdepends apt" gives me 28 packages, "apt-cache rdepends apt"
gives me 54 packages, and @Braiam's suggestion about "apt-cache showsrc apt" lists
"libapt-inst1.5" while neither of the above do. Every tool seems to have a different opinion???
Comment: @unorthodoxgrammar `showpkg` lists all the packages listed by `depends` and `rdepends`. You can immediately tell which ones are the reverse dependencies. The dependencies list includes *suggests*, *recommends*, *breaks* and *conflicts* packages as well, using numbers in the parenthesis to indicate the status, which are listed in a much cleaner way in `depends `, so that you can filter out the unnecessary bits. It doesn't add any new information that I can see.
Comment: `apt-cache rdepends` is looking for *Reverse dependencies*, my script and `apt-rdepends` are *recursively* looking for dependencies. `libapt-inst1.5` is a package provided by the source package `apt`, which is different from the binary package `apt`. `apt` binary package may or may not depend on anything else provided by the `apt` source package (it depends on at least one). Thus, it is a sibling in the dependency relationship, not a parent or a child. That said, you should install the four packages mentioned by @Braiam, using `apt-rdepends` to find the dependencies of all four.
Comment: @unorthodoxgrammar see http://packages.ubuntu.com/source/precise/apt for the source package and a list of binary packages compiled from it. You can probably use the source packages and its build-depends to build the packages on the target system.
Comment: "apt-cache showpkg apt" lists packages that aren't in the previous methods.
Answer: There are only 4 packages which you should to be preoccupated with: libapt-pkg4.12, apt-utils, libapt-inst1.5 and apt. The other dependencies to the apt packages are standard to all installations of Ubuntu. Why do I say only those 4 packages?
apt-cache showsrc apt
[...]
Package-List:
 apt deb admin important arch=any
 apt-doc deb doc optional arch=all
 apt-transport-https deb admin optional arch=any
 apt-utils deb admin important arch=any
 libapt-inst1.5 deb libs important arch=any
 libapt-pkg-dev deb libdevel optional arch=any
 libapt-pkg-doc deb doc optional arch=all
 libapt-pkg4.12 deb libs important arch=any
As you can see, the only packages that really comes from apt sources and are important are those.
Through the libapt-pkg4.12 package is pretty stable (there isn't right now a version on experimental, through all other packages have a new version) is recommended that you install them all together.
Also remember that product of this upgrade, you may break reverse dependencies to all those packages. First do apt-cache rdepends libapt-pkg4.12 apt-utils libapt-inst1.5 apt and check for any package that depends on a specific version of apt.
Answer: You can use Cube in that case. Cube downloads apps and all of its dependencies, and you can set whether to use apt-get or dpkg in installing them. Just select dpkg as default installer instead of apt-get in "Settings=>Preferences=>Installer Tab"
Check this tutorial to know more : http://community.linuxmint.com/tutorial/view/1583
Answer: Xubuntu includes in the base installation apt-offline to get around this situation provided you already have apt in place.  It determines what dependencies need to be downloaded and maps it out so that you do not have issues handling such download bundles.  The online documentation set contains a chapter on how to use the tool.


Updating a nodejs image inside of a Dockerfile

Question: I am trying to update the node version that we are using inside the Dockerfile of my application. Currently it is set as v12.21.0. I would like to update it to v16.13.0 as that is the current node LTS version. Please see my dockerfile code below.
So I turned this:
FROM node:12.21.0-alpine as build

RUN apk --update add bash

WORKDIR /usr/src/app
COPY . .
RUN yarn
RUN yarn build

FROM opsline/tools:alpine AS tools

FROM node:12.21.0-alpine

RUN apk --update --no-cache add ca-certificates

WORKDIR /usr/src/app

COPY --from=tools /usr/local/bin/chalk /usr/local/bin/
COPY --from=tools /usr/local/bin/gosu /usr/local/bin/
COPY --from=build /usr/src/app/build ./build
COPY --from=build /usr/src/app/node_modules ./node_modules
COPY --from=build /usr/src/app/server ./server
COPY --from=build /usr/src/app/package.json .
COPY --from=build /usr/src/app/scripts/pre-start.js .

COPY ./docker/entrypoint.sh /entrypoint.sh
RUN chmod +x /entrypoint.sh
ENTRYPOINT ["/entrypoint.sh"]

To This:
FROM node:16.13.0-alpine as build

RUN apk --update add bash

WORKDIR /usr/src/app
COPY . .
RUN yarn
RUN yarn build

FROM opsline/tools:alpine AS tools

FROM node:16.13.0-alpine

RUN apk --update --no-cache add ca-certificates

WORKDIR /usr/src/app

COPY --from=tools /usr/local/bin/chalk /usr/local/bin/
COPY --from=tools /usr/local/bin/gosu /usr/local/bin/
COPY --from=build /usr/src/app/build ./build
COPY --from=build /usr/src/app/node_modules ./node_modules
COPY --from=build /usr/src/app/server ./server
COPY --from=build /usr/src/app/package.json .
COPY --from=build /usr/src/app/scripts/pre-start.js .

COPY ./docker/entrypoint.sh /entrypoint.sh
RUN chmod +x /entrypoint.sh
ENTRYPOINT ["/entrypoint.sh"]

Is it true that all I would have to do is change the node version manually in the code and the rest should fall into place? Any advice is appreciated. Thanks
Comment: You can check the current node LTS version here https://nodejs.org/en/ which is **16.14.2 LTS**.

For future releases check here https://nodejs.org/en/about/releases/
Comment: Does it work if you run it?  What problems are you running into when you change the version in the `FROM` line?
Answer: Changing version will upgrade NodeJS if you are installing
but here your are using it as Base Image so you need to check whether such version is available in docker hub
If it is there we can use but 16.13.0-alpine is not there So I think you need to change version number to any version available at https://hub.docker.com/_/node


How convert select html tag to Html.DropDownList?

Question: How i convert this tag in html to @Html.DropDownList ?

 <select class="selectpicker input-price" data-live-search="true" data-width="100%"
   data-toggle="tooltip" title="Select">
    <option>Select City</option>
    <option>Test1</option>
    <option>Test2</option>
</select>

i can not set data-live-search and data-width to @Html.DropDownList
Thanks For Help
Comment: `@Html.DropDownListFor(m => m.YourProperty, Model.YourSelectList, new { data_live_search = true, data_width = "100%", data_toggle = "tooltip", title = "Select" })` (use underscore, not hyphen)
Comment: this work , thank you stephen
Answer: This is what I am doing for a drop down list:
Controller code:
public ActionResult Contact()
{
    Contact homeViewModel = new Contact();
    homeViewModel.subject = new List<Subject>();
    homeViewModel.subject.Add(new Subject { Id = 1, subject1 = "General Customer Service" });
    homeViewModel.subject.Add(new Subject { Id = 2, subject1 = "Suggestions" });
    homeViewModel.subject.Add(new Subject { Id = 3, subject1 = "Product Support" });

    homeViewModel.Selectedid = 1; //this sets the default value for your dropdown

    return View(homeViewModel);
}

Model code:
public class Contact
{
  [Required(ErrorMessage="Please fill the following")]
  public string name { get; set; }
  [Required(ErrorMessage = "Please Enter Correct Username")]
  [RegularExpression(@"^([0-9a-zA-Z]([\+\-_\.][0-9a-zA-Z]+)*)+@(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]*\.)+[a-zA-Z0-9]{2,3})$", ErrorMessage = "Please provide valid email id")]
  public string email { get; set; }
  public List<Subject> subject { get; set; }
  [Required(ErrorMessage="Please fill the following")]
  public string message { get; set; }
  public int Selectedid { get; set; }
}

View code:
 @model programname.model.Contact

 @Html.DropDownList("Selectedid", new SelectList(Model.subject, "Id",    "subject1", Model.Selectedid), new { @class = "form-control", id = "subject", required = "required" }

Comment: What does this have to do with OP's question? Are you trying to ask a new question?


How do I build a wet room for a wheelchair user?

Question: How do I build a wet room that:

Does not leek
Does not have water run out of its door
Is wheelchair accessible (e.g a very low slope)

It is very hard to get the slope right by hand and I have need two many cases when the sleep is too steep and the water run runs into the rest of the house.
Answer: A Barrier-Free Water Dam might be an option.  They allow the user to simply roll over them, then they spring back to their original shape and contain the water to the shower.
Answer: While I haven't build a space like you're describing, I have helped users of them and seen their designs.
If you are just trying to build a space that would allow the wheelchair user to shower, there are a number of products that are designed to make this relatively easy to install. A quick search yielded the link above, but I'm sure there are other options out there. These are less elegant looking than most true wet rooms, but can be highly functional. During college I assisted a user of a shower like that, who thought they were relatively well designed except that the controls were not in a location a seated person with restricted arm movement could easily reach (something to keep in mind however you build it).
If you're building a larger space you'll need to grade most of the floor, particularly the area around the shower to avoid water pooling away from the drains or flowing toward the door. This article has some thoughts to keep in mind when designing the space. You can make a raised edge near the shower that a wheelchair can get over just make sure you don't make it too hard to get over.  I've also seen spaces designed with a ridge that runs across the room that didn't cause problems for wheelchair users, but caused water to run toward one of two drains in the floor.  The advantage of grading the entire floor as I understand it, is that you always control where the water is going, instead of hoping it stays put.  This can be problematic of people with balance issues if you're not careful.
Answer: Rather than a slope, consider a little bit of a lip.  You'll need to consider who it is in a wheelchair, but if they can make it up a small bump, then add a higher threshold, and trim the door to give the necessary clearance.
You might also consider a bit of weatherstripping or similar, so that water can't easily get through the gap under the door.  (it doesn't need to seal that well, it can just be a small plastic flap on the inside of the door that comes down to meet the edge of the threshold.


Instantly Update Property in MVVM Light?

Question: I have a property in my View Model
public const string WelcomeTitlePropertyName = "WelcomeTitle";

    private string _welcomeTitle = string.Empty;

    ///
    /// Gets the WelcomeTitle property.
    /// Changes to that property's value raise the PropertyChanged event.
    ///
    public string WelcomeTitle
    {
        get
        {
            return _welcomeTitle;
        }

        set
        {
            RaisePropertyChanging(WelcomeTitlePropertyName);
            _welcomeTitle = value;
            RaisePropertyChanged(WelcomeTitlePropertyName);
        }
    }

This is hooked up to a textbox and has 2 way binding.
Now I have a KeyDown event that I need to get the current length of the "WelcomeTitle" property
  public ICommand AutoComplete
        {
            get
            {
               return new RelayCommand<KeyEventArgs>(e =>
                {
                    var length = WelcomeTitle.Length;
               });
            }
        }

Yep what I am finding is that WelcomeTitle property does not get updated till the user leaves the textbox. This does not work for me as I need to know the length(and later the current value in WelcomeTitle) and keydown.
How can I get around this? In codebehind this is no problem.
Answer: In WPF it would be easily achieved by setting UpdateSourceTrigger="PropertyChanged" in the binding; unfortunately, this is not possible with Windows Phone, so you need a workaround. A few options are described in this question.
Comment: hmm where would I stick that code from those options? In keypress down?
Comment: In the TextChanged event of the TextBox
Comment: An event handler in the code behind (you can't access the TextBox from the ViewModel anyway)
Comment: This seems to work but I had to change the event to KeyUp instead of KeyDown as it still does not work on KeyDown.
Comment: @chobo2, you should handle the TextChanged event rather than KeyUp or KeyDown
Comment: Sorry not following you. I should make a RelayCommand for TextChanged and then make a code behind event for TextChanged as well? What is the exact difference between textchanged and keyDown/Up
Comment: Who said anything about a RelayCommand for TextChanged? You just need an event handler for TextChanged that will update the binding source. In the setter of your viewmodel's property, you can then detect that the property has changed, and do whatever you need to do there.
Comment: It probably is not clear from my stripped down example but what I have is a property(WelcomeText) that stores the textbox value entered, I then have in keypress code to hit my server to grab all possible words for autocomplete based on user input. Are you saying I should move that server hit code to the TextChanged codebehind event?
Comment: OK, I think there are two things being mixed up here... In my view, you don't need the `AutoComplete` command at all, because you can detect any change to the text in the property setter. However, you still have the issue that this property isn't updated until the focus leaves the TextBox. The `TextChanged` event handler I'm talking about addresses *that* problem, not the call to the server
Comment: hmm I get what your saying the only thing I am not sure about how to do would be ignoring spaces and backspaces entered in. If someone is making a space to separate 2 words I don't want to do a server request as the result will be the same.


HTML form validation not appearing

Question: New to all this but essentially I'm trying to use HTML form validation via browser defaults. The form uses a JQuery script to submit the form. I've trawled through similar posts and updated my code but still no luck. If I click the Subscribe button with nothing entered, then there's no prompts presented.
HTML
<form class="form-inline" id="sub-form">

              <input type="name" class="form-control required" name="FNAME" id="mce-FNAME" value="" placeholder="First name" required />

              <input type="email" class="form-control required email" name="EMAIL" id="mce-EMAIL" value="" placeholder="Email address" required />

            <button type="submit" class="btn btn-primary" id="subscribe-btn" onclick="submitForm()">Subscribe</button>

<input type="text" name="b_8a28f24e93a8a23b993145f05_2d6480ea6a" tabindex="-1" value="">

        </form>

JQuery/JS
  //Mail Chimp form submission
  $('#sub-form').MailChimpForm({
    url: 'https://-.us19.list-manage.com/subscribe/post?u=8a28f24e93a8a23b993145f05&id=2d6480ea6a',
    fields: '0:FNAME,1:EMAIL',
    submitSelector: '#subscribe-btn',
    customMessages: {
      E001: 'This field can not be empty',
      E003: 'Please enter a valid email address',
    },
    onFail: (message) => {
      if ((message.indexOf("already") >= 0) || (message.indexOf("recent")) >=0) {
        alert('This email address is already subscribed. Stay tuned for our newsletter!')
      }
    },
    onOk: function() {
      $('#subscribe-ok').modal('show');
      $('#sub-form').each(function() {
        this.reset();
      });
    }
  });

UPDATE
So upon more testing the HTML validation works if I remove all the JQuery. As soon as I add it back in its gone. Any reason why my JS would break HTML validation?
Comment: Do you get any errors in your console?
Comment: Hi - no I'm afraid nothing there.
Comment: Interestingly seems to work with Firefox but not Chrome or Safari.
Comment: Validation works fine in my local machine
Comment: What browser and version are you using?
Comment: Maybe here is your answer, Did you try this? [link](https://stackoverflow.com/a/43902053/7894673)
Answer: Thanks everyone for the responses. In the end I opted for JQuery entirely and implemented ToolTipster and JQuery Validate. Final code below.
$("#sub-form").validate({
      errorPlacement: function(error, element) {
          var ele = $(element),
              err = $(error),
              msg = err.text();
          if (msg != null && msg !== "") {
              ele.tooltipster('content', msg);
              ele.tooltipster('open'); //open only if the error message is not blank. By default jquery-validate will return a label with no actual text in it so we have to check the innerHTML.
              console.log("form validation attempted")
          }
      },
      unhighlight: function(element, errorClass, validClass) {
          $(element).removeClass(errorClass).addClass(validClass).tooltipster('close');
      },
      rules: {
          field1: {
              required: true,
              email: false
          },
          field2: {
              required: true,
              email: true
          }
      },
      submitHandler: function(form) { // for demo
          alert('valid form');
          return false;
      }
  });

//Run validation on form for subscribe attempt
  $('#subscribe-btn').click(function () {
    if ($("#sub-form").valid()) {
            console.log('hello - valid form');
        } else {
            console.log('uh oh invalid form');
        }
    });

HTML form validation not appearing


Highly imbalanced Alzheimer's Disease MRI image dataset

Question: I am currently doing my final year project and I need your humble opinion. My dataset consists of 4 classes which contain :
Mild demented - 896 images
Moderate demented - 64 images
Non demented - 3200 images
Very Mild demented - 2240 images
As you can see, my moderate demented and mild demented are considered highly imbalance. Therefore, I am currently exploring the things that I should do when it comes to imbalance data. I am considering data augmentation or SMOTE to increase my imbalance data. However, I found that data augmentation should be done for training set only. In my case, I want to rebalance my data before splitting the data to ensure the data are balanced. What should I do? Can anyone help me?
I have tried data augmentation after data splitting on training set only. However, my supervisor advise maybe I should use SMOTE for oversampling the images.
Answer: The issue of data imbalance frequently arises in "long-tail learning," which focuses on addressing datasets with a long-tail distribution.

There are several methods available to handle the data imbalance problem. The simplest and most effective approach is to use cost-sensitive learning, which balances the class importance weight based on the number of data.
For instance, your dataset contains a total of 6,400 data, and the number of data for the "Moderate demented" class is 64, then the class importance weight for "Moderate demented" is calculated as 6,400/64 = 100. On the other hand, the number of data for the "Non-demented" class is 3,200, its class importance weight is calculated as 6,400/3,200 = 2.
Reference:
https://samer-baslan.medium.com/an-introduction-to-deep-long-tailed-learning-414881a2519


How to build SQL query that consolidate two tables?

Question: ALL
There are two tables, new and old.
[New]
Machine Date
A       Apr 16
B       Apr 16
A       Apr 15
C       Apr 15
A       Apr 14

[Old]
Machine Date
A       Apr 12
B       Apr 10
A       Apr 09
C       Apr 08
A       Apr 07

I want to bring Top 2 Machine where date > Apr 09
I can build a query for one table but dont know how to consolidate two table.
select top 2 machine, count(machine)
from new
where date > "Apr 09"
group by machine

it would be used two select query in one statement but don't know how to do.
Anyone can advise for this?
Answer: If you'll be doing this often, I'd recommend creating a view that shows both tables:
CREATE VIEW AllData AS
SELECT * FROM [New]
UNION ALL
SELECT * FROM [Old]

And then you can just select from the view and do whatever filtering you want:
select top 2 machine, count(machine)
from AllData
where date > "Apr 09"
group by machine

Also, I'm not sure if the data you're showing here is just an example, but I'd be careful about the date format you're using - since you're filtering based on a string, pretty much every date in the year will satisfy that condition, including "Jan 01". To update it, you may want to consider using an actual date type.
Comment: Thanks!! this is helpful for me to creat a query simply after making view!!
Answer: The query that you seem to want is:
select top 2 machine, count(machine)
from ((select * from [New]
      ) union all
      (select * from [Old]
      )
     ) t
where date > "Apr 09"
group by machine
order by count(machine) desc

When you use top, you should always have an order by.  Otherwise, the results are indeterminate.  I am guessing that you want the two with the highest count.


Adding ntfs partition to fstab slows down boot time

Question: I have a 1TB SSD drive I created 3 main partitions for 120GB for windows, 120GB for linux, and ~500GB for a shared drive.
I partitioned the shared drive as NTFS and added this line to fstab
UUID=xxx    /media/data     ntfs-3g rw          0   0

This works in that the drive does get mounted but now booting into Ubuntu takes over a minute.
I commented this line out and boot time was just at ~20secs.
I'm not even sure where to start here. Any information would be greatly appreciated.
Answer: I still couldn't figure out what I was doing wrong and I still don't know where to start to check for error messages about this and whatnot but after more research I ended up following instructions I got online to use Ubuntu's Disks application.
It was pretty straightforward, just open up Disks, select your partition, click the gear button, and hit edit mount options:

Select your mount options and it should add a line to your fstab file, mine looked this:
/dev/disk/by-uuid/<actual-uuid> /media/data auto nosuid,nodev,nofail,x-gvfs-show,x-gvfs-name=Data 0 0

I should say though I did this a few days ago and I couldn't remember if the options were default or if I looked them up. I've been tinkering about with this OS so much, I honestly don't remember a lot o what I did.
So if someone more knowledgeable about these options shed light on it, I would appreciate an edit.


Why packagecode is not being updated in registry after a small update or minor upgrade?

Question: I have an application installed and I am doing a small update (new msi with new package code but same version, product code and upgrade code). The update works fine but I noticed that I am not able to uninstall the software later (it gives an error saying that cannot find the source file and ask me to locate it. If I point the original MSI file - not the new one - that the uninstall occurs fine).
I think that is due to the package code of the new msi not replacing the former package code value in the registry (HCR\Installer\Products\GUID).
How can I force the installation of the new msi update that registry? I already tried using REINSTALL=ALL with REINSTALLMODE=vomus (vamus, and several other combinations).
I see the same issue when doing a minor upgrade (new package code, new version but same product code and same upgrade code).
My msi file as created using Installshield.
Comment: Small updates are not recommended. Is there a particular reason why you want to use it instead of a minor upgrade? Did you change [the package code](https://docs.revenera.com/installshield26helplib/helplibrary/MajorMinorSmall.htm)? (look towards bottom).
Comment: By the way, it is `REINSTALLMODE` and not `REINSTALL_MODE`. You can try `REINSTALLMODE=voums`. And the reason I ask about package code is that it certainly will not work without changing it.
Comment: @SteinÅsmul thanks for the interest in helping figuring out the issue. I used REINSTALLMODE (REINSTALL_MODE was a typo when writing the question, I just fixed it). About the packagecode, yes they are different and I can confirm it since when I install the new version directly (so, no upgrade) I see the correct package code there in registry. It is just when installing the new version on top of the old one that it appears that the packagecode doesn't get updated in the registry and keeps referring the old msi package code.
Comment: @SteinÅsmul, I tried both (small update and minor upgrade) and get same uninstall issue. The only way that worked so far was doing a major upgrade (different product code, same upgrade code). I updated the question to reflect that info.
Comment: Did you test on a virtual? Try that if you didn't. You could have a dirty-state on that test box you use.
Comment: good idea. I will try that and update here.
Answer: After several tentatives, I gave up using small upgrades and I am using major upgrades (new project code, new package code, same upgrade code) with the setup.exe from installshield.
But just as an extra info, I think the issue I was facing with the small upgrade is somehow related with the setup.exe created by installshield. I was able to do small upgrade using .msi files and the uninstall worked fine (the 2nd msi file must be installed via cmd line "msiexec.exe /i \product.msi REINSTALLMODE=vomus REINSTALL=ALL"). If you just try to install update via double click on the msi Windows you will give you a message that the product is already installed).
As sugested by @Stein Åsmul, just go with the major upgrade.
Here are some links that I found related to that issue:
https://community.flexera.com/t5/InstallShield-Forum/Minor-Upgrade-breaks-Uninstall/td-p/115568
https://docs.revenera.com/installshield24helplib/installshield24helplib.htm#helplibrary/MinorUpgradeRuntime.htm?Highlight=REINSTALLMODE
https://community.flexera.com/t5/InstallShield-Forum/Reinstallmode-is-defaulting-to-vomus/td-p/24565
http://www.msigeek.com/1256/how-do-you-create-a-minor-upgrade-for-an-application-using-installshield
https://vincechan.me/2016/05/17/reinstallmode-vs-reinstallmodetext/


Broadcast Android

Question: I want to build more Android app that can send data of another Android app.
Now there are for example 3 apps (OneApp, TwoApp, ThreeApp) and another app (AlertAPp).
Now I want the the 3 apps can send soma data at AlertApp and in the future, another app can send data at AlertApp never change other apps code.
I have see the Broadcast receiver in Android but I don't know if it is the good solution or not.
Answer: You can send data through intents
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "This is my text to send.");
sendIntent.setType("text/plain");
startActivity(sendIntent); // or startActivityForResult

More details on documentation.
Also you can use a public database (not saved in cache), but encrypted, or files.
Comment: Catalin, thanks for your answer. I suppose that OneApp send this message. How can Alert App intercept this message ?
Comment: @bircastri using intents, you could start your wanted app, in your case `Alert App` by knowing your app package and class that should receive data
Comment: Ok thanks, but I can for example send the message from an app to another app, and the second one works in background ?
Comment: Yes. This approach is similar how you send and email using intents.
Answer:
first app from what you want to send broadcast

sendBroadcast(new Intent("KEY_STRING_ANYTHING")
                               .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
                               .setComponent(new ComponentName("APP_PACKAGE_NAME", "APP_PACKAGE_NAME.receiver.MyBroadcastReceiver")));

second app from what you want to receive a broadcast, In manifest Application Tag - declare the receiver of MyBroadcastReceiver (also enable this 2 properties - android:enabled="true"
              android:exported="true") and inside that declare intent-filter as below

        <intent-filter>
            <action android:name="KEY_STRING_ANYTHING" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>

receiver/MyBroadcastReceiver.java

public void onReceive(Context context, Intent intent) {
    Log.e("data", intent.getAction());
    Intent intent1 = new Intent(Const.EventBroadcast);
    intent1.putExtra("action", intent.getAction());
   *compare key and perform action*}

Broadcast Android


Zoom in imageView image using c# wpf

Question: im trying to make a window which contain "browse" button to load image file and a button "+" to zoom in the image. Browse button and its open dialog successfully loads the image into Image aka . When I press "+" button, it doesnot zoom in the loaded image but blurs it. Whats wrong?
The original loaded image is named as OriginalSizedImage.
The zoomedIn image is named as
private void ZoomInButton_Click(object sender, RoutedEventArgs e)
        {
            BitmapImage newZoomedInImage = new BitmapImage();
            newZoomedInImage.BeginInit();
            newZoomedInImage.DecodePixelWidth = originalSizedImage.DecodePixelWidth + 20 ;
            newZoomedInImage.DecodePixelHeight = originalSizedImage.DecodePixelHeight + 20;
            newZoomedInImage.UriSource = originalSizedImage.UriSource;
            newZoomedInImage.EndInit();
            imageView.Source = newZoomedInImage ;
        }

Comment: Besides that setting DecodePixelWidth/Height won't crop an image, it makes no sense to create new BitmapImage instances all the time. Better just set an appropriate RenderTransform on the Image element that shows the BitmapImage. Use e.g. a ScaleTransform. Otherwise just use a CroppedBitmap, e.g. like here: https://stackoverflow.com/a/29768984/1136211
Comment: Possible duplicate of [Zoom Cropped pixels in a user control](https://stackoverflow.com/questions/28740086/zoom-cropped-pixels-in-a-user-control)
Comment: that thread is difficult. I was unable to understand it
Answer: It is unnecessary and inefficient to create a new BitmapImage each time you change the zoom factor.
Better put the Image element in a parent element that clips it
<Grid ClipToBounds="True">
    <Image x:Name="imageView" RenderTransformOrigin="0.5,0.5">
        <Image.RenderTransform>
            <ScaleTransform/>
        </Image.RenderTransform>
    </Image>
</Grid>

and then modify the ScaleTransform that is assigned to its RenderTransform (and perhaps also its RenderTransformOrigin):
private void ZoomInButtonClick(object sender, RoutedEventArgs e)
{
    var transform = (ScaleTransform)imageView.RenderTransform;
    transform.ScaleX *= 1.1;
    transform.ScaleY *= 1.1;
}

private void ZoomOutButtonClick(object sender, RoutedEventArgs e)
{
    var transform = (ScaleTransform)imageView.RenderTransform;
    transform.ScaleX /= 1.1;
    transform.ScaleY /= 1.1;
}

Zoom in imageView image using c# wpf


$\overline{\mathbb{Z_2}}$ closure of $\mathbb{Z_2}$, $\alpha, \beta$ roots of $x^3+x^2+1$, $x^3+x+1$. Show $\mathbb{Z}(\alpha) = \mathbb{Z}(\beta)$.

Question: Let $\overline{\mathbb{Z_2}}$ be an algebraic closure of $\mathbb{Z_2}$, and let $\alpha, \beta \in \overline{\mathbb{Z_2}}$ be zeroes of $x^3+x^2+1$ and of $x^3+x+1$, respectively. Show that $\mathbb{Z}(\alpha) = \mathbb{Z}(\beta)$.
The solution:

Theorem 33.3:

First of all, shouldn't $\mathbb{Z_2}$ have $2$ elements? Why $\mathbb{Z}(\alpha)$ and $\mathbb{Z}(\beta)$ are extensions of degree $3$?
Comment: I'm voting to close this question as off-topic because OP has abandoned it.
Comment: When you write ${\rm Z}(\alpha)$, etc., I think you mean ${\bf Z}_2(\alpha)$, etc. Please edit your question accordingly.
Comment: Also, is it not explained somewhere in your materials that if $p$ of degree $n$ is irreducible over $F$ and $p(\alpha)=0$ then $F(\alpha)$ is an extension of $F$ of degree $n$?
Comment: Are you still here?
Answer: If $K$ is any field over which $x^3+x^2+1$ is irreducible, then $K(\alpha)\cong K(\beta)$ where $\alpha$ and $\beta$ are zeroes
of $x^3+x^2+1$ and $x^3+x+1$. That is because $1/\alpha$ is a zero
of $x^3+x+1$.


Dice conditional expectation

Question: Suppose we both roll two fair twenty sided die. Given that I rolled higher than you, what is the expected value of my roll?

I believe I could answer this question but I'm mainly wondering if there is a more efficient way to compute this answer rather than summing up the conditional probabilities of rolling each number n 1-20 and multiplying that by n?
Comment: Of the $n^2$ pairs of possible results, $\frac{n(n-1)}{2}$ of these have your dice of greater value than mine. If you rolled $m$, there are $m-1$ possible cases where you are higher than me. So, we calculate the total sum of your values over the winning cases to be $(\sum_{m=1}^{n} m(m-1)) = \frac{n(n+1)(n-1)}{3}$ . Dividing by number  winning cases, ie by $\frac{n(n-1)}{2}$, we get expectation of $\frac{2(n+1)}{3}$, where $n=20$. Sorry it's not clever.
Comment: *What is the expected value of my roll given that it is greater than yours?* Please rephrase your question. As it is written it is not clear what you mean.
Comment: I'll denote with $X, Y$ the outcome of the two dices and assuming they are independent. I don't know whether there's an even ''simpler'' way, but computing by Bayes the probability of $P(X=k \mid X > Y) = \frac{P(X > Y \mid X =k)}{P(X > Y)} P(X=k) = \frac{k-1}{190}$ and then taking the expected value seems rather straightforward once one knows the result of the summations $\sum_{k=1}^n k^p$ for $p = 1,2$.
Answer: Found the trick to solve it. Let $n$ be the max value of the die, and $(d_1,d_2)$ be a pair satisfying $d_2 > d_1$, ie. a favorable event, where the second element of the pair represents your roll, and the first represents theirs.
Let's represent the event $(d_1,d_2)$ where $d_2>d_1$ as the  triple of differences: $$(v_1,v_2,v_3) = (d_1 - 0, \hspace{1mm} d_2-d_1, \hspace{1mm} (n+1)-d_2)$$
These three differences are uniformly distributed values between $0$ and $n+1$ (excluding $0$ and $n+1$), with the restriction that they sum to $n+1$.
We are looking for: $E(d_2) = E(v_1+v_2)$ . But $$E(v_1 + v_2) = E(v_2 + v_3) = E(v_3 + v_1)= $$ $$= E(\frac{(v_1+v_2) + (v_2+v_3) + (v_1 + v_3) }{3}) =$$ $$=E(\frac{2}{3}(v_1 + v_2 + v_3)) = $$
$$= E(\frac{2}{3}(n+1)) = \frac{2}{3}(n+1)$$
Summary of proof idea:

Dice conditional expectation


Asbestos or normal insulation within hot water tank

Question: I was removing my hot water tank and realised there was some kind of insulation inside. Does this look like asbestos?

this is the material. My initial thoughts were fibreglass. Can anyone ascertain what the material is?
Comment: There are a lot of testing labs that will tell you within a week, but it will likely cost multiple tens of dollars.
Comment: I'm voting to close this question because the only way to know if something is asbestos is to have it lab tested. Even at the lab they can't tell just by looking at it.
Comment: Age of the tank? Only way to be sure about asbestos is lab testing. Looks the same in pictures as other stuff.
Answer: The only way to know if its asbestos or not is by testing it.  There are test kits you can buy at your local hardware store, these test kits require that you mail out the sample.  You can also Google "Asbestos testing center near me" their may also be a physical place you could take a sample to yourself.
If you take it to a physical location:
-put on a mask and gloves
-Put a sample in a zip-loc bag
-double seal that bag inside another zip-loc bag
If you buy a testing kit the directions will be similar.
Ive tested 7-10 differnt things in my own house that I thought was asbestos and they all came back as not asbestos and some other material.
Its really better to test than not test if youre worried about it.  Always good to have peace of mind.  Best of luck!
Comment: You can also tell by age of the tank.


Same class name in multiple namespaces in Visual Studio

Question: How to know if there is a class name repeated in different namespaces in Visual Studio? Obviously I'm not looking to test every class name manually.
Comment: If you move them use refactoring tools (VS, Resharper, ...) those will fix/alert most issues.
Comment: @HimBromBeere: But that's not what the OP was asking for. (And just having `using` directives for both namespaces wouldn't be enough - you'd then have to try to use the type.)
Comment: You get a compile-error saying either that compiler can´t identify the class or that the name is ambigios.
Comment: Do you mean within a specific assembly that you're testing? You could pretty easily write a unit test to do that with reflection.
Comment: @HimBromBeere: Only if it *is* being used ambiguously. It would be perfectly feasible to create a project which contained the same class name in two different namespaces but without any compile-time errors.
Comment: Disambiguation: I'm not receiving error. I'm looking for a solution to prevent repeating a class name multiple times in a large assembly with multiple namespaces.
Comment: It is simple to search class name via "Find in files" or other similar ways but I'm looking for a way to check for uniqueness of my defined class names through the assembly.
Comment: Why do you even care about this? Usually you get unambiguity by using the namespaces.
Comment: It is not a check for the uniqueness of the name of a specific class. I look for  a way to check all my class names.
Comment: @HimBromBeere I do get unambiguity but when reorganizing classes among namespaces, I need to be sure that I can move them inside assembly without being afraid of name conflict.
Comment: _I need to be sure that I can move them inside assembly without being afraid of name conflict_ - compiler will tell you faster then unit tests.
Comment: @Fabio You are right but meanwhile automatic renaming can be the source of future headaches.
Comment: Seems little bid odd, that while you are using strong typed programming language, you still need to check for types/classes ambiguity
Comment: No it is not odd. In general you should not be worried about duplicate names. Namespaces have been designed so you can have duplicate type names.
Answer: I'd just write a unit test that uses reflection. Something like:
<code>var duplicateGroups = typeof(SomeTypeInAssembly).GetTypes()
    .GroupBy(t => t.Name)
    .Where(g => g.Count() != 1);
// Assert that duplicateGroups is empty
</code>
Exactly how you assert that the collection is empty will depend on your test framework - you'll also want to make sure that when the test does fail, it gives you a useful failure message, ideally a list of the types in each group.