Two new, 256GB microSD cards. Both have problems mounting as ext4

Question: I bought a 256GB MicroSD card from Walmart recently, branded as 'Onn' which I suppose is a Walmart generic brand. I was able to format it as ext4, and then I tried to rsync to the card — which froze and corrupted the card.
I've had this happen before, where rsync is apparently too fast for the card and it corrupts it. So I reformatted, copied over my files, then moved the card to my PinePhone (which runs Mobian, a Debian distro), and it won't auto-mount, and I can only manually mount it as read-only.
So, I bought a Samsung EVO 256GB card from eBay. As soon as I got it, I removed the existing partitions, created a big, ext4 partition, and as soon as it was done, it said the system didn't have permission to mount the partition.
After this, every attempt to mount, from Nautilus or the command line, resulted in variations on this error message:
wrong fs type, bad option, bad superblock on /dev/sdf1,
       missing codepage or helper program, or other error

I ran fdisk, fsck, e2fsck, and tried to repair the filesystem from the GUI. Nothing worked. The only think that worked was to run mkusb and restore the card to a standard storage device.
Here are my questions:

The newer card shows up on my computer as 268GB, even though it's supposed to be a 256GB device. Is this a giveaway that it's a bootleg card? The packaging seemed legit and the seller was highly rated, but that seems suspicious to me.
Is there an issue formatting an SD of this size as ext4? I have never heard of such a thing.
Should I just leave the disk as FAT? I only use Linux for everything, so my impulse is to make everything ext4. I am going to put this disk in my PinePhone, and will be syncing to my server and to my computer, back-and-forth, and I have this idea that a FAT partition will store permissions differently and somehow complicate hte sync process. But that might be incorrect and it might just be standard to leave SD cards formatted the way they were purchased.

I'm running ubuntu 20.04.
Comment: I updated the question to include my Ubuntu version. The questions kind of lean on each other, so answering one might resolve the others.
Comment: Have you tried formatting the card(s) `exfat`?
Comment: Not explicitly — although I would assume it did format it this way, even though it says FAT32, because I thought FAT32 only went up to 32GB. Maybe it's FAT32+. Anyway, the card *seems* fine in its current format, but became unmountable as ext4.
Comment: Maybe try the f3 package to check the real card size.
Answer: OK, the answer to this question is that both cards were either fake, or low-quality.

If your card's capacity is more than advertised, that's almost certainly a tell that it's a fake card.
MicroSD cards can be formatted to Ext4 with no problem. However, you should remove journaling from the partition after you created it. You can do this by running tune2fs -O ^has_journal /dev/sdXY.
There's no problem with an ext4 SD card. If you're strictly Linux on all devices, it's a bad idea to format as FAT or any of its variants. I found that if I put a FAT device in my computer, and copied over files using mc, the copying was much slower when the card was FAT. I also have some files with a question mark in the filename, and these cannot be copied to a FAT volume. So I wouldn't recommend it.

Using F3 (Fight Flash Fraud) was a good suggestion, and it did identify one of the two cards as fraudulent. I think the other one is just low-quality and I have read, anecdotally, that these Onn cards from Walmart are rebranded Sandisk cards that didn't pass Q/A. I'm not sure if that's true, but it does seem like the card was more fragile and reformatting it revealed this.


$A \subset \mathbb{R}$ uncountable $\Rightarrow$ $ \exists ~I$ interval such that $A \cap I$ is dense in $I$?

Question: If $A \subset \mathbb{R}$ is uncountable, does it follow that there exists a non-degenerate interval $I$ such that $A \cap I$ is dense in $I$?
I was thinking that Cantor set might be a counterexample, but eventually I reached the conclusion that it isn't. I'm not really sure, though.
I think that we can assume WLOG that $A \subset [0,1]$. This is because if we choose $A_k=A \cap [k,k+1]$, then $A= \bigcup\limits_{k \in \mathbb{Z}}A_k$, and since this is a countable union, it follows that there exists $n \in \mathbb{Z}$ such that $A_n$ is uncountable. We can assume WLOG that $n=0$ and then we can just take the problem from the beginning, but now with $A_0$ instead of $A$.
I tried to solve the problem by contradiction, but I didn't succeed.
Comment: The cantor set is a counterexample. It is nowhere dense.
Answer: What you are asking is whether for an uncountable set $A$ the closure of $A$ has a non-void interior. So any Cantor set (uncountable, closed, and not containing an interval) will be a counterexample. Note that the Cantor space does not have connected subsets with more than one point, so this will work in many other spaces.
Answer: As said in the comments, the cantor set is a counterexample, as it has empty interior, so it is nowhere dense (if $C\cap I$ was dense, then it would equal $I$, since $C$ is closed).
Similar examples show that even if you strengthen the hypothesis to say that $A$ is of positive Lebesgue measure, this is still not true. However in this case, you do get something: by the Lebesgue density theorem, you have that if $A$ has positive measure (in fact, as large as you want, up to but not including full measure), then $A$ is dense at almost every point of $A$ in the sense of approximate density.
This shows that having large cardinality and measure imply nothing about category (in the sense of Baire category).


List<> - Reflection

Question: I'm trying to determine if a list contains a object, if it does then run a method to clear the original list (in a singleton class), then repopulate the list minus the one I ran the condition over.
public void removeSelectedItem(Object obj){
    SearchBuilder builder = SearchBuilder.getInstance();
    try {
        String methodName = labelToMethod.get(getTitle());
        if( methodName == null ){
            methodName = getTitle().replace(" ","");
        }
        Method m = builder.getClass().getMethod("get"+methodName);
        Object r = m.invoke(builder);
        if( r != null ){
            if( r instanceof Integer ){
                if( ((Integer) r).intValue() == ((Integer) obj).intValue() ) {
                    setSelectedItem(null);
                }
            } else if ( r instanceof String ){
                if(r.equals(obj)) {
                    setSelectedItem(null);
                }
            } else if ( r instanceof ArrayList ){
                Log.d("TEST",((ArrayList) r).size()+"");
                if( ((ArrayList) r).contains(obj) ){
                    Log.d("TEST", "R CONTAINS OBJ");
                    Log.d("TEST", "BEFORE: " + ((ArrayList) r).size() + "");
                    clearSelectedItem();
                    Log.d("TEST","AFTER: " + ((ArrayList) r).size() + "");
                    for ( int i = 0; i < ((ArrayList) r).size(); i++ ){
                        Log.d("TEST","IN FOR LOOP" + i);
                        if( !((ArrayList) r).get(i).equals(obj) ){
                            Log.d("TEST", "SETTING VALUES");
                            setSelectedItem(((ArrayList) r).get(i));
                        }
                    }
                }
            }
        }
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }
}

The clearSelectedItem method is:
    public void clearSelectedItem(){
    SearchBuilder builder = SearchBuilder.getInstance();
    try {
        String methodName = labelToMethod.get(getTitle());
        if( methodName == null ){
            methodName = getTitle().replace(" ","");
        }
        Method m = builder.getClass().getMethod("clear"+methodName);
        m.invoke(builder);
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }
}

The output I'm getting is:
D/TEST :  2
D/TEST :  R CONTAINS OBJ
D/TEST :  BEFORE: 2
D/TEST :  AFTER: 0

So it's not entering the loop, as the ArrayList size has been reduced to 0. But what I don't understand is, why has the ArrayList been reduced? Surely the object has been set as part of the m.invoke call earlier in the removeSelectedItem method, and the clearSelectedItem doesn't touch this response?
I'm rather new to Java, so any insight would be great!
EDIT:
So I've managed to solve my problem, but would still really like some insight into what's going on...
I've solved it by cloning the ArrayList:
                } else if ( r instanceof ArrayList ){
                Object c = ((ArrayList) r).clone();
                if( ((ArrayList) c).contains(obj) ){
                    clearSelectedItem();
                    for ( int i = 0; i < ((ArrayList) c).size(); i++ ){
                        if( !((ArrayList) c).get(i).equals(obj) ){
                            setSelectedItem(((ArrayList) c).get(i));
                        }
                    }
                }
            }

Comment: You are calling the 'get' method not the 'set' method at `Object r = m.invoke(builder);`.
Comment: Yes that's expected. The get method is used to get the original selected items which the removeSelectedItem function loops over and then resets the values via the setSelectedItem() method.
Comment: What is `SearchBuilder`?
Comment: SearchBuilder is a singleton class used to store search criteria. It's irrelevant for the question though. The issue is that the value of r.size() changes from before clearSelectedItems, and after.
Comment: `it's irrelevant for the question` no, it is not. your list `r` comes from `builder.getSomething()`, and your list is emptied when you call `builder.clearSomething()`. Clearly that's where the list is cleared.
Comment: That's correct. But by that stage `r` is an `ArrayList` containing the values. So why when I interrogate that list (which should already be defined) after clearing the super list in builder does my already defined list also get cleared?
Comment: It's like `r` is just a reference to the `ArrayList` in `SearchBuilder`.
Answer: So after a little more research, Java is pass-by-value, which means that it passes the reference to the ArrayList, rather than create a new ArrayList with the same values. Amending Object r in any way affects the original ArrayList in SearchBuilder itself.
http://www.javaranch.com/campfire/StoryPassBy.jsp
Answer: So I dont understand why you are repopulating the list itself,
would it be much cleaner or neat if you just use
    if(list.contain(object))
    {
       list.remove(object);
    }

or if you want to remove all of them just use
      while(list.contain(object))
      {
      list.remove(object);
      }

List<> - Reflection


How do you tell the amount of solution of this row reduced matrix?

Question: The first four correspond to the variables x, y, z and u and the fifth column corresponds to the right-sides.
The thing i'm asking is, how many solutions does this system of questions have and how do you find that out? Not sure how to think of it because there's no "Free variable"
Comment: (1) This is not a Mathematica question. (2) Dimension of solution space = #vars - #pivots.
Answer: Write down the equations and you get:
$$
x+\frac{88}{87}u=\frac5{29}\\
y+\frac{317}{87}u=\frac{77}{29}\\
z-\frac{184}{87}u=-\frac{21}{29}
$$
You see that you can easily get a solution depending on $u$ and $u$ is a free variable:
$$
x=\frac5{29}-\frac{88}{87}u\\
y=\frac{77}{29}-\frac{317}{87}u\\
z=-\frac{21}{29}+\frac{184}{87}u
$$


Error with array() function in python-3.x

Question: im new in python.
part of my code is:
def _checksum(self, data):

    if sum(len(i) for i in data) & 1:
        data.append('\0')

    **words = array('h', ''.join(data))**
    checksum = 0
    for word in words:
        checksum += word & 0xffff
    hi = checksum >> 16
    low = checksum & 0xffff
    checksum = hi + low
    checksum += (checksum >> 16)
    return ~checksum & 0xffff

in python 2 its work, but in python 3 have error:

TypeError: sequence item 0: expected str instance, bytes found

i'm understand have problem in code line:
words = array('h', ''.join(data))

but i not understand how to fix this
thank you for help!
Comment: Is that array() function np.array or something you defined?
Answer: The problem in your code is not with array(), but its with the join() function.
When you use join like
words = array('h', ''.join(data))

You are using the str.join method, which expects all arguments to be string. But in your data, the values are bytes or atleast the first one is bytes.
If you want to join bytes, then you must use it like
words = array('h', b''.join(data))

and all values must be bytes in data.


How to remove a long alphanumeric pattern in R

Question: I want to remove a 32 digit ID from a string. The ID is in 32 character/digit format separated by "-"
y <- c("abcd1234-ab12-cd12-1z12-abcd1234abcd6789 Print me I am ok")
What i need is the remaining part of the string "print me I am ok"
appreciate your help!
Comment: If all you really care about is the text that comes AFTER the first blank space character, then you can use the answer provided by @Brian `stringToTrim.Substring(IndexOf(" ") + 1)`, or if you know how many hyphens `-` there are you could also trim based on that `stringToTrim.Substring(33+num_of_hyphens)`
Answer: Will this help?
<code>string stringToTrim = "abcd1234-ab12-cd12-1z12-abcd1234abcd6789 Print me I am ok";
string result = stringToTrim.Substring(IndexOf(" ") + 1);
</code>
Comment: I was looking for a regex expression which can remove the 32 digit pattern. The 32 digit pattern can come anywhere in the string. Sorry if I was not very clear in the question..


File naming convention in XCode

Question: While at WWDC I noticed a file naming convention in. One of the demos that I had not seen before.  The example had :
AppDelegate.h
AppDelegate.m
AppDelegate_animation.m

The _animation file semed to have all animation related code.
Is this naming convention documented anywhere?
Answer: I haven't seen any Docs on the underscore, but here's a good start:
https://developer.apple.com/library/iOS/#documentation/Cocoa/Conceptual/CodingGuidelines/Articles/NamingBasics.html
Answer: I don't think apple has much in terms of documenting something as arbitrary as naming your object code files ..
Its an interesting idea, not even using a category, simply splitting the object code out and have the same header file be in charge of them both. (I personally prefer categories, seems like a more formal interface)
ie:
AppDelegate+Animations.h
AppDelegate+Animations.m

File naming convention in XCode


SOLR: SynonymFilterFactory with stemming

Question: If I understand correctly, the SynonymFilterFactory does not stem synonyms in any way. As such, one would have to be pretty exhaustive with plurals and tenses in their synonym file if they want good recall regardless of pluralization/tensing.
I see that the SynonymFilterFactory has an optional argument where it can accept an analyzer.

analyzer: (optional; default: WhitespaceTokenizerFactory) The name of the analyzer class to use when parsing the synonyms file.  If analyzer is specified, then tokenizerFactory may not be, and vice versa.

I doubt that nesting the desired analyzer like so is valid:
<analyzer type="query">
    <tokenizer class="solr.WhitespaceTokenizerFactory" />
    <filter class="solr.StopFilterFactory" ignoreCase="true" words="stopwords.txt" />
    <filter class="solr.WordDelimiterFilterFactory" generateWordParts="1" generateNumberParts="1" catenateWords="0" catenateNumbers="0" catenateAll="0" />
    <filter class="solr.LowerCaseFilterFactory" />
    <filter class="solr.SnowballPorterFilterFactory" />
    <filter class="solr.SynonymFilterFactory" synonyms="synonyms.txt" ignoreCase="true" expand="true" >
        <analyzer>
            <tokenizer class="solr.WhitespaceTokenizerFactory" />
            <filter class="solr.StopFilterFactory" ignoreCase="true" words="stopwords.txt" />
            <filter class="solr.LowerCaseFilterFactory" />
            <filter class="solr.SnowballPorterFilterFactory" />
            <filter class="solr.RemoveDuplicatesTokenFilterFactory" />
        </analyzer>
    </filter>
    <filter class="solr.RemoveDuplicatesTokenFilterFactory" />
</analyzer>

I suspect that compiling an extension analyzer .jar and placing it in SOLR's lib folder might be the only way to do this. Is there a way to define a named analyzer in configuration, or another method to accomplish this goal?
Answer: This does not answer my original question (about how to do this via configuration only), but is the solution I ended up using in the event that anyone else wants to do it.
First, a custom analyzer that will be used to pre-process the synonyms coming in from the Synonym filter (most importantly, stemming them with Snowball):
public class SnowballAnalyzer extends Analyzer {
    /**
     * Creates a
     * {@link org.apache.lucene.analysis.Analyzer.TokenStreamComponents} which
     * tokenizes text when given a reader.
     *
     * @return A
     *         {@link org.apache.lucene.analysis.Analyzer.TokenStreamComponents}
     *         built from an {@link WhitespaceTokenizer} filtered with
     *         {@link LowerCaseFilter} and English {@link SnowballFilter}.
     */
    @Override
    protected TokenStreamComponents createComponents(String fieldName) {
        Tokenizer source = new WhitespaceTokenizer();
        TokenStream filter = new LowerCaseFilter(source);
        filter = new SnowballFilter(filter, "English");
        return new TokenStreamComponents(source, filter);
    }

}

This is extracted as a .jar and deployed into your SOLR home's lib directory. Next, make sure to tell SOLR to use this analyzer in your synonym filter (usually in schema.xml or managed-schema):
<fieldType name="stemmedText" class="solr.TextField" positionIncrementGap="100">
    <analyzer type="index">
        <tokenizer class="solr.WhitespaceTokenizerFactory"/>
        <filter class="solr.StopFilterFactory" words="stopwords.txt" ignoreCase="true"/>
        <filter class="solr.WordDelimiterFilterFactory" catenateNumbers="1" generateNumberParts="1" generateWordParts="1" catenateAll="0" catenateWords="1"/>
        <filter class="solr.LowerCaseFilterFactory"/>
        <filter class="solr.SnowballPorterFilterFactory"/>
        <filter class="solr.RemoveDuplicatesTokenFilterFactory"/>
    </analyzer>
    <analyzer type="query">
        <tokenizer class="solr.WhitespaceTokenizerFactory"/>
        <filter class="solr.StopFilterFactory" words="stopwords.txt" ignoreCase="true"/>
        <filter class="solr.WordDelimiterFilterFactory" catenateNumbers="0" generateNumberParts="1" generateWordParts="1" catenateAll="0" catenateWords="0"/>
        <filter class="solr.LowerCaseFilterFactory"/>
        <filter class="solr.SnowballPorterFilterFactory"/>
        <filter class="solr.SynonymFilterFactory" expand="true" analyzer="your.package.SnowballAnalyzer" ignoreCase="true" synonyms="synonyms.txt"/>
        <filter class="solr.RemoveDuplicatesTokenFilterFactory"/>
    </analyzer>
</fieldType>

And finally, using the above type on whatever fields you want:
<field name="keywords" type="stemmedText" indexed="true" stored="false"/>

With this example, documents' keywords fields will be stemmed in the index. When a query is done on that field, the term will be stemmed then used to look up synonyms (that are already pre-stemmed by the custom analyzer). The result is that a synonym file containing "incomplete" synonym list (plurals, tenses) has a much higher chance of getting a match.
Specific example
Synonym file entry: [dog,doggy,dogs,canids,canid,puppy,pups,pup]
Search term: puppies (notice that it's not in the synonym list)
Parsed query: SynonymQuery(Synonym(keywords:canid keywords:dog keywords:doggi keywords:pup keywords:puppi))


Requests hanging on Session module on IIS 7.5

Question: From time to time, some requests on my website starts to hang on the RequestAcquireState state of the Session module. When that spiral begins all requests timeout and we need to restart the IIS on the affected server.
I investigated it a lot and the only conclusion I got is that somehow a deadlock is happening while the application tries to access user data stored in Session.
The only option I can think of to fix this issue is to either reduce or stop using Sessions in my application. This is definetely part of the plan, but it will take a while before we can complete that.
We run 6 machines with IIS 7.5, out of proc StateServer and server affinity on in our Load Balance.
Any hints on how to workaround this issue or fix it at all without having to remove Sessions entirely?
Comment: Have the same problem with my asp.net web forms 4.0 app & iis 7.5... any suggestion ?
Comment: Is there by any case some page do a lot of work, eg, some process, or the download/upload of a big file ?
Comment: No, most of the pages are read only. It's an e-commerce application. When the problem is not happening the average response times of all pages are between 70 and 80ms.
Comment: Have you considered switching to SQL Server state mode? You can also eliminate server affinity in your load balancer and prevent users' sessions from getting dropped with a server meltdown.
Comment: Another thing I would check is how bloated the session state is at time of failure. When you login to the server and look at task manager, find aspnet_state.exe, is it hogging memory, soaking CPU, etc?
Comment: And one more thing... [Here's an article](http://bytes.com/topic/asp-net/answers/329298-aspnet_state-exe-internals-info-needed) that discusses how aspnet_state works behind the scenes and how things get "persisted" to there or how they might actually get held in the w3wp.exe process and not get flushed/GCed. Thought might be relevant reading for you.
Comment: Next time the problem happens I will make sure to check that. Thanks. For now I'm reducing the amount of call to the Session by using a local cache to see if it improves.
Answer: Lock mechanism exist on both provider and session module (IIS Session Module). You can develop custom session module, but you still need provider without locking or You can develop custom provider without locking but you still need IIS session module and it is not so simple to implement at that level.
The Solution is UnlockedStateProvider [aka Unlocked]
Follow the white rabbit :P (Check the demo project, it explains everything.)
Answer: The answer is Hotfix Rollup 2828841 for .NET Framework 4.5 , here all the explanation:
http://forums.asp.net/t/1888889.aspx/2/10?Question+regarding+a+possible+bug+within+NET+4+5
and here the download link
It works for me on IIS 7.5 Windows Server 2008 rs x64 , asp.net web forms application with lot of ajax request.
Comment: Actually the download link does not allow to download this hotfix.
Comment: Thanks. I'm gonna try it and get back here.
Comment: I didn't pay attention to the framework the hotfix applies to until I got it. I'm not using framework 4.5, but 4.0 so this hotfix does not apply. Thanks though.
Comment: Following is the discussion on a user forum where a person describes how he tried to contact Customer Support to get this hotfix. https://social.msdn.microsoft.com/Forums/vstudio/en-US/abc2ff86-c03b-4d4b-91b8-83006062f97b/download-hotfix-rollup-2828841?forum=msbuild
Answer: I just found out today that if you have a long running request (or in my case, an infinite loop), then all subsequent requests will be locked, because by default ASP.NET locks on session.
So if you have users with requests in RequestAcquireState, then check if there is a request in ExecuteRequestHandler that is locking the session, and thus preventing other requests from starting.
There is a discussion here on how to prevent locking on session.
(Basically, create most of your pages as Session-Read-Only, and modify session as rarely as you can.)
Answer: Is it possible those users have another long running request and the requests you see piling up are actually secondary requests? By default, ASP.NET will lock Session until a request is complete. If a second request comes in before the first one is complete, it will have to wait. If you are using MVC, you can change this behavior by adding an attribute to your controller.
[SessionState(SessionStateBehavior.ReadOnly)]
This makes Session read-only, removing the locking behavior allowing subsequent requests to be processed.
Comment: Why would the first request hang in the first place? The issue is pretty much the same if that's the case. I'd still have hanging requests with no reason.


Multiple S3 events together trigger a lambda function

Question: I have a scenario where I have two buckets s3-a and s3-b.
When data is put into s3-a it sends out an S3 event.
The same happens with s3-b.
I need to trigger a lambda function when I have the data in both the S3 buckets.
One way I could think of is use a dynamodb as a marker if a corresponding S3 object is found, then through dynamodb streams invoke a lambda which checks if both the markers are true.
Comment: Why do you keep posting the same question, slightly differently each time, instead of updating your original question?
Comment: This is a bit different one Mark, though it looks similar to the other one.
Answer: Check the data in both buckets in each trigger. Whichever trigger finds data in both buckets, proceeds further. Make it Idempotent so that if both triggers find the data in both buckets, there is no adverse effect.
Comment: Should I be thinking of to use a ddb to ensure that they are idempotent
Comment: that is up to you how you implement it.


Make text in sharepoint left navigation as hyperlink

Question: I am using calendars in Sharepoint 2016. I created Team Calendar as below in image. However it is not hyperlink. I need that as hyperlink. I have code which works in console, but not when added in script editor

 $('.ms-acal-apanel > ul >li > ul > li > span').each(function(){
    $(this).wrapInner('');
});

Any help will be appreciated. Thanks in advance.
Answer: Add script editor content like this:

Or


Is importing headers bad?

Question: What are your opinions on <code>#import</code>ing header files?
If I import:
<code>#import <Foundation/Foundation.h>
#import <QuartzCore/QuartzCore.h>
#import <UIKit/UIKit.h>
</code>
and many more headers, and only use them once in a while, is it a waste?  Does it slow down my app in any way?  More importantly, does it increase the size of my app?
Thanks.
Answer: Nope, it doesn't do any of those things.
Headers are used by the compiler to determine how to find where various types and classes are defined. Extraneous #imports do--kinda sorta--make the process of compiling your app slower by some unmeasurably small amount.
But the resulting binary application will not be any different in size or execution speed if you have redundant headers imported in your files.
Answer: Adding to quixoto's answer, Objective-C added the
<code>#import
</code>
Header.  The original C header was:
<code>#include
</code>
The difference is that #import actually checks to see if you have already included the header in your code.  If you have, the #import statement does nothing.
Comment: Thanks for the additional info.

Is importing headers bad?


Ionic Capacitor 404 eror - inappbrowser is not in the npm registry

Question: I got an error 404 from running inappbrowser plugin
npm install @ionic-enterprise/inappbrowser

npm ERR! code E404
npm ERR! 404 Not Found - GET https://registry.npmjs.org/@ionic-enterprise%2finappbrowser - Not found
npm ERR! 404
npm ERR! 404  '@ionic-enterprise/inappbrowser@latest' is not in the npm registry.

I have also run npm config set registry https://registry.npmjs.org/  but still get the same error
Answer: @ionic-enterprise/inappbrowser is a private plugin, you can only install it if you are a paid customer or are on trial period. If you are in one of those situations, contact support so they can help you configure your machine to install packages from the private registry.
Answer: If your using cordova this would do it:ionic cordova plugin add cordova-plugin-inappbrowser --save


Can a receptacle be added to a lamppost?

Question: I'm adding a post and a post-mounted light fixture in the backyard. Some posts have an outlet at the bottom, but they appear to always have a "decorative ladder rest" (with plastic golden balls!) that is an eyesore. Is it possible to add a receptacle to a plain post?
The plan is to use this light, which fits on a 3" post.
Comment: So are you asking how to add a receptacle, or looking for shopping guidance?
Comment: @TheEvilGreebo, in the question, neither. I've asked whether a receptacle can be added to a plain post. In the comments, I replied to your shopping guidance with comments about shopping guidance. Should I clarify the question?
Comment: http://www.arcadianlighting.com/cm-z8984.html - you haven't looked hard enough.
Comment: @TheEvilGreebo, thanks for the suggestion, but that thing made me barf. I'm still looking for the with-outlet, without-ladder-rest version of a plain black pole.
Comment: I guess that's [this one](http://www.arcadianlighting.com/hk-6610-bk.html), if you believe the description and not the picture. Thanks for the link.
Answer: There is no reason you could not, if you followed the standard requirements for outdoor recepticles, such as

Ground Fault Circuit Interrupter (GFCI)
sealed box
properly protected cable

However, this is likely to be a bulky add on.

Cutting a hole in the post presents a problem becasue you need to install a sealable box and sealable cable connections.
Finding a post that already has a UL listed outlet is probably a safer, easier and maybe cheaper alternative. (See comment by @The Evil Greebo) A manufacturer can design an integrated housing for the outlet and get it UL rated, whereas you need to rely on off-the-shelf parts (read not custom fit) to get the same safety and performance.
Also, on the posts you have seen so far, it might be easier to remove the decorative items and plug them with small caps or finials than adding a safe outlet.
Comment: @JeremyW.Sherman In an ideal world, but I would be nervous about drips into the pole from the lamp attachment point or other joints. Better safe . . .
Comment: +1. I was going to suggest just hacksawing off the ladder rest bars as well. That seems a ton easier than retrofitting a receptacle into the pole.
Comment: Though I believe if you put the jbox wholly in the pole, it would not need to be WP, because it's now in a dry location. You'd just need gasketing for the cover. (Good luck finding a gasketed cover that matches the tight curve of a pole.)
Answer: You don't need the bulky solution posted by @bib.
In my yard I have exactly what you are looking for, a receptacle on a plain 3-inch pole.  Google "Design House 502112", available from a variety of sources including Home Depot.  It's called a "replacement" receptacle, but it can be added new by drilling a 1-3/8" hole in the side of the pole.
The biggest issue with this item is that the cover is not terribly rugged... mine broke after 8 years of regular use (which is why I am replacing it now), but I've seen other reviews indicating quicker failure.
Answer: I guess a lot depends upon just how you are doing your light. If you are purchasing a ready-made light pole with integrated light fixture then the ability to add the outlet would depend on how the pole is constructed. For instance if the pole was a smallish pipe type thing at one inch diameter adding an outlet would be a completely different thing than adding an outlet to the cast metal base that was eight or ten inches in size.
If you are making your own post out of wood adding an outlet may simplest if the post was constructed as a box construction out of boards as opposed to being a solid timber.
In either case the ability to add an electrical outlet is possible if you select the proper type of post.
Of course you can even go the route of using surface mounted exterior electrical boxes and conduit but that can be rather ugly and mostly suitable for purely utilitarian applications.


What if the hosting Django server don't have the module I imported?

Question: I have imported "smtplib" in the code, and I doubt that the server won't have this installed. Is there a CDN for modules in python ?
Comment: `smtplib` is part of the python standard library. So dont worry. If a lib is not make uae of `pip` and `requirements.txt`.
Comment: no, you have to install-it on the pythonpath
Comment: you can first install it on the server using pip command
Comment: If you don't control the python packages that are installed in your application's environment, you need a better hosting provider.
Answer: You should save your dependencies in a requirements.txt file and use pip to install the requirements as part of your Django app's deployment process.
Edit: smtplib is part of the standard lib, so it should be available out of the box.
Comment: For third-party packages, yes. However smtplib is part of the standard library as does not need installing.


Appending data into an undeclared list

Question: Every once in a while the following scenario turns up while I code in Python:
I iterate through a loop and find that I want to store the intermediate values of a variable in a list to be used later. Following is a very basic sample code:
for x in range(0,10):
    y = x*x
    temp_list.append(y)

The problem is temp_list has not been declared yet. So I usually navigate to the top of the loop and then add the following:
temp_list = []
for x in range(0,10):
    y = x*x
    temp_list.append(y)

While this may seem trivial, I was just wondering whether there is any pythonic way to create a list if it does not exist and then append a value to it, or else if it exists, just append?
Comment: You could use a try/except block to check if x is set (`try: \ x \ except NameError: \ x = []`), but that's not really very pythonic IMHO. (NOTE: I'm using '\' to indicate line breaks here)
Comment: Yes that was what I was thinking. But I was wondering the try except block would consume more time. As you can see the exception will be only on the first attempt after which we do not require it at all. If the number of iterations in the loop are very high, will the try except block add a lot of overhead?
Comment: I'm not sure how it is in python, but IIRC, in other languages, try blocks are only expensive when they throw.
Answer: For your very base sample it can be done using list comprehension:
l = [x*x for x in range(0, 10)]

Comment: @Pulimon: You can always use list comprehension by putting your complex piece of code into a function of (even better) a generator function.
Comment: True, but like I said this is just a sample code. Usually I would have to store an intermediate variable 'y' which is available inside a big loop. Also the value of y is obtained after a lot of data processing which we may not be able to describe in a single line. In other words, I may not be able to use list comprehension
Comment: @Ber Done, thank you - it was just an option - to show that variables can be obtained by locals
Answer: It should be always clear if a variable is declared or not. How otherwise would you like to access it?
What you can do dynamically is a dict entry:
a = {}

for x in range(0,10):
    y = x*x
    a.setdefault('temp_list', []).append(y)

The a['temp_list'] will be created only if needed.
Comment: Oh this is an interesting approach
Answer: Depending in your problem, a good "pythonic" way of dealing with that sort of structure could be to abstract it into a generator.  For your trivial example:
def squares():
    for x in range(0,10):
        y = x*x
        yield y

Then:
temp_list = [i for i in squares()]

Very often when you need a temporary list like that its because you are running a series of operations on your data, each of which involves another loop.  Using generators instead can significantly improve both performance and memory usage because they result on only a single loop.
Note that for trivial examples its usually easier to write a generator expression:
temp_list = (x*x for x in range(0, 10))

If you want a not-so-pythonic way of doing it, you can edit the locals dictionary, but this is not really a good idea since it leads to obfuscated code:
for x in range(0, 10):
    y = x*x
    locals().setdefault('temp_list', []).append(y)

Answer: Another way to solve using locals as per OPs template,
for x in range(0,10):
   y = x * x
   temp_list = temp_list + [y] if "temp_list" in locals() else [y]

print(temp_list)

gives,
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

[Program finished]

but yes, this should probably be solved with list comprehension

Appending data into an undeclared list


Do you need to delete imported files from Documents/Inbox?

Question: I've got an iOS app that imported files from an email attachment.
I've noticed that once i'm finished with it it places the imported file into Documents/Inbox.
Should my app be deleting these files or does the OS eventually get around to clearing them out?
if so, how? i've tried:
[[NSFileManager defaultManager] removeItemAtPath:[self.url path] error:nil];

However it doesn't seem to reference the file in the inbox, even though self.url is the correct path to my import file.
Answer: System does not clear imported files, so you should clear them manually when it is necessary, but not to delete the Documents directory.
How to clear the NSDocumentsDirectory you can find here
If you want to delete files from the inbox use the same code adding
...
NSString *path = [NSString stringWithFormat:@"%@/Inbox", documentsDirectory ];
NSArray *directoryContents = [fileMgr contentsOfDirectoryAtPath:error:&error];
...

Read the reference
From apple doc:

Use this directory to access files that your app was asked to open by
  outside entities. Specifically, the Mail program places email
  attachments associated with your app in this directory; document
  interaction controllers may also place files in it.
Your app can read and delete files in this directory but cannot create new files or write to existing files. If the user tries to edit
  a file in this directory, your app must silently move it out of the
  directory before making any changes.
The contents of this directory are backed up by iTunes.
Comment: this doesn't clear the Inbox. this Inbox folder seems to be a special folder. its created by the system, not my app. i can't delete it using this method.


What determines what type of weapon will be produced through a weapon fusion?

Question: I've noticed a fusion of two weapon types will always produce the same weapon type, so I assume there is some sort of system for determining the weapon type produced, as opposed to it being random.
What determines what type of weapon will be produced through a weapon fusion?
Answer: You are right, this is a predictable system. In order to figure out what weapon you will get, you will need to know a few different things in order to figure it out.
First, you need to know what weapon combinations will result in the weapon type that you are going after. This (translated) chart will help with that:
From there, you need to know what "number" the weapon you want to make is. There are 12 of each weapon type, and they are numbered from 1 to 12. This chart lists the weapon numbers for each of the weapons in the game:
When you fuse two weapons together, you just add those numbers together to get the number of the resulting weapon. If the result is higher than 12, it just wraps back around to 1; in other words, if the two weapon numbers add up to a number that is higher than 12, subtract 12. (For example, if you want to make a Palutena Blade, you could use the Cragalanche Cannon plus the Dark Pit Staff  -  12 + 11 = 23, 23 - 12 = 11.)
If the fusion results in just an X and a ?, it means that you haven't unlocked the weapon in-game yet, and you can't just fuse things to create it. You will need to explore the game more completely, finish more levels, etc. to unlock all of the available weapons, but then you can fuse things to your heart's content.
This is not entirely foolproof - sometimes you might randomly get something you didn't expect. it does work most of the time, however. Also, there hasn't been a way (as of yet) to know what stars and abilities get carried over when you fuse weapons, unfortunately.
Comment: Exceptions to the table:
Samurai Blade + Earthmaul Club = Arlon Orbitars
Rose Staff + Eyetrack Orbintars = Samurai Blade
Knuckle Staff + End-All Arm = Gaol Blade
Somewhat Staff + Virgo Palm = Upperdash Arm
Dark Pit Staff + Fortune Bow = Palutena Blade
Stealth Claws + Violet Palm = Rail Cannon
Hedgehog Claws + Ogre Club = Great Reaper Palm
Angel Bow + Phosphora Bow = Viridi Palm
Angel Bow + Drill Arm = Centurion Orbitars
Cursed Palm + Ball Cannon = Black Club
Pudgy Palm + Fireworks Cannon = Phoenix Arm
Ogre Club + Rail Cannon = Dark Pit Staff
Shock Orbitars + Volcano Arm = Dynamo Cannon
Comment: And also First Blade + Centurion Orbitars = Palutena Bow. For another view of the same information see http://www.kidicaruswiki.org/Weapon


Openshift: Uploading File not possible / Sending emails not possible

Question: I have a small web project where I use openshift as a service for a test system.
Now I got 2 problems:
1) I have a form in which a user shall upload a picture. For that I use multipartfile. But the file upload just doesn't work, while it does locally under dev.
So now I ask myself if I need to configure something on the server. But I couldn't find out what (and why).
2) I am sending emails after a certain action. Which again runs perfectly fine under development, but not using my test system on openshift. If I remember correctly it was a 415 error, I have to repeat the test at home to look it up.

I can't give more information right now as I'm not yet home, but I don't think that much code is needed as it all works fine testing it locally.
I post this question rather for a quick answer like "uuh yeah, for openshift applications you need to configure it first for doing those things: here and there, make this and that and read here" which I oversaw.
I hope someone can give me some hints, I don't get why it all works locally but not on a test system.
Answer: Quick Answer:
Make sure your file uploads are being sent to your <code>$OPENSHIFT_DATA_DIR</code> and for email check out this post https://www.openshift.com/forums/openshift/send-mail-through-openshift-using-gmail or use something like SendGrid which is free in the OpenShift Marketplace.
If those don't help, posting some application logs will be really helpful
Comment: Thanks for your response. I found out that I actually got an entire different problem which might is probably the root problem of all: I can't send payload over POST requests. Maybe you could you take a look [>here<](http://stackoverflow.com/questions/25894284/openshift-415-erorr-restful-communication-with-payload-not-possible)? I created a new question instead editing this one..


How i can filter my data in angularJS throw links?

Question: i have

in html its looks like:

                    Все бренды

{{ brand.name }}

One item in my Json looks like this:
{
    "name": "Bra by Joseline",
    "category": null,
    "price": 8370.0,
    "old_price": 8370.0,
    "vendor": {
        "id": 1,
        "name": "Agent Provocateur",
        "seo_name": ""
    },
    "recommended": [],
    "id": 750
}

i want filtering my items by "vendor.name" field and i have no idea how make it reality, its my first expirience in angularJS, sorry for noob question :)
My controller look like this:
 (function () {
    'use strict';

    angular
        .module('beo.products.controllers')
        .controller('ProductsListController', ProductsListController);

    ProductsListController.$inject = ['$scope', '$http'];

    function ProductsListController($scope, $http) {

        $scope.setMainClasses('catalog-page');

        activate();

        function activate() {

             $http.get('api/v1/products/').success(function(data) {
                  $scope.products = data;
                  $scope.ProductSortLeft = '-id'; //по умолчанию фильтроваться будут по обновлению
            });
            $http.get('api/v1/categories/').success(function(data) {
                  $scope.categories = data;
            });

            $http.get('api/v1/shops/').success(function(data) {
                  $scope.shops = data;
            });

            $http.get('api/v1/vendors/').success(function(data) {
                  $scope.vendors = data;
            });
        }
    }

})();

I use filter columns like these:
    <filter></filter>

Уведомление о рапродаже

        <select class="selectpicker" ng-model="ProductSortLeft">
            <option value="-price">Самые дорогие</option>
            <option value="price">Самые дешевые</option>
            <option value="click_count">Популярные</option>
            <option value="-id">Новые</option>
        </select>

            Бесплатная доставка $150+

        {{ product.name }}

{{ product.old_price }}

            {{ product.price }}

                Получить скиду

Comment: you can use custome filter for this.
Comment: Do you mean to *sort* (display in a different order) instead of filter? Otherwise, I can't understand your question.
Comment: i add my controller, can you help me with custom filter?
Comment: @Hulehule20 i add html where i use filters column
Answer: You can filter on vendor.name like this:

var app = angular.module('myapp', []);
app.controller('myctrl', function($scope) {
  $scope.filter = "";
  $scope.brands = [{
    "name": "Bra by Joseline",
    "category": null,
    "price": 8370.0,
    "old_price": 8370.0,
    "vendor": {
      "id": 1,
      "name": "Agent Provocateur",
      "seo_name": ""
    },
    "recommended": [],
    "id": 750
  }, {
    "name": "Another brand",
    "category": null,
    "price": 8370.0,
    "old_price": 8370.0,
    "vendor": {
      "id": 1,
      "name": "Agent Bond",
      "seo_name": ""
    },
    "recommended": [],
    "id": 750
  }]
});

  <input ng-model="filter" placeholder="filter" />

{{ brand.name }}

Comment: I need filtering by links :(
Comment: I guess I was confused by your sentence 'i want filtering my items by "vendor.name" field '... I don't see any urls in the json, where are the links coming from?
Comment: yeah right, i want filter by vendor.name, but like here ( http://www.shopstyle.com/browse/handbags )
Comment: after tap on link, or check box i want to get my sorting items list


jQuery Validate: Retaining error after validation

Question: I have a simple login form and have jQuery validate replacing the field labels when there's an error to display. The problem is that, once the error is cleared, the label disappears. I would like to find a way to revert back to the previous label's content, or rebuild that label  when the field is valid...
Here's my code:
$(document).ready(function(){
    $("#login").validate({
        errorPlacement: function(error, element) {
            element.prev().replaceWith(error);
        },
        rules: {
            "email": {
                required: true,
                email:true,
            },
            "password": {
                required: true,
                minlength: 6
            }
        },
        messages: {
            email: {
                required: "Please enter your email address.",
                email: "Please enter a valid email address"
            },
            password: {
                required: "Please enter your password.",
                minlength: "Please enter a password with 6 characters or more."
            }
        },
    });
});

And the HTML:
<form name="login" id="login" method="post" action="authenticate.php">

    Email Address:
    <input type="text" name="email" id="email" class="required email" />

    Password:
    <input type="password" name="password" id="password" class="required" />

    <input type="submit" value="Log In" id="submit" />

In essence, when the user submits the form, if there's no data in the Email field, then the label for email gets replaced with the error. But once it has valid input, I want to put back the original label.
Thanks in advance for any suggestions,
Z
Comment: It may not be possible, but you might fiddle around with the `highlight` and `unhighlight` functions, and from those save off the old label, and the re-set it on `unhighlight`.
Comment: Thanks for the reply. I actually worked out a compromise whereby, instead of replacing the previous label with the error label, I'm appending a span into that label using error.appendTo(element.prev()) and errorElement: "span".

It's less than ideal, but at least when the span appears, the error code is where I want it to be, and when it disappears, the label remains intact.

I just made it so the label and the error complete each other like sentences... Eg, "Email Address" " is required." or "Email Address" " is not properly formatted."

(PS: Sadly, it seems that linebreaks don't work)
Comment: Ah, that is a decent solution, I agree...  I suggest you post an answer to your own question, and mark it as accepted (this is 100% OK on StackOverflow).  That way anyone else that finds this question will know a good answer.
Comment: It wouldn't let me do that earlier, but now it seems okay. Thanks again for help.
Answer: I actually worked out a compromise whereby, instead of replacing the previous label with the error label, I'm appending a span into that label using error.appendTo(element.prev()) and errorElement: "span". Here's the new code:
            $(document).ready(function(){
            $("#login").validate({
                errorElement: "span",
                errorPlacement: function(error, element) {
                    error.appendTo(element.prev());
                    //element.prev().replaceWith(error);
                },
                rules: {
                    "email": {
                        required: true,
                        email:true,
                    },
                    "password": {
                        required: true,
                        minlength: 6
                    }
                },
                messages: {
                    email: {
                        required: " is Required",
                        email: " is Improperly Formatted"
                    },
                    password: {
                        required: " is Required",
                        minlength: " is not Long Enough"
                    }
                },
            });
        });

It's less than ideal, but at least when the span appears, the error code is where I want it to be, and when it disappears, the label remains intact. I just made it so the label and the error complete each other like sentences... Eg, "Email Address" " is required." or "Email Address" " is not properly formatted."
Thanks to everybody that contributed here,
Z
Answer: You can remove
errorPlacement: function(error, element) {
         element.prev().replaceWith(error);
     },

and the messages should appear beside the textboxes instead.
Comment: The challenge here is that I want it to appear exactly where the label is -- not beside or below the text box.
Answer: You can try to removeChild(label),and attach a new one to it when the error accur. Toggling the label seems to make sence
Comment: Thanks for the reply. Part of my problem seems to be an inability to place the relevant code inside of a function that's triggered when the error clears.


'&' before the parameter name

Question: Just a quick and no doubt easy question. I'm pretty new to PHP and am looking through some existing code. I have tried to find the answer to my question on google, but to no avail.
Can somebody please let me know what the '&' sign before the parameter $var does??
function setdefault(&$var, $default="")
{
  if (! isset($var))
  {
    $var = $default;
  }
}

Answer: Passes it by reference.
Huh?
Passing by reference means that you pass the address of the variable instead of the value.  Basically you're making a pointer to the variable.
http://us.php.net/language.references.pass
Answer: It means that the function gets the reference to the original value of the argument $var, instead of a copy of the value.
Example:
function add(&$num) { $num++; }

$number = 0;
add($number);
echo $number; // this outputs "1"

If add() would not have the ampersand-sign in the function signature, the echo would output "0", because the original value was never changed.
Answer: & means pass-by-reference; what that code does is check whether the variable passed to the function actually exists in the global scope. Without the & it'd try to take a copy of the variable first, which causes an error if it doesn't exist.
Answer: This means that you are passing a variable by reference https://www.php.net/language.references.pass.  Simply this means the function is getting an the actual variable and not a copy of the variable.  Any changes you make to that variable in the function will be mirrored in the caller.
Answer: It's indicating that the parameter is passed by reference instead of by value.

'&' before the parameter name


Failed to fetch repositories

Question:
Possible Duplicate:
How to install software or upgrade from old unsupported release?
How can I fix a 404 Error using the Ubuntu archives?

I am having trouble downloading the Ubuntu repositories:
$ sudo apt-get update
...
Failed to fetch
http://archive.ubuntu.com/ubuntu/dists/maverick/main/binary-amd64/Packages.gz
404  Not Found

Failed to fetch
http://archive.ubuntu.com/ubuntu/dists/maverick/restricted/binary-amd64/Packages.gz
404  Not Found
...

I can connect to the server fine:
# ping archive.ubuntu.com
PING archive.ubuntu.com (18.104.22.168) 56(84) bytes of data.
64 bytes from sudice.canonical.com (126.96.36.199): icmp_req=1 ttl=52 time=149 ms
64 bytes from sudice.canonical.com (22.214.171.124): icmp_req=2 ttl=52 time=149 ms
64 bytes from sudice.canonical.com (126.96.36.199): icmp_req=3 ttl=52 time=149 ms

--- archive.ubuntu.com ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 2001ms
rtt min/avg/max/mdev = 149.221/149.305/149.355/0.321 ms

Here is my sources.list:
deb http://archive.ubuntu.com/ubuntu maverick main restricted universe
deb http://archive.ubuntu.com/ubuntu maverick-updates main restricted universe
deb http://archive.ubuntu.com/ubuntu maverick-security main restricted universe

and system details:
lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 10.10
Release:    10.10
Codename:   maverick

Any ideas?
Answer: As a release gets old (especially if it is not a LTS release), it becomes no longer hosted at archive.ubuntu.com. However, the repository is still hosted at
http://old-releases.ubuntu.com

So try changing your repository source to http://old-releases.ubuntu.com.
Comment: Thanks - that did it. I am surprised there is no redirect.

Failed to fetch repositories


how to mock async PermissionsAndroid.request in jest?

Question: I have this code in react native i want to make a test:
const granted = await PermissionsAndroid.request(
          PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
          {
            title: 'Device current location permission',
            message: 'Allow app to get your current location',
            buttonNeutral: 'Ask Me Later',
            buttonNegative: 'Cancel',
            buttonPositive: 'OK',
          }
        );

i am looking at an answer here but seem not working: How to mock PermissionAndroid from react native
jest.doMock('react-native/Libraries/PermissionsAndroid/PermissionsAndroid', () => ({
  ...jest.requireActual('react-native/Libraries/PermissionsAndroid/PermissionsAndroid'),
  request: () => ({
    [PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION]: PermissionsAndroid.RESULTS.GRANTED,
  }),
  check: () => true,
}));

on ios i am doing it like this which was quick:
jest.spyOn(Geolocation, 'requestAuthorization').mockResolvedValue('granted');

i can't seem to think of a way how to do it in android?
Answer: I could recommend you to try with react-native-permissions. It already have a mock file that you can use. You can use Jest + React Testing Library Native.
In my case I used a jest-setup.js file
import {jest} from '@jest/globals';

jest.mock('react-native-permissions', () =>
  require('react-native-permissions/mock'),
);

Then configure jest inside you package.json file
"jest": {
    "preset": "react-native",
    "setupFilesAfterEnv": [
      "@testing-library/jest-native/extend-expect"
    ],
    "transformIgnorePatterns": [
      "node_modules/(?!(jest-)?react-native-permissions|)"
    ],
    "setupFiles": [
      "./jest-setup.js"
    ]
  }

For Geolocation service I created a react-native-geolocation-service inside __mocks__/react-native-geolocation-service.js
export default {
  getCurrentPosition: jest.fn().mockImplementation(successCallback => {
    const position = {
      coords: {
        latitude: 57.7,
        longitude: 11.93,
      },
    };
    successCallback(position);
  }),
};

In your App component you could have this
import React, {useEffect, useState} from 'react';
import { View } from 'react-native';
import {check, request, PERMISSIONS, RESULTS} from 'react-native-permissions';
import Geolocation from 'react-native-geolocation-service';

const App = () => {
  const [location, setLocation] = useState(null);

  const handleLocationPermission = async () => {
    let permissionCheck = '';
    if (Platform.OS === 'ios') {
      permissionCheck = await check(PERMISSIONS.IOS.LOCATION_WHEN_IN_USE);

      if (permissionCheck === RESULTS.DENIED) {
        const permissionRequest = await request(
          PERMISSIONS.IOS.LOCATION_WHEN_IN_USE,
        );
        permissionRequest === RESULTS.GRANTED
          ? console.warn('Location permission granted.')
          : console.warn('Location perrmission denied.');
      }
    }

    if (Platform.OS === 'android') {
      permissionCheck = await check(PERMISSIONS.ANDROID.ACCESS_FINE_LOCATION);

      if (permissionCheck === RESULTS.DENIED) {
        const permissionRequest = await request(
          PERMISSIONS.ANDROID.ACCESS_FINE_LOCATION,
        );
        permissionRequest === RESULTS.GRANTED
          ? console.warn('Location permission granted.')
          : console.warn('Location perrmission denied.');
      }
    }
  };

  useEffect(() => {
    handleLocationPermission();
  }, []);

  useEffect(() => {
     Geolocation.getCurrentPosition(
        position => {
            const {latitude, longitude} = position.coords;
            setLocation({latitude, longitude});
     },
     error => {
       console.log(error.code, error.message);
     },
     {enableHighAccuracy: true, timeout: 15000, maximumAge: 10000},
      );
     }, []);

  return (<View></View>)
}

Then in you test file you can test the behaviour using React Testing Library Native.
import React from 'react';
import {render, waitFor} from '@testing-library/react-native';
import App from '../App';
import {check} from 'react-native-permissions';
import Geolocation from 'react-native-geolocation-service';

describe('<UserScreen />', () => {
  test('should check for permissions', async () => {
    render(<App />);

    await waitFor(() => {
      expect(check).toHaveBeenCalledTimes(1);
      expect(Geolocation.getCurrentPosition).toHaveBeenCalledTimes(1);
    });
  });
});

I wrote a similar and more detailed Post on my website.


Finding the derivative of a composite function

Question: So i'm working on this problem and am not sure if i'm applying the chain rule correctly because i'm arriving at what appears to be an incorrect answer.
Find $\frac{dw}{dx}$ if $u = \frac 12x^3$, $v=3(u + u^2$), and $w = \frac{1}{v^2}$
Am I right in thinking I should apply the chain rule?
$$f(g(h(x)))' = {f'(g(h(x)))} {g'(h(x))} {h'(x)}$$
Next I took the derivative of each of those functions to come up with:
$ \frac{d}{dv} = \frac{-2}{v^3}$, $\frac{d}{du} = 3(1 + 2u)$, and $\frac{d}{dx} = \frac{3x^2}{2}$
Next I multiplied these derivatives together, simplified and substituted all v's and u's out with their original values until I just had x's, and then simplified more (used calculator for much of this instead of doing by hand)
Is that the correct approach and i'm messing up the algebra at the end, or did I mess up the application of the chain rule?
Answer: Yes that's exactly the correct approach, and the derivatives you computed are correct; if you get an incorrect final answer, check your algebraic manipulations. The only remark I'd add is on your notation. To be accurate, you should write $(f \circ g \circ h)'(x)$ rather than $f(g(h(x)))'$. This is because you are differentiating the composite function $f \circ g \circ h$ and evaluating it at the point $x$ (The RHS of that equation is correct though).
Also, $\dfrac{d}{dv} \neq \dfrac{-2}{v^3}$; strictly speaking this doesn't make sense. You should have written $\dfrac{dw}{dv} = \dfrac{-2}{v^3}$ instead, or $\dfrac{dw}{dv} \bigg|_{v} = \dfrac{-2}{v^3}$ to be more proper and indicate that you're evaluating at the point $v$, and likewise for the other derivatives.
Comment: Thanks for confirming I was on the right track and also for the correction on notation. As a beginner, I find the notation is a tricky thing to understand on its own.


Bootstrap 3 Navigation Toggle not working

Question: I copied over the navbar example from the docs and it worked fine.  I made several edits and now the toggle button is not working.  I've looked at several threads in StackOverflow and haven't found anything that's helping me.  Here is my code:

            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#addressToolBar">
                Toggle navigation

            </button>

                <button class="dropdown-toggle btn btn-primary navbar-btn" data-toggle="dropdown" role="button" aria-expanded="false">4203 Afton Ln </button>

4203 Afton Ln, 78744

4511 Elwood Rd, 78722

8518 FM 1826, 78736

  add new

  import

            <form class="navbar-form navbar-left address-search" role="search">

                        <input type="text" class="form-control" placeholder="Search">

                            <button type="submit" class="btn btn-default"></button>

            </form>

                    Other

 export

 get all invoices

 billing options

 delete

 Edit

 Add New

Here is a (non-working) fiddle.
Answer: Your toggle button has a lower z-index than other elements, hence you can select it. Just add this line to your CSS and problem solved :
.navbar-toggle {
    z-index: 100000;
}

See Bootply for reference
Answer: Your nav toggle is working fine. The issue is being caused by this bit of code

    <button class="dropdown-toggle btn btn-primary navbar-btn" data-toggle="dropdown" role="button" aria-expanded="false">4203 Afton Ln </button>

4203 Afton Ln, 78744

4511 Elwood Rd, 78722

8518 FM 1826, 78736

  add new

  import

With position relative it is covering the entire width of the nav and so the toggle button is behind it and cant be pressed.
You could look at changing the position or at adding a z-index:xxxx; to the toggle button to keep it on the top layer.


What curve is bell shaped in the normal distribution?

Question: The normal distribution is characterized by the bell shaped curve.

My question is that which curve is bell shaped in the normal distribution? Is it the frequency histogram, the relative frequency curve, or the PDF that is bell shaped?
Comment: The density function is bell shaped
Comment: Then why I do see that it is the frequency histogram in some places?
Comment: From Wikipedia : "Histograms give a rough sense of the density of the underlying distribution of the data."
Comment: https://en.m.wikipedia.org/wiki/Histogram#:~:text=Histograms%20give%20a%20rough%20sense,is%20always%20normalized%20to%201.
Comment: Thanks. What about the relative frequency curve?
Comment: https://en.wikipedia.org/wiki/Normal_distribution
Answer: The normal distribution is continuous - it can take any value in the real numbers. Any value it takes has a zero probability of being exactly repeated - frequencies will be 0 or 1. So it has a probability density function, not a freqency curve.
A frequency histogram represents discrete values which may occur more than once. That might be for a discrete distribution (e.g. the Binomial) which is approximately normal, or for sample data from a normal distribution that has been grouped into ranges giving frequencies greater than 1. So when you see a freqency histogram in the classic bell shape, you're seeing something that approximates to, or derives from, a normal distribution.


jQuery - Grab a  ID and distribute it to its children

Question: I've been trying to grab the #id of a DIV and pass it to each of it's children with jQuery to no avail.

    Link 1
    Link 2

    Link 1
    Link 2

turns into..

I'm using..
$("div.gallery").each(
    function(){
    var galleryCount = $("div.gallery");
    $("div a:has(img)").attr( "rel", galleryCount );
    }
);

..but that just ends up giving me [ object, Object ]. It looks like it's counting both div.gallery's and trying to assign both of them to rel.
How do I grab just the parent id and apply it to it's children?
Comment: Ok there aren't enough green check marks to go around on this one, so future n00bs that stumble on this page try everything.
Answer: Use the below code
$(document).ready(function(){
    $(".gallery").each(function(){
        rel = $(this).attr("id");
        $(this).find("a").attr("rel",rel)
    });
});

Comment: There are so many right answers, it's amazing I didn't fall into one. Thanks.
Answer: The correct way to do it is:
$("div.gallery").each( function()
{
    var $this = $(this);
    var id = $this.attr('id'); // <-- Get the ID attribute

    $this.children("a").attr("rel", id);
});

Here's a working example.
Comment: You're still setting the rel attribute of all `a`s instead of just the children.
Comment: This applies the first gallery id to all links. :( or atleast it did in my test.

Edit: you people are quick!
Comment: The working example I've included just does exactly what you asked.
Answer: This should work (untested):
$("div.gallery").each(function(){
    var galleryId = $(this).attr('id');
    $("a:has(img)", this).attr( "rel", galleryId);
    }
});

Comment: This worked! Could you explain why exactly? I get that.. using this selects div.gallery, and get it's id via .attr, but i'm not clear on what the second this is doing.
Comment: The second parameter of the `$`/`jQuery` function is a context. You could also use `$(this).find('a:has(img)')`
Comment: Looks like I have to hit the books harder. Thank you.
Answer: Take the children, add the rel-attribute, change the inner html to img.
$(".gallery").children().each(function(){
    $(this).attr("rel", $(this).parent().attr("id"));
    $(this).html("");
});

outputs:

Comment: This also works, although in my current circumstance it's easier if I don't have to explicitly put each image in the javascript. Incomplete question on my part. Thank you!
Answer: It sounds like you want to apply the id of each parent to the rel attribute of it's children? Try:
$('.gallery').each(function () {
    $(this).find('a').attr('rel', $(this).attr('id'));
});

Here's the jsFiddle
Comment: This also works, and this one is easier for me to read. ..so .find, finds whats inside .gallery correct?
Comment: Thank you! I'll have to start fiddling with that more.


Where to find logs for "Low Disk Space"

Question: After seeing the window popping up that shows

Low disk space | The volume "Filesystem root" has only X MB disk space remaining.

Where can we find the log file that logs this low disk space warning?
If it is not logged by default, how can we log it so that we can record down some details like the timestamp of this event?
Output of cat /var/log/syslog | grep -i disk:
Sep  5 09:10:11 foo systemd[1]: dev-disk-by\x2duuid-4d64b496\x2d3e08\x2d497f\x2d9e51\x2d40db25c7710b.device: Job dev-disk-by\x2duuid-4d64b496\x2d3e08\x2d497f\x2d9e51\x2d40db25c7710b.device/start timed out.
Sep  5 09:10:11 foo systemd[1]: Timed out waiting for device dev-disk-by\x2duuid-4d64b496\x2d3e08\x2d497f\x2d9e51\x2d40db25c7710b.device.
Sep  5 09:10:11 foo systemd[1]: Dependency failed for File System Check on /dev/disk/by-uuid/4d64b496-3e08-497f-9e51-40db25c7710b.
Sep  5 09:10:11 foo systemd[1]: systemd-fsck@dev-disk-by\x2duuid-4d64b496\x2d3e08\x2d497f\x2d9e51\x2d40db25c7710b.service: Job systemd-fsck@dev-disk-by\x2duuid-4d64b496\x2d3e08\x2d497f\x2d9e51\x2d40db25c7710b.service/start failed with result 'dependency'.
Sep  5 09:10:11 foo systemd[1]: dev-disk-by\x2duuid-4d64b496\x2d3e08\x2d497f\x2d9e51\x2d40db25c7710b.device: Job dev-disk-by\x2duuid-4d64b496\x2d3e08\x2d497f\x2d9e51\x2d40db25c7710b.device/start failed with result 'timeout'.
Sep  5 09:34:55 foo systemd[1]: dev-disk-by\x2duuid-4d64b496\x2d3e08\x2d497f\x2d9e51\x2d40db25c7710b.device: Job dev-disk-by\x2duuid-4d64b496\x2d3e08\x2d497f\x2d9e51\x2d40db25c7710b.device/start timed out.
Sep  5 09:34:55 foo systemd[1]: Timed out waiting for device dev-disk-by\x2duuid-4d64b496\x2d3e08\x2d497f\x2d9e51\x2d40db25c7710b.device.
Sep  5 09:34:55 foo systemd[1]: Dependency failed for File System Check on /dev/disk/by-uuid/4d64b496-3e08-497f-9e51-40db25c7710b.
Sep  5 09:34:55 foo systemd[1]: systemd-fsck@dev-disk-by\x2duuid-4d64b496\x2d3e08\x2d497f\x2d9e51\x2d40db25c7710b.service: Job systemd-fsck@dev-disk-by\x2duuid-4d64b496\x2d3e08\x2d497f\x2d9e51\x2d40db25c7710b.service/start failed with result 'dependency'.
Sep  5 09:34:55 foo systemd[1]: dev-disk-by\x2duuid-4d64b496\x2d3e08\x2d497f\x2d9e51\x2d40db25c7710b.device: Job dev-disk-by\x2duuid-4d64b496\x2d3e08\x2d497f\x2d9e51\x2d40db25c7710b.device/start failed with result 'timeout'.
Sep  5 10:03:12 foo systemd[1]: dev-disk-by\x2duuid-4d64b496\x2d3e08\x2d497f\x2d9e51\x2d40db25c7710b.device: Job dev-disk-by\x2duuid-4d64b496\x2d3e08\x2d497f\x2d9e51\x2d40db25c7710b.device/start timed out.
Sep  5 10:03:12 foo systemd[1]: Timed out waiting for device dev-disk-by\x2duuid-4d64b496\x2d3e08\x2d497f\x2d9e51\x2d40db25c7710b.device.
Sep  5 10:03:12 foo systemd[1]: Dependency failed for File System Check on /dev/disk/by-uuid/4d64b496-3e08-497f-9e51-40db25c7710b.
Sep  5 10:03:12 foo systemd[1]: systemd-fsck@dev-disk-by\x2duuid-4d64b496\x2d3e08\x2d497f\x2d9e51\x2d40db25c7710b.service: Job systemd-fsck@dev-disk-by\x2duuid-4d64b496\x2d3e08\x2d497f\x2d9e51\x2d40db25c7710b.service/start failed with result 'dependency'.
Sep  5 10:03:12 foo systemd[1]: dev-disk-by\x2duuid-4d64b496\x2d3e08\x2d497f\x2d9e51\x2d40db25c7710b.device: Job dev-disk-by\x2duuid-4d64b496\x2d3e08\x2d497f\x2d9e51\x2d40db25c7710b.device/start failed with result 'timeout'.

Comment: Is the goal just to monitor a computer's available storage space over time?
Comment: Can you edit our question and post the result of `cat /var/log/syslog | grep -i disk` please?
Comment: What is your Ubuntu version and desktop environment?
Comment: @matigo Yes, and the disk space available fluctuates wildly so I am trying to get an approximate timestamp of when it goes really low.
Comment: @N0rbert 14.04, 16.04, both using Mate desktop
Comment: @darth_epoxy Updated with the output you requested. The other `syslog*` files contains more of the same
Comment: 14.04 EOL, 16.04 EOL. What is your current system? Why do you show Unity on screenshot?
Comment: @N0rbert Ugh I got confused with another system, Mate is the correct desktop environment. I'm stuck on 14.04 and 16.04 for these machines due to a software being used that requires them
Comment: See my below answer. Just tested on 16.04 LTS MATE VM - log monitoring shows that this low-space warning is not logged. .
Comment: You may want to set up some sort of disk space monitoring that works independently of your desktop environment. Something as simple as a cronjob doing `df -k / | tail -n 1 | logger` every hour or even every minute may be enough.
Answer: This dialog is generated by desktop settings daemons. Depending on the flavor the list includes:

cinnamon-settings-daemon
gnome-settings-daemon
mate-settings-daemon (your case, based on comments)
ukui-settings-daemon

For MATE log monitoring shows that this low-space warning is not logged. You can check space distribution using MATE Disk Usage Analyzer (mate-disk-usage-analyzer) or via CLI - using ncdu. Then you can move/remove huge files in your home directory.
Cleaning old kernels, kernel headers and package cache may be useful - try commands below:
sudo apt-get clean
sudo apt-get autoremove --purge

Where to find logs for "Low Disk Space"


How sensitive is tagging on the PC version?

Question: I have noticed that Jet Set Radio is now available on Steam as Jet Set Radio HD. I was wondering how well this works on a PC using a keyboard - the reason I ask, I have played this game extensively on a Dreamcast, and one of the key points of the game is to 'tag' various parts of the environment (such as busses, walls, gates, etc) with your art.
On the Dreamcast, this was done with the analogue sticks, and if you didn't do exactly the arrangement as prompted on screen you had to start again. This is shown in the screenshot below;

On the Dreamcast this would have involved rotating the analogue stick clockwise, and then anti-clockwise, in quick succession.
Since a PC keyboard is not capable of making these movements, how does tagging work on the PC version of Jet Set Radio? Has it been tweaked to make it less sensitive to failure or would I need an analogue gamepad in order to play this game on PC?
Answer: Unfortunately, the keyboard controls for Jet Set Radio are pretty terrible. Upon launching the game, you're met with the following pop-up:

This, unfortunately, isn't very intuitive when it comes to tagging sites in the actual game.
After some trial and error, I discovered the solution for tagging areas such as the one in your screen shot.

Right before this screenshot was taken, I had a single down arrow. I managed to complete it by pressing S. However, upon completing that, I was met with what you see here. My first two attempts at this ended in complete failure. Eventually, I learned that the appropriate pattern for this particular arrow was: S > D > W. If I didn't do it fast enough, it failed, wasting a can of paint. If I did it too fast, it failed, wasting yet another can of paint.
So, long story short (too late!), the keybindings for keyboard use during tagging is horrible. While it doesn't require a gamepad to play, you would probably find your experience much more enjoyable if you used one.


All LibreOffice windows are in one menu icon

Question: In Ubuntu 18.04 using GNOME, all of the opened LibreOffice windows are concentrated under one LibreOffice menu icon.
This is unlike the former versions where each application (Writer, Calc ...) had its own icon. This is very uncomfortable when you have many windows opened.
Is there any way to change this setting?
Comment: Yes, I was under Wayland session. Logging back to normal session solved the problem.
Comment: This is not standard behaviour. Also in Ubuntu 18.04, different components of LO have a different icon. Is your installation a standard fresh install? Beware that, as a bug, it may take up to 30 seconds before the icon of another LO component actually appears in Alt+tab (or the Dash if not pinned).
Comment: Are you by any chance in a Wayland session? What's the output of the following command in Terminal: `echo $XDG_SESSION_TYPE`?
Comment: I do have different icons for each component, but it only opens new files. All of the existing files are under the LibreOffice icon.
Comment: It depends... if you install from PPA, you will have separate icons... installing from web page (deb files), you will have one icon in case of installing the development version...
Answer: This is a bug with LibreOffice in a Wayland session (see this and this). You can verify whether you're in a Wayland session by running
<code>echo $XDG_SESSION_TYPE
</code>
As a workaround you may switch to an Xorg session. Then the icons should appear correctly.


$\sin 2x = 1/2, 2x = 150, 390$. But why not 30?

Question: $0<x<360$
So $\sin(2x) = \sin (30 + 360)$ or $\sin(2x) = \sin (180-30)$.
It derives from
\begin{align*}
\sin x - \cos x & =\frac{1}{\sqrt2}\\
\sin^2 x + \cos^2 x -2\sin x \cos x & = \frac{1}{2}\\
2\sin x \cos x & = \frac{1}{2}
\end{align*}
But why not $\sin (2x) = \sin (30)$ ? So $x = 15$.
The answer only $x = 75$ and $195$.
Comment: Yes, why not? What's stopping you? Who told you you shouldn't have $2x = 30^\circ$? Also, don't forget $540^\circ - 30^\circ$. And $720^\circ + 30^\circ$. And $900^\circ - 30^\circ$. And ... Not to mention the negative angles.
Comment: If you want to type math enclose it between dollar signs $, i.e write \$0<x<360\$
Comment: By squaring you introduced extra solutions where $\sin x-\cos x=-\frac1{\sqrt 2}$
Comment: $x = 15º$ is also correct, but we also need the domain in order for your question to make sense.
Comment: How do you get from $\sin x-\cos x=\frac1{\sqrt 2}$ to $\sin(2x)=\frac12$?
Answer: We have that
$$\sin 2x = \frac12=\sin 30° \iff 2x=30°+k360° \quad \lor \quad2x=180°-30°+k360°$$
therefore all the solutions are in the form

$x=15°+k180°=15°,15°\pm 180°,15°\pm360°,\ldots$
$x=75°+k180°=75°,75°\pm 180°,75°\pm360°,\ldots$

and for the range $0°\le x <360°$ the solutions are $15°$, $75°$, $195°$, $255°$.


Weird XAML parsing error when trying to set TextBox.IsReadOnly

Question: I've managed to reduce this to a simple test case. An exception is thrown during the parsing of this XAML using XamlReader.Parse():
<DockPanel xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <DockPanel.Resources>

        </Style>
    </DockPanel.Resources>

    <TextBox IsReadOnly="True" />
</DockPanel>

The exception message is:

Cannot set unknown member 'System.Windows.Controls.TextBox.IsReadOnly'. Line number '13' and line position '11'.

If I don't set IsReadOnly on the TextBox, it parses fine. It also parses fine if I remove the style trigger.
Can anyone shed some light on this? I'm rather new to WPF.
UPDATE:
Here's the unit test I'm using to reproduce this (it's failing on my PC):
[TestMethod]
public void TestIsReadOnlyOnTextBox()
{
    // Arrange
    var xaml =
@"<DockPanel xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation"" xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml"">
    <DockPanel.Resources>

        </Style>
    </DockPanel.Resources>

    <TextBox IsReadOnly=""True"" />
</DockPanel>
";

    // Act
    try {
        var root = XamlReader.Parse(xaml);
    }
    catch (XamlParseException ex) {
        Assert.Fail(ex.Message);
    }

    // If we get here, test passes
}

UPDATE 2:
I was originally referencing just PresentationFramework v4.0.30319. Adding references to PresentationCore, System.Xaml, and WindowsBase has no effect.
.NET version of project is 4 (full, not client profile).
UPDATE 3:
Arg, this works fine in ExpressionBlend 3.0.1927.0 and XamlPadX 4. As reported by AresAvatar, it seems to only fail when parsed with XamlReader.Parse() or XamlReader.Load()!
Comment: @Cameron, I had tried just the Xaml at the top, which works.  It's XamlReader.Parse that is broken.  The exception has an inner exception from the XamlWriter, but the details are the same.  I say report it to Microsoft.
Comment: Your code worked fine for me.
Comment: Also worked fine for me.  What version of WPF are you using?
Comment: OK, I reproduced your problem using your test code with XamlReader.Parse.  This looks like a Microsoft bug to me.
Comment: Try out to change IsReadOnly by TextBox.IsReadOnly
Comment: I'm assuming the assembly with your unit tests references all the proper assemblies?
Comment: @CodeNaked: I've added the exact test case code I'm using (which fails here).
Comment: @AresAvatar: I'm using WPF shipped with .NET 4
Comment: @CodeNaked: I'm referencing PresentationFramework v4.0.30319. Am I missing anything else?
Comment: @CodeNaked: Added those, plus PresentationCore. Still no dice.
Comment: This only does not work for me when put into Kaxaml, wonder why...
Comment: @AresAvatar: How did you get it to work before?
Comment: @sll: Just saw your comment and tried -- no effect.
Comment: @AresAvatar: OK, thanks. This is embedded in a WinForms app, so we use `XamlReader.Load(stream)` (which causes the same exception).
Comment: Try changing `TargetType="TextBox"` to `TargetType="{x:Type TextBox}"`, just for my sanity. I had a weird problem that occurred from not using the longhand notation.
Comment: I bet you'll need to set an appropriate ParserContext.  Sure _your_ code has access to all the assemblies and whatnot you're referencing.  Doesn't mean the parser does...
Comment: @Adam: I tried your suggestion, but to no avail
Comment: @Jeff: I tried using an explicit parser class, but I'm not sure which other assemblies I'd need to reference (I'm not using any special ones as far as I can tell). Could you expand on your comment?
Comment: @Cameron: `XamlReader.Parse()` has an overload that accepts a `ParserContext`.  I'm saying everything you need is probably set in that context.  I don't know how to set it myself, I've been messing with this for a while but couldn't figure out how this should be set.  You should look into this.
Comment: @Jeff: Thanks for the suggestion, I'll poke around with that a bit. It works if I remove the `IsReadOnly="True"` though, which leads me to think it's not something in the context.
Comment: I am getting this on a DataTemplate in 2021, .net 5
Comment: I had same issue today on .Net 6.
It build just right but decided to replace it with aplying style.
Answer: Short answer, clearly this is a bug. The following can be used as a workaround.
Update, workaround 2
Even just executing the following line before XamlReader.Parse(xaml) fixes the problem, still clueless as to why though..
XamlReader.Parse(@"<TextBox xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation""
                            xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml""
                            IsReadOnly=""True""/>");
var root = XamlReader.Parse(xaml);

Workaround 1
Using Boolean in mscorlib instead of True in the Trigger seems to fix the problem for good. The following xaml does not throw an exception in XamlReader.Parse
var xaml =
@"<DockPanel xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation""
             xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml""
             xmlns:s=""clr-namespace:System;assembly=mscorlib"" >
    <DockPanel.Resources>
        <s:Boolean x:Key=""BooleanTrue"">True</s:Boolean>

        </Style>
    </DockPanel.Resources>
    <TextBox IsReadOnly=""True"" />
</DockPanel>";

Some research details..
I did some testing of this weird problem.
First I included the working DockPanel in Xaml and saved it with
string xaml = XamlWriter.Save(theDockPanel);

just to see if that piece of xaml was working with XamlReader.Parse, and it did.
Then I made small changes to the generated xaml (and reverted once the exception came back) until I got as close as possible to the original. The weird part is that once this xaml has been parsed, the original works as well.
The part that made it working seems to be using <s:Boolean>True</s:Boolean> instead of True.
var modifiedXaml = @"<DockPanel xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation""
                                xmlns:s=""clr-namespace:System;assembly=mscorlib""
                                xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml"">
                <DockPanel.Resources>
                    <s:Boolean x:Key=""BooleanTrue"">True</s:Boolean>

                    </Style>
                </DockPanel.Resources>
                <TextBox IsReadOnly=""True"" />
            </DockPanel>";

var originalXaml = @"<DockPanel xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation""
                                xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml"">
                <DockPanel.Resources>

                    </Style>
                </DockPanel.Resources>
                <TextBox IsReadOnly=""{Binding}""/>
            </DockPanel>";
try
{
    // If this line is executed, no `XamlParseException` is thrown
    var root = XamlReader.Parse(modifiedXaml);
    var root2 = XamlReader.Parse(originalXaml);
}
catch (XamlParseException ex)
{

}

I'll update again if I find something more on this..
Comment: The second workaround is nice and short, and only needs to be executed once. The `x` namespace isn't needed, so it can be shortened to `XamlReader.Parse("");`. Thanks!
Comment: Holy cows that's weird! Thanks for the workaround, I'll play around with it tomorrow and get back to you.
Comment: Had the same problem with a DatePicker where the inner DatePickerTextBox would complain. Changing from IsReadOnly="True" to True did the trick. Thanks!
Answer: One of my clients experienced this on one install - I could not repro it myself.
In my instance the Text property was bound to an underlying view model's string property, and the IsReadOnly property was set to "True" in xaml as in the first example from Cameron.

The problem was solved by changing the binding to the Text property's mode to OneWay.
<TextBox Text="{Binding SomeProperty, Mode=OneWay}" IsReadOnly="True" />

Comment: This was what I encountered.  The TextBox was bound to a readonly property and without the Mode=OneWay (or OneTime) it would generate the runtime exception.
Answer: I had this problem happen to me on a WPF application using Telerik UI for WPF 2017.2 using implicit styles.
I'm posting this here because it is very likely that others will reach this question looking for the error message:

Cannot set unknown member 'System.Windows.Controls.TextBox.IsReadOnly'

Normally, the implicit style XAMLs are configured with build action of "Resource", if you change it to build action "Page", all the Telerik controls are displayed correctly.
Source: Telerik feedback page
So far, I've only needed to change the build action on Telerik.Windows.Controls.Input.xaml but your mileage may vary. At least you will not have to change the implicit styles like I did.
PS: I hope this workaround sheds some light to anybody that has a similar issue or is trying to investigate the apparent bug on the .NET XamlReader
Answer: The XamlParser won't automatically load extra assemblies such as System.Windows.Interactivity which is where Triggers are defined. Try declaring a dummy variable from that assembly in code prior to parsing the Xanl. Alternatively, use Assembly.Load to load the assembly.
Comment: I tried your suggestion using `var dummy = TriggerCollection.ShouldSerializeStoredWeakReference(null);` (randomly chosen method). Still same exception. I suspect it's not the trigger in general, since it parses fine if I remove the `IsReadOnly="True"` attribute on the `TextBox` element itself. It's `System.Windows.Interactivity`, by the way
Comment: Based on the other answer it sounds like it might be mscorlib that is not being loaded in time. This sounds very strange but it might be worth trying to declare a boolean variable prior to the Parse call.
Comment: I added a dummy boolean variable, but it didn't change the behaviour. I have a hard time believing that the code could run at all without mscorlib being loaded ;-)
Comment: Based on the other answer and how the original code is parsed correctly after the workaround it still seems as if 'something' is not being loaded correctly. The workaround that I described was required to parse Xaml containing a Telerik RadChart. I agree though - mscorlib not loading seems very unlikely.


Cannot get to the resources under webroot folder

Question: So i downloaded the source zip for the framework and lithium just now.
I unpacked the lithium zip into the correct directory(all this is on a windows machine) and then used filezilla to upload to my host as a test.
The lithium page shows up fine, but it's not styled.
The folder structure is

/sample/app
/sample/libraries/lithium/{lithium core extracted here}.

I didn't make any changes to the files at all.
Replicated the problem in development environment.
Error in firebug is:
"NetworkError: 404 Not Found - http://localhost/sample/css/debug.css"
Answer: I think this is a hint that path rewriting is not working. Do you use Apache? If so, you need to enable mod_rewrite
on my server, this is the right command:
<code>sudo ln -s /etc/apache2/mods-available/rewrite.load /etc/apache2/mods-enabled/rewrite.load
</code>
You can also check out my installation instructions for my browser game based on lithium up until to the Chapter "Creating a user" its pretty generic Lithium setup
https://github.com/BitAlchemists/Elenears-Erben/wiki/Installation
Comment: um i dont know exactly what you did =) but you can write an answer yourself and accept it
Comment: basically the .htaccess from the app root didn't make it to the production server. As a result, even if you have mod_rewrite on, it doesn't know its supposed to rewrite anything.
Comment: what did you do with the .htaccess file?
I just downloaded the lithium framework but the css files are not loading. Ive had a similar problem before, and think it was something in the .htaccess files that needed to be changed..


How to avoid the bug when you cannot join either team - class change and team change keys not working

Question: Sometimes during the map restart, when there are many people joining blue or red team, I usually meet the bug when I choose a team to join, but it fails (due to too uneven number of players probably), and when I try to choose a team again, nothing happens - pressing , or . doesn't work - neither class menu nor team menu is appearing, and all I see is the map aerial view with scoreboard. The only thing to do is to re-connect to that server (which is not always possible if the server is full and you're still connected but 'stuck', so no player slot is available).
How to avoid this or how to prevent, or how to recover from such a bug?
Comment: "Asked 4 years ago"?!? Valve should have fixed this by now :((
Comment: @Christian Busy with Half-Life 3, obviously ))
Answer: In order to avoid it I suggest to not try entering more than once in the door of specified team, if the first time fails selected random.
Anyway, if it happens that you got stuck, you can easily recover from this bad situation by opening console and write
retry

Retry command force a server reconnection and you access again the team selection screen. Sometimes, on busy servers with many people try connecting, this command causes to lose the slot.
For this reason, as suggested by @Dave McClelland in comments, is preferable use the command
spectate

because it fix the problem without forcing a re-connection.
If you really want to join RED or BLU team and reduce the probabilities to trigger that annoying behavior, I suggest to wait that half or more users on the server choose their own team, and then try enter your desired door.
Comment: @mbaitoff Yes, `spectate` should work for you without forcing a reconnect
Comment: @Drake I have found people say that executing `spectate` in the console unsticks you from the "limbo" and puts you in the spectators class without the need of reconnection. Gonna try it also.
Comment: @Drake I don't want the rep, as the OP had already found that part of the answer for himself by the time I commented.  Feel free to add it to your answer once you confirm
Comment: Well, if I want to select a specific team, that won't help - I just have to try entering that team continuously until it succeeds. However, the idea with `retry` is very promising - gonna try it today. By the way, was this bug ever reported to Steam Support, - is it a "by-design" behavior or indeed a bug?
Comment: Sometimes even `retry` doesn't guarantee you your slot. I tried this on popular servers and I get kicked out with "Server is full." That said, it works much of the time.
Comment: @mbaitoff Good question, it seems well known on community of hardcore TF2 players, but I do not know if someone ever submit this bug to Valve. I added another suggestion.
Comment: @mbaitoff I didn't know spectate command, I will try it too. You can update my answer of if you prefer write a new one with that command.
Comment: @Dave McClelland: Wow, that'd be awesome if the servers I went to allowed spectating in the first place.
Comment: @Pyro Find better servers, then :)
Answer: I think it may be related to maximum team number on server for MvM matches and also the robots being regarded as opposing team members (auto_balance / team_balance issue related issue [supposedly... :P])
I had this problem non stop every time I started tf2 for all attempted connects to tf2 MvM matches. Normal matches were fine. I have found that by joining servers that have 5 or less players resolves the problem for MvM (for me anyway) if more players join the server (5+) the problem does not reproduce, you can remain on that server with map changes and player increases and the bug does not reoccur.
As the default for server maximum team for MvM matches is 6, joining a game with 5 players or less guarantee's a spot (in theory..) despite how ever many bots / robots their are :) I would say this is a bug that valve should look at, not that I cbf submitting it myself (lol) A simple man with simple goals. Hope this helps someone. If it doesn't, I apologise.
PS: I forgot to add, none of the above commands worked for me. All they did was what they describe.. (eg spectate, retry) with same results. Good Luck!
Answer: Just type in console: jointeam [red/blu/spectate]
Comment: Have you tried this yourself?
Comment: Yes i did do that. and surely it works
Comment: Sorry for the bump. I am commenting here just to say the issue still exists and this is the solution that works best for me. Much better than reconnecting, and sometimes the bug still persists after a `retry`. This is the only one that solves for me.


Making A Redstone Switch in Minecraft Bedrock Edition

Question: I've made a redstone clock and I have a line of redstone that flashes. I want to make a lever which when is activated, allows the redstone clock to function, and when is off, stops its functioning. How do I make such a switch?
Comment: Most MCJava clocks with those properties should do the same in MCBE. This article lists a bunch of them that can be toggled: https://minecraft.gamepedia.com/Mechanics/Redstone/Clock_circuit
Answer: You'll need a repeater clock:
Run a lever into the front of a block. Then, on the left of the block, place a sticky piston facing away from the lever, and on the right of the block, place a redstone torch on the block. In the direction of the front of that block, place three redstone next to the redstone torch. Then, connect two repeaters on the left of this dust - the closest repeater to the block should be facing away from the redstone, and the other repeater should be facing towards it. You should also place 1 redstone dust to the left of this second repeater. Finally, attach a different block to the sticky piston.
See the image if instructions are unclear.

This should function as a toggleable clock for most purposes.


Exporting raw alpha with ImageMagick

Question: I need to extract raw alpha from images in order to pass this to an application for use as an opacity mask.  The expected format is 8 byte unsigned ints per pixel.  How can I do this with ImageMagick?  I have tried convert image.png image.a but the .a file does not seem to have the correct data.
What is the best way to extract the alpha with ImageMagick?  Ideally, this would work with any input image format that supports alpha or transparency.
Answer: Try this:
$ convert -size 16x16 xc:none -draw "stroke black fill red circle 8,8 4,4" circle_on_transparent_bg.png

$ convert circle_on_transparent_bg.png -channel A -separate -depth 8 gray:image_alpha.raw

$ od -t x1 image_alpha.raw
0000000    00  00  00  00  00  00  00  00  00  00  00  00  00  00  00  00
*
0000040    00  00  00  00  00  01  20  89  be  8a  20  01  00  00  00  00
0000060    00  00  00  00  10  ff  ff  ff  ff  ff  ff  ff  12  00  00  00
0000100    00  00  00  13  ff  ff  ff  ff  ff  ff  ff  ff  ff  11  00  00
0000120    00  00  01  ff  ff  ff  ff  ff  ff  ff  ff  ff  ff  ff  01  00
0000140    00  00  21  ff  ff  ff  ff  ff  ff  ff  ff  ff  ff  ff  1f  00
0000160    00  00  8d  ff  ff  ff  ff  ff  ff  ff  ff  ff  ff  ff  89  00
0000200    00  00  c0  ff  ff  ff  ff  ff  ff  ff  ff  ff  ff  ff  ff  00
0000220    00  00  8b  ff  ff  ff  ff  ff  ff  ff  ff  ff  ff  ff  93  00
0000240    00  00  21  ff  ff  ff  ff  ff  ff  ff  ff  ff  ff  ff  24  00
0000260    00  00  01  ff  ff  ff  ff  ff  ff  ff  ff  ff  ff  ff  01  00
0000300    00  00  00  10  ff  ff  ff  ff  ff  ff  ff  ff  ff  11  00  00
0000320    00  00  00  00  12  ff  ff  ff  ff  ff  ff  ff  10  00  00  00
0000340    00  00  00  00  00  01  23  91  c4  8e  22  01  00  00  00  00
0000360    00  00  00  00  00  00  00  00  00  00  00  00  00  00  00  00
0000400

Answer: Try this:
convert image.png -channel A -separate image_alpha.png

Well, it's quite straightforward: you take alpha channel and save it to another file. Script outputs with 1-channel png (8 byte per pixel).
Comment: This is a good first step but I need a raw data file out of this rather than a PNG.  Any ideas?
Comment: Hmm. I don't think, it's possible out of the box. You should write own program using one of the IM ports (http://imagemagick.org/script/api.php): it will extract the alpha channel, writes it to image in memory, iterates through its pixels and writes it to the file in needed format. As an option, consider using BMP - its format is quite simple and mostly consists of raw data.

Exporting raw alpha with ImageMagick