JQuery.ajax success function returns empty

Question: I have a very basic AJAX function in JQuery:
$.ajax({
    url: "http://www.google.com",
    dataType: "html",
    success: function(data) {
        alert(data);
    }
});

But the data is always an empty string, no matter what url I go to...  Why is that?  I am running this locally at http://localhost:3000, and am using JQuery 1.4.2.
If I make a local response, however, like this:
$.ajax({
    url: "http://localhost:3000/test",
    dataType: "html",
    success: function(data) {
        alert(data);
    }
});

...it returns the html page at that address.  What am I missing here?
Comment: @aviraldg How would he be able to post this question?
Comment: @Jacob by developing on another (offline) computer (as I do)
Comment: Are you connected to the internet? (Silly, I know...)
Comment: I don't think you can do that...
Answer: You're running into the same-origin policy, preventing you from making an ajax request to another domain, for security reasons.
You can't make a request to:

Another domain
Another port, even on the same domain
A sibling domain

You can make a request to:

The same domain
A subdomain of the current domain

You can read more about it here
Comment: thanks! how then are these people making/using [JQuery RSS readers like this one](http://www.hovinne.com/blog/index.php/2007/07/15/132-jfeed-jquery-rss-atom-feed-parser-plugin)?
Comment: [got it](http://jquery-howto.blogspot.com/2009/11/cross-domain-rss-to-json-converter.html)
Comment: Something is not logical: why in that case is not an error, but a success with an empty answer?
Answer: You can't load data from other domains. It's a security feature.
Here's a link that talks about how to create a proxy from your web server to get around his limitation.
http://jquery-howto.blogspot.com/2009/04/cross-domain-ajax-querying-with-jquery.html


How to use Wayland in Gnome Flashback

Question: I would like to use Wayland in Gnome Flashback. My operating system is Ubuntu 18.04.

It's possible to configure Metacity to use Wayland?
If not, it's possible to configure Gnome Flashback to use Mutter window manager which supports Wayland?

EDIT: Is there any other window manager that supports Wayland and can be used with Gnome Flashback?
Answer: Metacity is x11 window manager and that is not going to change. No, Metacity will not use Wayland.
It might be possible to use Mutter, but it is not supported. You would have to disable many things in gnome-flashback, otherwise there will be conflicts between gnome-flashback and mutter, because both will try to do same things, for example, manage monitors.
Comment: To avoid video tearing in my nvidia graphics card
Comment: @Tux, no! If you want to use GNOME Flashback then forget about Wayland. Why you so much want Wayland?
Comment: Is there some guide to use Mutter, or any other window manager that supports Wayland in Gnome Flashback?

How to use Wayland in Gnome Flashback


Compiz changes my window's theme

Question: I have Gnome Shell, Unity and Xubuntu on my computer and I would like to use compiz in Xubuntu. Whenever I put in "compiz --replace" it changes my window's theme from Greybird to Gnome's Ambiance. It doesn't seem like I can change it back in Xubuntu's settings menu, when I click on Window Manager, everything is blank. Any suggestions?
Answer: When you use "compiz --replace", you are replacing xfwm4 with compiz. That means the xfwm4 window manager is no longer running. Since greybird is part of xfwm4, it won't run either.
Answer: You can try just logging out and back in as another shell (Click the gear) to get back into the settings. As well I got the Compwiz manager when I was messing around with it.
sudo apt-get install compizconfig-settings-manager
Comment: If this doesn't work you may have to edot the ~/.config/xbuntu-session file to include the compiz profile

Compiz changes my window's theme


Ubuntu 22.04 on Dell XPS 17 Hangs on Shutdown

Question: When I try to shut down my computer, it hangs on the Ubuntu/Dell splash page. I've used F1 to view the logs, and the last lines are usually the following:
systemd-shutdown[1]: Syncing filesystems and block devices.
systemd-shutdown[1]: Powering off.
kvm: exiting hardware virtualization

and then every few seconds I get a new UFW BLOCK log, like the following:
[UFW BLOCK] IN=enxc025a57a0fd0 OUT= MAC=(some address) SRC=192.168.1.1 DST=22.214.171.124 LEN=36 TOS=0x00 PREC=0x00 TTL=1 ID=18930 DF PROTO=2

I haven't been able to find any documentation about how to read these logs though, so I have no idea how to track down that string in the IN field.
Once every 10 - 15 shutdowns, though, it won't hang on the kvm log, and go further. I was able to catch that once, and the final lines it caught on there were:
thunderbolt 1-1: new device found, vendor=0xd4 device=0xb70
thunderbolt 1-1: Dell WD19TB Thunderbolt Dock
usb usb2-port3: attempt power cycle
usb usb2-port3: unable to enumerate USB device

And while it hung on that line, it didn't produce UFW Block logs.
I have about 10 more lines for each log, but since I've had to transcribe the logs manually from a photo I took with my phone, I didn't want to flood the post unless they were necessary.
Has anyone seen something like this? I can't find much. I tried blacklisting the kvm scripts, but that didn't get rid of the kvm line.
Answer: After running this command the problem was resolved:
shutdown -H -P +0

Previously, I had installed the NVIDIA driver using this tutorial: https://www.cyberciti.biz/faq/ubuntu-linux-install-nvidia-driver-latest-proprietary-driver.
One of the two solved the problem.
Comment: I only installed the NVIDIA driver and was able to shutdown normally. Thank you very much!


How to fix X Error: BadAccess, BadDrawable, BadShmSeg while running graphical application using Docker?

Question: I am running Ubuntu MATE 20.04 LTS. I have installed Docker to this system.
I need to run FreeMat 4.2 which is not available for Ubuntu 20.04 LTS anymore because of Qt4 deprecation.
I did the following:
sudo apt-get install docker.io
sudo usermod -a -G docker $USER
# reboot

mkdir ~/docker-freemat
cat > ~/docker-freemat/Dockerfile << EOF
FROM ubuntu:18.04
RUN apt-get update
RUN apt-get install -y freemat
CMD freemat
EOF

docker build -t ubuntu:freemat ~/docker-freemat

To run FreeMat from container I'm using the following command:
docker run -e DISPLAY -v /tmp/.X11-unix:/tmp/.X11-unix --user="$(id --user):$(id --group)" ubuntu:freemat

But the FreeMat window is non-functional, instead it looks like:

and terminal output is the following
X Error: BadAccess (attempt to access private resource denied) 10
  Extension:    130 (MIT-SHM)
  Minor opcode: 1 (X_ShmAttach)
  Resource id:  0x14e
X Error: BadShmSeg (invalid shared segment parameter) 128
  Extension:    130 (MIT-SHM)
  Minor opcode: 5 (X_ShmCreatePixmap)
  Resource id:  0x3200014
X Error: BadDrawable (invalid Pixmap or Window parameter) 9
  Major opcode: 62 (X_CopyArea)
  Resource id:  0x3200015
...

How to get rid of this error and get application window shown normally and fully-functional?

Some notes:

Changing 18.04 to 16.04 or even 14.04 in Dockerfile does not change anything
Installing Docker from docker.com does not change anything
Comment: I think passing just the X11 socket to the docker container isn't enough. Errors indicate that the container cannot access shared memory which is resident in the host OS. If you want to run the aforementioned program in docker just because the unavailability of Qt4 , you can download and compile the [Qt4 source code](https://download.qt.io/archive/qt/4.8/4.8.5/). Here is the [instructions](https://doc.qt.io/archives/qt-4.8/installation.html)
Comment: Also you have another choice. --ipc option for docker might help you to enable the container to communicate with the host processes ( e.g X-server ).But there are also security considerations . See [here](https://stackoverflow.com/questions/38907708/docker-ipc-host-and-security)
Comment: Also as stated [here](https://www.x.org/releases/X11R7.7/doc/xextproto/shm.html) the MIT-SHM is actually an extension for passing the XImages and some Pixmaps via shared memory. So if the container cannot access that , you cannot open any graphical application.
Comment: Great. @ParsaMousavi please transform your comments to the answer. Setting [`--ipc="host"`](https://docs.docker.com/engine/reference/run/#ipc-settings---ipc) make it work!!!
Answer: You can set the option --ipc=host to enable the docker container to communicate with host processes and also accessing the shared memories .
The command to launch graphical application will look as follows:
docker run --ipc=host -e DISPLAY -v /tmp/.X11-unix:/tmp/.X11-unix --user="$(id --user):$(id --group)" ubuntu:freemat
and will show the application window:

MIT_SHM is actually an extension for passing the XImages and some Pixmaps via shared memory. So if the container cannot access that , you cannot open almost any graphical application.
And if you're concerned with the security , you can use --cap-drop to drop some capabilities as stated here.


How much of a cylinder can you see from a single point of view?

Question: I'm creating wraps for trash cans and recycling bins to label them appropriately. They'll wrap 360 degrees around the bins. I want the text on the bins to be readable from a single point-of-view (so someone doesn't need to walk around the bin to read the whole thing). Assuming the bins are cylinders, is there a way to represent what percentage of the cylinder would be viewable from a given point of view?
Comment: It depends how close to the bin you are. I think a more significant question is how distorted the text will be, which probably comes down to a matter of taste.
Comment: Assuming top and bottom don't matter, if a cylinder is bisected by a plane, an ellipse is obtained. What fraction of an ellipse is visible from a single point-of-view in that plane?
Answer: When you stand $N$ radiuses away from the surface of the cylinder, you can see this fraction of its surface:
$$ \frac{1}{\pi}\cos^{-1}\left(\frac{1}{N+1}\right) $$
-- or $\arccos(1/(N+a))/180^\circ$ if your arccosine function produces answers in degrees rather than radians.
Practically: When you stand outside the cylinder, you can see a fraction of its circumference that depends on how far from it you are. The fraction is always less than 180°, but approaches it closely as your viewpoint moves farther away from the cylinder.
On the other hand, you need to get your head fairly close to the trash can (closer than one radius to the surface) in order to see less than a third of the circumference.
So if your goal is just that an observer at a reasonable distance can see at least one copy of every letter of the text you write, writing it three times will be sufficient. But then you risk that the viewer will have to piece the text together from to halves as in:
<code>    |                                                                |
    |TED THREE TIMES AROUND THE CAN.        THIS TEXT IS REPEATED THR|
    |                                                                |
</code>
If you want at least one full copy of the entire notice to be visible from anywhere, four or five repetitions would be advisable.
Comment: A very practical answer.
Comment: Henning, this is an awesome answer. Thanks so much for your practical advice.
Comment: +1 for the great answer but I believe the correct plural form of "radius" is "radii", not "radiuses".


Hibernate's sessionFactory overwrites initialState entity after merge

Question: I'm using Springboot and Hibernate in a project and I'm doing a PATCH request.
Long story short, I invoke an update with:
hibernateEntityAccess.update(original, patchedData, OperationTarget.ENTITY);

This is the update invoked:
    @SyncChs
    @Transactional(rollbackFor = Exception.class)
    public void update(final Auditable<?> initialState, final Auditable<?> finalState, final OperationTarget target, final boolean isInternalOperation) throws IOException {
        int key = operation.getCurrentSession().setInitial(initialState, (AuditableEntity) initialState, target, isInternalOperation);
        Auditable<?> merged = (Auditable<?>) sessionFactory.getCurrentSession().merge(finalState);
        operation.getCurrentSession().setFinal(key, merged, (AuditableEntity) finalState, isInternalOperation);
    }

After .merge(finalState), the data in original is overwritten with the data that was in patchedData.
I've made my entities clonable and tried this
hibernateEntityAccess.update(original.clone(), patchedData.clone(), OperationTarget.ENTITY);

to see if original variable would not be overwritten by merge but the same behavior occurred.
Does anyone have an idea of why this happens?
Comment: that is expected: I believe you have retrieved `initialState` via `em.find` or something similar, so actual state get stored in persistent context and HBN modifies that state when performing `merge`. Call `em.detach(initialState)` before calling `update`
Answer: I've solved it by using .toBuilder().build():
hibernateEntityAccess.update(original.toBuilder().build(), patchedData.toBuilder().build(), OperationTarget.ENTITY);

This way my original variables didn't change.


ORA-01847 Error to get a date

Question: I'm having a problem with this query:
select to_char(ADD_MONTHS((LAST_DAY(to_date(DATEVAR, 'yyyymmdd'))+1),-1),'yyyymmdd') from mytable
where ROWNUM=1
and var = to_char(last_day(to_date(DATEVAR, 'yyyyMMdd')), 'WW')-1;

I want it to return when the var is the last week number of the month and return null when it isn't if my var is '29' (weekNumber) i get:

ORA-01847: "day of month must be between 1 and last day of month"

But if i change the week number to '30'(last week number of the month) i get the correct result:
'20160701'

Please help thank you.
Comment: ***Never***, *ever* call `to_date()` on `date` value.
Comment: Last week number? last week number of the month is 30? How do you expect to write correct code, when your mind is confused between "week" and "day"? There is no way to write correct code from confused thinking. Regardless of anything else, your very last line will fail: you compute a `to_char()` of something (doesn't matter what) and then you subtract 1 from the resulting character string. You need a different approach to asking your question: State what you are trying to do, what your data looks like and what output you want - don't just show your code (which doesn't work correctly anyway).
Comment: @mathguy but there are over 30 weeks in the year, so why would you assume that the OP is getting confused between days and week numbers?
Comment: @Boneist - or perhaps I am getting confused? What is the last week number of the month - weeks are numbered for the year, and we are looking at the highest week number for a week that overlaps with a given month? And we are supposed to be able to guess that, not from an explanation of the problem, but from reading someone's code for it?
Comment: @mathguy that's the meaning I understood from the OP's post - mainly from their description of their problem, not their code.
Comment: @Boneist - Ok, then I am the one who was confused. It has happened before.
Comment: @mathguy, eh, it's Friday! Also, I may have been known to get confused myself, on the odd occasion or two..... or lots! *{;-)
Answer: I don't see an issue with your code? With var set to 30:
WITH mytable AS (SELECT trunc(SYSDATE, 'yyyy') - 1 + LEVEL datevar
                 FROM   dual
                 CONNECT BY LEVEL <= 366)
SELECT to_char(add_months((last_day(datevar) + 1), -1), 'yyyymmdd') ret_col
FROM   mytable
WHERE  rownum = 1
AND    30 = to_number(to_char(last_day(datevar), 'WW'))- 1;

RET_COL
--------
20160701

Change the 30 to a 29 in the above query, and I get no rows returned.
The only thing that I can think is that your datevar column has a datatype of VARCHAR2 instead of DATE and that you're experiencing some implicit date conversion issues due to your NLS_DATE_FORMAT setting.
N.B. edited my query to remove the to_date()'s that were there on the datevar (which, as I'd defined the datevars as DATEs, was a very silly thing to do! Thanks @mathguy.) Also, added in an explicit to_number() in the where clause.
Comment: You are still relying on the same implicit conversion I pointed out in my comment to the OP - in the last row you are subtracting 1 from a string. This may be one of those cases when Oracle guesses correctly, but subtracting 1 from a string is generally not a good practice.
Comment: @mathguy in this instance, the implicit conversion of the string to a number is fairly safe. But I take your point and have added an explicit to_number()

ORA-01847 Error to get a date


What is a magic with 5 lines of code in htaccess?

Question: I want to know, with this code in .htaccess
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]

Can do many things on query strings from URLs like Wordpres have done by example. It's depend on our coding or.. ? What is the secret ingredients to make like that?
Let me know if you have a good source to share with me. All in one.
Answer: This would make some kind of catch all page.
Let's explain it line by line
RewriteEngine On

enable mod rewrite
RewriteBase /

Set the base url of the rules to '/'
RewriteCond %{REQUEST_FILENAME} !-f

if the requested file doesn't exist (i.e not a jpg)
RewriteCond %{REQUEST_FILENAME} !-d

if the requested directory doesn't exist
RewriteRule . /index.php [L]

Redirect everything to index.php
So to summarize it will redirect any URL to index.php if the filename or directory requested doesn't exist.
and the documentation if you want to do some more reading.
Answer: The rewrite engine makes it possible to match paths and do manipulations, redirects etc. based on advanced rules.
Your specific example sets up two conditions (path must not represent an existing regular file nor directory) and then redirects anything else to index.php. You can then implement whatever you wish in index.php in order to match and/or parse the original request (e.g., /news/some-title could be forwarded to the news module where the news item can be fetched via the slug).
Sometimes you will see the initial redirect rewrite(s) done directly in .htaccess. The above could look like:
RewriteRule ^news/(.+)$ newsview.php?title=$1 [QSA,L]


query to call stored procedure from data service created using wso2 application server

Question: How to write a query to call a stored procedure having both an in and an out parameter using the data service which is created in the wso2 application.
I am using this query: call wso2proc(:e_id,:e_name,?)
and stored procedure is as below..
create or replace PROCEDURE WSO2PROC ( e_id IN emp20.id% TYPE , e_name IN emp20.name% TYPE , e_address OUT emp20.address% TYPE ) IS
    BEGIN
        select address INTO e_address from emp20 e where e.id=e_id and e.name=e_name;
    END WSO2PROC;

Please suggest how to write the query while creating a data service in wso2 application server so that out parameter is returned.
Comment: To clarify- is there is one DSS server and one AS where has a service. And you want to get some data using DSS depending on some input provided my AS service. Am i correct in your scenario here.
Comment: I am using wso2 sb 4.0.6 now and created data service in browser which should get data from oracle data base using stored procedure
Answer: Thanks, Shelan.
Got the answer.
Now I used this query .....> call wso2proc(?,?,?)
And given input mapping for all the in and out parameter name present in stored procedure's parameter with same name.
AS for example :
create or replace procedure wso2prc(name in varchar,address out varchar)
So given name as in and address as out in input-mapping with same name as present in above proc.
Apart of this I did out-mapping for address, which will come as a result from procedure.
And Its working.


VBA - Word change the concept of word(a.b is one word or two)

Question: I have a question: i want to have an array of words of a WORD document, which are larger than 29 and Shorter than 40 characters. I implemented it in VBA this way:
Sub function()

    Dim arr(1000) As String
    counter = 0

    For Each sentence In ActiveDocument.StoryRanges
        For Each w In sentence.Words
            If Len(w) > 28 And Len(w) < 40 Then
                arr(counter) = w
                counter = counter + 1
            End If
        Next
    Next

End Sub

The Problem is that I want all words with char '_' cosidered as one word; for example: 'Adrian_link_mart' is one word and not 3: 'Adrian' and 'link' and 'mart' like it will be considered
thanks for your help, adrian
Comment: What's your actual question? How is the code you have not working, exactly? I think those who've responded in comments are interpreting incorrectly... FWIW you can't change how Word recognizes what a "word" is. You need to explain the logic required for your requirement. For example, is every occurrence of a `_` to be appended to the "word" before and after it? If not, when not?
Comment: One more nested loop like `For Each w2 In Split(w, "_")` will do the job. `Split()` will return an array formed by the string `w` split by the delimiter `_`. In there you can just do your `if` and `arr(Counter)=` business on `w2`.
Comment: Yeah, now that I'm playing around with it @CindyMeister I see that I had the problem backwards. Perhaps the solution is just to join values ending in `_` with the following value?
Comment: @Marcucciboy2 Probably, but let's wait until the OP provides more precise information...
Answer: This may help.  There is a bit of a wrinkle as you will see below.
Option explicit

Sub test()

' Use a collection rather than an array as we don't need
' to know the size in advance
Dim word_array              As Collection
' Word doesn't actually have a  'word' object. Probably because
' that clashes with Word the application.  So instead of Word.Word
' we are using word.range which gives us all the utility we will
' need
Dim my_word_range           As Word.Range
Dim my_range                As Word.Range

    For Each my_range In ActiveDocument.StoryRanges
        For Each my_word_range In my_range.Words
            With my_word_range
                Do While .Next(unit:=wdCharacter) = "_"
                    ' '_' is considered to be a word  by Word so we need to
                    ' count two Word words to get to the end of the next
                    ' text word IYSWIM
                    .MoveEnd unit:=wdWord, Count:=2

                Loop

                If .Characters.Count > 28 And .Characters.Count < 40 Then
                    word_array.Add Item:=.Text

                End If

            End With

        Next

    Next

End Sub

If you are new to VBA then

Include Option explicit at the top of every module
In the VBA IDE go Tools.Option.Editor.Code Settings and make sure every box is ticked.
Learn how to use F1.  In the VBA IDE, putting the cursor on a keyword and pressing F1 will bring up the MS help page for that keyword


Gameboy Visual Advance Pokemon file saved as sg1 file

Question: I am really struggling to load my saved game (that I put hours into) on my VisualBoy Advance. I keep getting an error message when I try and open it, and if I go into VBA and Ctrl + O then the saved file does not show up in its folder. It looks like it is saved as an .sg1 file - does this make a difference? Is there a way I can change this to a compatible file?
Please tell me you have good news...
Answer: I don't understand why you're doing Ctrl + O to load the savefile, that option is used to open the game itself (which is usually a .gba file).
VBA's save files should already be in .sav format, unless you are using save state which is a different story.
That .sg1 file should be VBA savestate file, so you can't properly load the game from that. The only way to load that file is starting the game, then load savestate (which is done by pressing F1)
Here's a video tutorial for reference.
Note:
When using VBA it's not only recommended to save the state, it's better to export battery file, too:

File -> Export -> Battery file

This is a really important step that you need to take.


Is there a lighting code restricting where lights can be placed?

Question: I am having a new home built in New Brighton, MN, USA. We went over the plans on where we would like our lights, outlets, switches to be placed throughout the home. I asked them to place a light in a different position in the storage area of the garage.
See the image below. The red X's indicate where the lights are currently placed. A few months ago I asked them to move the red X in the storage area closer to the main part of the garage (where the blue X is located). At first, no one objected to this plan. However, we just did a walk through of the home before they install the drywall. I was told that they cannot move the light because of "code".
I've tried searching but cannot find any code restricting where lights can be placed. Does anyone know of such code for my area or in general?
Comment: See if they will rough in another box where you want it. While you are in your golfing phase you could cap the wires and put a blank cover plate on it. When you are finished golfing or when you sell this house someone can put a fixture where it should be.
Comment: It looks to me like the current position is closer to the middle of the storage area than the position you want to change it to. Could that be a basis for a code requirement?  Maybe you could get them to add a box at the new position and have that in addition to the current one. If not, unless this is a low ceiling, it would be easy to add a box there later which would be on the same switch as the current  location.
Comment: Yeah that's a huge area (23' long) for a single light. I'd at least leave that one where it is and install another light where you indicated (which, btw, should be less work than actually removing the old one). I recently insulated and drywalled my 19x21' garage, and have 2x 100W LED bulbs in the middle (about where yours are), 2x 3' flourescent fixtures at the back and put nothing in the front above where the door opens, but in retrospect I wish I had put two more there (6 lights total) and just used the 100W LED bulbs everywhere. You have twice the space with half the fixtures ;)
Comment: I accidentally posted this question as a guest. But, I actually don't want the light there because I plan on having a golf hitting net in that area. I will be standing directly underneath where the light is currently. I am concerned about height clearance when I swing a golf club. I plan on putting a lamp or some other light in the storage area.
Answer: I don't know of any restrictions off the top of my head other than in closets and bathrooms. I would make them show you the code reference sounds like someone missed the change and is two lazy to do it they way you wanted it.
Answer: As of NEC 2005 (NEC is updated every 3 yrs.), (210.70A2b) requires a "switched light in the garage, hall & stairs"; as well as, "a switched lighting outlet on exterior side of all grade level doors except garage vehicle door."  There is no mention of spacing, specific location, minimum lumens, or etc.


android threading and handler - Changing UI objects from a background thread

Question: I've recently written a small android application to send and receive UDP messages over a local network.I have a UDP receiver thread that runs to listen for UDP packets, what I want to happen is a button to become enabled on the UI when a packet is received that contains a certain string of data. I know that this has to be done with a handler, the problem being that I have a small amount of knowledge about threads and very little knowledge about handlers.  would someone be able to shed some light on how a handler could be put into my code? thanks
code:
public void startUDPlistener() {

    // Creates the listener thread
    LISTEN = true;
    Thread listenThread = new Thread(new Runnable() {

        @Override
        public void run() {

            try {

                Log.i(LOG, "Listener started!");
                DatagramSocket socket = new DatagramSocket(BROADCASTPORT);
                socket.setSoTimeout(1500);
                byte[] buffer = new byte[BUFFERSIZE];
                DatagramPacket packet = new DatagramPacket(buffer, BUFFERSIZE);

                while(LISTEN) {

                    try {

                        Log.i(LOG, "Listening for packets");
                        socket.receive(packet);
                        String data = new String(buffer, 0, packet.getLength());
                        Log.i(LOG, "UDP packet received from "+ packet.getAddress() +" packet contents: " + data);

                    }
                    catch(IOException e) {

                        Log.e(LOG, "IOException in Listener " + e);
                    }
                }

                Log.i(LOG, "Listener ending");
                socket.disconnect();
                socket.close();
                return;
            }

            catch(SocketException e) {

                Log.e(LOG, "SocketException in Listener " + e);

            }
        }
    });

    listenThread.start();

}

Comment: A simple alternative to using a Handler would be to use the `runOnUiThread(...)` method: http://stackoverflow.com/questions/11140285/how-to-use-runonuithread
Answer: You basically just add one and send either a Message or a Runnable.
private final Handler mUiThreadHandler = new Handler(Looper.getMainLooper());

void fromAnyThread() {
    final String importantDataFromBackGroundThread = "!!!";
    mUiThreadHandler.post(new Runnable() {
        @Override
        public void run() {
            System.out.println("Hi from Ui Thread:" + importantDataFromBackGroundThread);
        }
    });
}

The Handler handles all messages / runnables within the Thread it runs in. If you specify Looper.getMainLooper() you are guaranteed that this is the main thread.


PHP - Custom QRCodes?

Question: I saw some online qr code generators such as https://dashboard.unitag.io/ and I was wondering how they do it.
Is it possible to do that in PHP? If so, how would I manage to do that? (I know there are some APIs to create colored QR codes and insert images into it, but I never found any that could change the 'shape' of the QR code...)
Comment: Possible duplicate of [Dynamically generating a QR code with PHP](http://stackoverflow.com/questions/5943368/dynamically-generating-a-qr-code-with-php)
Comment: Possible Duplicate Of - http://stackoverflow.com/questions/5943368/dynamically-generating-a-qr-code-with-php
Comment: This question possibly belongs on [Software Recommendations](http://softwarerecs.stackexchange.com)
Answer: I would look into a library called PHP QR Code. It's open source and is pretty simple to use,
<code>QRcode::png('code data text', 'filename.png'); // creates file
QRcode::png('some othertext 1234'); // creates code image and outputs it directly into browser
</code>
If you're looking for a library with a little more functionality, check out Advanced Custom QR Code Generator. It costs $35 but gives you the ability to work with shapes, colors, and even embed logos.
Comment: the library mentioned is no longer available for sale, but it is on github - https://github.com/mahadazad/qrcode
Comment: Thanks! That's exactly what I was looking for!
Comment: Thanks for the reply. As I mentioned, I already know about some APIs that create QR codes, but none of them can change the shape of the QR code like unitag does.
Comment: @LCastr0 I've updated my answer including another library you may want to checkout
Comment: @CFPSupport But that is a Python. Any idea of php ?

PHP - Custom QRCodes?


For a template: error C4430: missing type specifier - int assumed. Note: C++ does not support default-int

Question: #include <list>

template < class TYPE >
class CIndex : protected std::list < TYPE >
{
public:
    typedef std::list < TYPE >::iterator  CIndexIt;
    typedef std::list < TYPE >::difference_type  CIndexDiff;

The error happens in the last line of the above code.
I've seen this and the msdn page but both don't solve my error.
Anyone knows what could be causing the problem?
EDIT:
The reason the first link's solution didn't work was because although adding typename worked for the above code, it didn't work for the below code:
#include<hash_map>
class CWItems
{
typedef stdext::hash_map < unsigned long, CWksItem* >   CItem;
CItem mItems;

So I thought I was doing the wrong thing by adding typename everywhere. Using typename after the typedef in this code caused this error:
error C2899: typename cannot be used outside a template declaration

Without typename, the error shown is error C4430: missing type specifier - int assumed. Note: C++ does not support default-int, at the CItem mItems; line.
Comment: possible duplicate of [Using types defined in template arguments](http://stackoverflow.com/questions/741597/using-types-defined-in-template-arguments)
Comment: Useful to have the link you posted. My problem still isn't solved though. Have edited my question to add more info. Help?
Comment: `CWItems` is not a class template so you can't have any dependent names. Where is `CWksItem` declared?
Comment: CWksItem is mentioned as `class CWksItem;` (forward declaration). But the error persists even if CWksItem is substituted with `int`.
Comment: I think the problem is something else. I wrote some standalone code for the hash_map and it worked. Thank you.
Answer: You need to add the typename keyword because std::list<TYPE>::iterator and std::list<TYPE>::difference_type are dependent names:
typedef typename std::list < TYPE >::iterator  CIndexIt;
typedef typename std::list < TYPE >::difference_type  CIndexDiff;

See http://pages.cs.wisc.edu/~driscoll/typename.html for more information.
Comment: The problem showed up in another part of the code, and this time `typename` didn't solve it. I've mentioned more in the edited section of my question. Help?
Answer: You are missing the typename keyword exactly as in the question that you linked to:
typedef typename std::list < TYPE >::iterator  CIndexIt;
typedef typename std::list < TYPE >::difference_type  CIndexDiff;


Adding a property to a silverlight 4 control to add functionality

Question: I am curious how I can add a property to add functionality to a control. Currently I am just extending controls, but I was curious if it is possible to add a property to add functionality to a control. Like for example the ToolTipService. You can add that to controls. Would it be possible for me to add a property to add a contextmenu without having to extend a textbox lets say? I know about behaviors, but is it possible to do that as a property? Let's say I add a property IsContextMenuBehaviorAdded="True" and that will just attach a behavior, or just add functionality. Any help would be greatly appreciated. Thanks in advance.
Answer: If you are looking to add a context menu to a control then you can do that with the Silverlight Toolkit which contains a ContextMenuService.
Comment: I have an extended contextmenu control. is it possible to use that with the contextmenuservice?
Comment: @pqsk:  I your controls extends the the Toolkit `ContextMenu` then yes.
Comment: Awesome. Just one more question. Say on my view I have a few textboxes that I want this contextmenu to be in. I see that the ContextMenuService has some properties. Is it possible to make that a usercontrol resource so I wouldn't have to write all the properties for each textbox?


Using exception handling

Question: I am trying to create an exception block that reads an error message and shuts down the program gracefully if my user inputs anything other than a number. How can I achieve this?
x=int(input("Choose a number:"))

try:
    x==int()

except:
    print("Invalid input.")

    sys.exit()

y=int(input("Choose a number:"))

try:
    y>=0 or y<=0

except:
    print("Invalid input. Please try again.")

    sys.exit()

Answer: In python the try block lets you test a block of code for errors.
The except block lets you handle the error.
In except block you can use ValueError as you are trying to convert the input to an integer, so if the input value is an integer, the code in the try block will be executed. otherwise the code in the excpet block will be executed.
You can use the while loop to exit the program only when you want by changing the value of the start variable to False.
start = True

while start:
    try:
        x=int(input("Choose a number for x :"))
        y=int(input("Choose a number for y :"))

        # if x > y:
        #     print("x is greater than y")
        # elif x == y:
        #     print("x equal to y")
        # else:
        #     print("x is less than y")

    except ValueError:
        print("Invalid input. Please enter a number")
        start =  False

Learn more about exceptions:

https://www.w3schools.com/python/python_try_except.asp
https://docs.python.org/3/tutorial/errors.html#handling-exceptions

Learn more about while loop:

https://www.w3schools.com/python/python_while_loops.asp

Using exception handling


Toolbar in a new line inside a ToolBarTray

Question: I have two ToolBars in ToolBarTray. Although they can fit in one line, I want to put each ToolBar in new line.
How Can I do that ?
<ToolBarTray VerticalAlignment="Top" Margin="0,20,70,0" Height="65">
    <ToolBar Height="30" VerticalAlignment="Top" Background="LightGray" >
        Name :
        <TextBox Width="120"></TextBox>
        <ComboBox Width="120" Margin="5,0,0,0">
            <ComboBoxItem>Item 1</ComboBoxItem>
            <ComboBoxItem>Item 2</ComboBoxItem>
            <ComboBoxItem>Item 3</ComboBoxItem>
        </ComboBox>
        <Button Height="25" Width="80" Background="White" Margin="5,0,0,0">Search</Button>
        This is a first ToolBar
        <Button Height="25" Width="80" Background="White" Margin="5,0,0,0" ToolBar.OverflowMode="Always">Look for ..</Button>
    </ToolBar>

        <ToolBar Height="30" VerticalAlignment="Top" Background="LightGray">
            Name :
            <TextBox Width="120"></TextBox>
            <ComboBox Width="120" Margin="5,0,0,0">
                <ComboBoxItem>Item 1</ComboBoxItem>
                <ComboBoxItem>Item 2</ComboBoxItem>
                <ComboBoxItem>Item 3</ComboBoxItem>
            </ComboBox>
        </ToolBar>
    </ToolBarTray>

Answer: From MSDN: ToolBar.BandIndex Property:

The position of the ToolBar in a ToolBarTray depends on the values of
  the ToolBarTray.Orientation, Band, and BandIndex properties. When
  Orientation is set to Horizontal, a band represents a row in the
  ToolBarTray. When Orientation is Vertical, a band represents a column
  of the ToolBarTray.

In this case, you'll need to set the ToolBarTray.Orientation Property to Vertical:
<ToolBarTray Orientation="Vertical"
             VerticalAlignment="Top" Margin="0,20,70,0" Height="65">
  <etc />
</ToolBarTray>

And, don't forget about ToolBar.Band and ToolBar.BandIndex Properties:

If you do not explicitly set this property, its value is determined by
  the order in which the ToolBar is set in the ToolBarTray. For example,
  if you put two toolbars in a ToolBarTray without setting the Band and
  BandIndex properties, the value of Band will be 0 for both toolbars.
  The value of BandIndex will be 0 for the first toolbar and 1 for the
  second toolbar.


When do I put - inside an  element?

Question: When do I put  headings inside a header element? I can't understand it, sometimes it seems to me that each heading has to be between header tags.
Let's take this sidebar as example :

How to code it?

How to format

or

How to format

Answer: See the specification of the header element:

A header element is intended to usually contain the section's heading
  (an h1–h6 element), but this is not required. The header element can
  also be used to wrap a section's table of contents, a search form, or
  any relevant logos.

So you can have many header elements in a page (it's not limited to the top of the page), and you can use it around headings, but it's optional. This means both of your examples are correct.
Comment: Both code examples (assuming that there is other content in the `aside` element, as in the image) are formally correct, but using `h1` relying on the outline algorithm is "[dangerous fiction](http://www.paciellogroup.com/blog/2013/10/html5-document-outline/)". Using the `header` element hardly has any benefit here, as a wrapper for a single element.
Answer: The header tag is for what displays at the top of the page of the page-what is sometimes called the banner. So put your h1-h6 tags in it when they are in the banner of your page.
Tags like header and footer are basically just div's renamed for organizational sanity. In the future search engines and browsers may look for header and footer tags to help them process and display information better. For now, it lets you avoid staring at a bunch of div tags.

     Web page Banner

Content

    Web page bottom

Instead of this...

 Web page Banner

Content

Web page bottom

Answer:  give us some great added semantic value in order to describe the head of a section.
You can use multiple headers in a web page, each of which will then become the  for that section of the document. So, using a  depends on the complexity of the section. The more complex it is, the more necessary the header element becomes.
a  typically contains at least (but not restricted to) one heading tag (
 –
).
hope it helps
Comment: So this means that i can have an  element without  -  inside?
I Read in HTML5 doctor few years ago that if you have  you need to have a  -  inside.

When do I put - inside an  element?


How to remove old HPLIP in Ubuntu-Mate 18.04

Question: I need to get working HP15w laserjet printer with Ubuntu-Mate 18.04 LTS (HPLIP ver. 3.17.10 included).
According to HP site, HP15w is supported starting from hplip 3.18+ release.
I found this guide, but surprisingly it turned out that hplip package has dependencies with whole desktop:
sudo apt purge hplip
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following packages will be REMOVED:
  hplip* printer-driver-postscript-hp* ubuntu-mate-core* ubuntu-mate-desktop*
0 upgraded, 0 newly installed, 4 to remove and 0 not upgraded.
After this operation, 2,847 kB disk space will be freed.

I'm just interpreting something wrong? Or installer is going to remove all GUI from that computer?
We bought that printer a month ago and really need to get it working.
Answer: Really the sudo apt purge hplip command will not end with GUI removal.
The command will remove MATE meta-packages but the MATE desktop itself will remain installed.
I have double tested this on fresh Ubuntu MATE 18.04 LTS.


C# GODOT | ERROR: call_build: An EditorPlugin build callback failed

Question: <code>    Mono: Logfile is: C:\Users\Yunus Aka\AppData\Roaming/Godot/mono/mono_logs/2020_08_12 04.29.52 (13092).txt
Unicode error: invalid skip
ERROR: call_build: An EditorPlugin build callback failed.
   At: editor/editor_node.cpp:5273
</code>
Hi, i've been start godot and iam taking this error.
I  am using mono godot 64 bit and i already download ".NET framework 4.7.1", ".NET framework 4.7" but it doesn't work. Give me same error again.
Please help meee
Answer: I solved it for an error at editor/editor_node.cpp:5273 when I looked at the error and the pressed the "view log" there. It said that I was missing .NET developer pack 4.7.
I tried 4.8 first which didn't work. It had to be 4.7.


Question restructuring

Question: Question
Influence:

http://www.ted.com/conversations/18501/are_people_really_more_narciss.html
http://www.theguardian.com/technology/2012/mar/17/facebook-dark-side-study-aggressive-narcissism
http://www.huffingtonpost.com/2013/05/01/teenagers-values-materialistic-work_n_3193782.html
http://blogs.berkeley.edu/2014/06/26/are-we-more-self-absorbed-than-previous-generations-or-more-self-aware/
https://www.linkedin.com/pulse/20140911175326-66132034-social-media-and-narcissism-rise-of-a-self-obsessed-society
http://www.psychalive.org/obsession-with-selfies/
http://www.telegraph.co.uk/women/womens-life/11265022/Selfie-obsession-are-we-the-most-narcissistic-generation-ever.html

What can I do to restructure my question so that it wouldn't, elicit (fully) opinion based answers?
@Josh    /  @JoshGitlin
Answer: You should add some of the references you include here to your original question. That way if somebody doesn't believe you opinion-based claim that "people are becoming more egotistical", you will have left them some evidence. You will have motivated your question.
However, please be respectful to the people that read and answer your questions. Don't just drop a bunch of links on us, as you did here. Nobody has the time or interest to click through your links and see what they say, especially without context and when they are mostly linking to not-the-best-of sources for scientific discussion (although of course, we should evaluate that on a link by link basis; but we aren't going to do that with 7 context-less links that a stranger posted on the internet). Put your evidence in context, explain what it is that people are saying and who is saying it, with the links providing corroboration and citation. Do this concisely.
Show us that you did some initial research and reflection. For more information, see: How do I ask a good question?
Comment: I'm trying to reach out to the mods on chat. I've posted some stuff there I would like to discuss. I can't ping you though. Could you come over to the axon terminal? It's rather urgent (new pro-tem mod stuff). Thanks.

Question restructuring


Deduction in polynomial calculus.

Question: Polynomial calculus is a proof system with two derivation rules:
$${p ~~~~ q\over \alpha p + \beta q} ~~~~~~ {p \over x_i \cdot p}~~~~~~ {\over x_i^2 - x_i}$$
where $p,q \in \mathbb{F}[x_1, \ldots, x_n]$, $\alpha, \beta \in \mathbb{F}$, $\mathbb{F} $ is a field.
My lecture note says that for every multilineal $f$ one can derive $f\big|_{x_i=0} \cdot (1-x_i)$ and $f\big|_{x_i=1} \cdot x_i$ from $f$ but I've tried to do so and failed, all useful polynomial I can derive from $f$ are $f x_i$ and $(1-x_i) f$ and I don't see how to derive the needed polynomials from them. Any ideas?
Comment: What do those expressions mean? Should they look like that? $${p ~~~~ q\over \alpha p + \beta q} ~~~~~~ {p \over x_i \cdot p}~~~~~~ {\over x_i^2 - x_i}$$
Comment: Yes, see for instance definitions in https://www.csc.kth.se/~jakobn/research/GeneralizedMethodPCdegree_CCC.pdf
Comment: Thank you, I was not familiar with this topic
Answer: Well, turned out that it's simple:
for every multilinear $f = x_i f\big|_{x_i=1} + (1-x_i) f\big|_{x_i=0}$, therefore $(1-x_i) f\big|_{x_i=0} = f - x_i(1-x_i) (-f\big|_{x_i=1} + f\big|_{x_i=0})$. The latter could be derived from the axiom $x_i^2 - x_i$.
$x_i f\big|_{x_i=1}$ could be derived in a similar way.

Deduction in polynomial calculus.


Writing a function in terms of its power series with some tricky reindexing steps

Question: Represent the following function as a power series and find it's radius of convergence:
$$\frac{x^2}{(8+x)^3}$$

By Using differentiation to find the power series of a fairly tricky function!! We know that
$\frac{1}{(8+x)^3} = \frac{1}{2} (\sum_{n=0}^\infty (-1)^{n+2} (n+2)(n+1) x^n (\frac{1}{8})^{n+3})$
Therefore we have:
$\frac{x^2}{(8+x)^3} = x^2 (\frac{1}{2} \sum_{n=0}^\infty (-1)^{n+2} (n+2)(n+1) x^n (\frac{1}{8})^{n+3})$
Multiplying the $x^2$ through yields
$= \frac{1}{2} (\sum_{n=0}^\infty (-1)^{n+2} (n+2)(n+1) x^{n+2} (\frac{1}{8})^{n+3})$
But we can't have a power series be expressed in terms of $x^{n+2}$. It needs to be in terms of $x^n$. So we subtract a $2$ from everywhere an $n$ appears in our expressoin and make the summation start at $n=2$
$= \frac{1}{2} (\sum_{n=2}^\infty (-1)^{n} (n)(n-1) x^{n} (\frac{1}{8})^{n+1})$
Comment: Solution verification tag
Comment: Whats your question?
Comment: Looks all okay.
Answer: Yes it's correct. Since for $n=0$ and $n=1$ the terms vanish, if you want to start at $n=0$ we can write $$\frac{x^2}{(x+3)^3}= \frac{1}{2} \sum_{n=2}^\infty (-1)^{n} (n)(n-1) x^{n} (\frac{1}{8})^{n+1}=\frac{1}{2}\sum_{n=0}^{\infty}(-1)^n(n)(n-1)x^n(\frac{1}{8})^{n+1}$$
Comment: Yeah that's fine, I said that you can start at $n=0$ because your previous sum: $\frac{1}{8+x^2}$ started at $n=0$.
Comment: Eh, solution manual had it starting at $n=2$, so I just went with that


Filtering an Array based on another Boolean array

Question: Say I have two arrays:
const data = [1, 2, 3, 4]
const predicateArray = [true, false, false, true]

I want the return value to be:
[1, 4]

So far, I have come up with:
pipe(
  zipWith((fst, scnd) => scnd ? fst : null)),
  reject(isNil)
)(data, predicateArray)

Is there a cleaner / inbuilt method of doing this?
Solution in Ramda is preferred.
Answer: This works in native JS (ES2016):
const results = data.filter((d, ind) => predicateArray[ind])

Comment: @CarlosToscano-Ochoa Positional parameters cannot be skipped. It doesn't matter what it's called, you have to specify it.
Comment: What is the purpose of the 'd' parameter? It is not used, so...
Answer: If you really want a Ramda solution for some reason, a variant of the answer from richsilv is simple enough:
R.addIndex(R.filter)((item, idx) => predicateArray[idx], data)

Ramda does not include an index parameter to its list function callbacks, for some good reasons, but addIndex inserts them.
Comment: I'm afraid it's too involved to discuss here, but you can see the relevant Ramda issues: [452](https://github.com/ramda/ramda/issues/452) (contentious), [484](https://github.com/ramda/ramda/issues/484), [729](https://github.com/ramda/ramda/issues/729), and [1061](https://github.com/ramda/ramda/pull/1061)
Comment: Nice solution! Can you share a bit more about the reasons why the index is not included?
Answer: As asked, with ramda.js :
const data = [1, 2, 3, 4];
const predicateArray = [true, false, false, true];

R.addIndex(R.filter)(function(el, index) {
  return predicateArray[index];
}, data); //=> [2, 4]

Updated example to fix issue referenced in the comment.
Comment: This wont work if the data array contains duplicate value, as indexOf will return only the first index


Remote access Ubuntu Server filesystem through GUI

Question: I recently installed Ubuntu Server on an old computer to test various things.
For now, I always accessed the server through ssh in a powershell/cmd session in my win10 laptop.
How can I access the Ubuntu files through with a GUI?
For the moment I just know accessing it through ssh with for example FileZilla.
I also could install (is one built in?) a ftp server an access it.
But what are the ways I could access ubuntu server files with a GUI "out-of-the-box" without needing to install anything?
Comment: Umm... [Nautilus](https://help.gnome.org/users/gnome-help/stable/nautilus-connect.html.en)?
Comment: Do you mean from Windows? Without installing anything in Windows? Or do you mean from Ubuntu (an Ubuntu desktop system)? If from Windows, maybe Samba (in Ubuntu) would be an alternative, see for example https://help.ubuntu.com/community/Samba  ; If from Ubuntu, Nautilus (using ssh) is a good alternative, as suggested by @pomsky.
Comment: TotalCommander can access a remote filesystem through SSH, sort of like sshfs on Linux.
Comment: Thanks sudodus & pomsky I mean without installing anything in ubuntu server. Accessing from Linux & Windows. @sudodus if you post an answer I accept it :)
Answer: The Ubuntu server
When you write that you do not want to install anything in the Ubuntu server, I guess you mean except an SSH server, which you have already (for example openssh-server) or a Samba server according to this link and links from it,
help.ubuntu.com/community/Samba

If you want to log in and run application programs remotely, you can do it via
ssh user@ip-address

or if you want to run GUI application programs remotely,
ssh -X user@ip-address

if you have some basic X software installed in the server, for example
sudo apt-get install fluxbox xinit xterm

and the software you want to run.
From Windows
If you do not want to install anything into Windows, Samba is a good alternative. You can use Explorer and connect to the Samba share like you would connect to a shared directory in another Windows system via the network.
But there are several tools, that can be installed, and that communicate via ssh, not only Filezilla, but also WinSCP. You can also install an SSH client and log in.
From Ubuntu Desktop
If you do not want to install anything into an Ubuntu Desktop system, Nautilus is a good alternative. It can connect via ssh, enter the address into the box for directory to be displayed, for example sftp://email@example.com/home/sudodus and you can save it as a bookmark for easy access later.
And as described earlier, you can run
ssh -X user@ip-address

Answer: Try sshfs, i uses ssh an no need to extra software.
Project source from github: https://github.com/winfsp/sshfs-win
Its avaiable on Windows, linux and mac. You can take a look in this video https://youtu.be/lMC5VNoZFhg?t=547
Answer: You might want to have a look at Webmin, which has a File Manager module.
Setup Webmin repos:
sudo curl -o setup-repos.sh https://raw.githubusercontent.com/webmin/webmin/master/setup-repos.sh
sudo sh setup-repos.sh

Install Webmin:
sudo apt install webmin

Then Webmin can be accessed on the IP address of the host on port 10000 (https://X.X.X.X:10000/).


Invariant Violation: Objects are not valid as a React child using Expo

Question: I am trying to use React's new Context api in my React Native application (using Expo). However I get an error. Please note, I only get this error when I try to abstract away the Context.Provider into a Component.

Here is my UserContext.js code:

import React from "react";
import { SecureStore } from 'expo';
import { AUTH_TOKEN, FIRST_NAME, LAST_NAME, EMAIL } from '../constants/config'

// Signed-in user context
const UserContext = React.createContext();

export class UserContextProvider extends React.Component {

constructor(props) {
    super(props)
    this.state = {
    token: SecureStore.getItemAsync(AUTH_TOKEN) || "",
    firstName: SecureStore.getItemAsync(FIRST_NAME) || "",
    lastName: SecureStore.getItemAsync(LAST_NAME) || "",
    email: SecureStore.getItemAsync(EMAIL) || "",
    };
    this.setUserContext = this.setUserContext.bind(this);
}

setUserContext = (authToken, firstName, lastName, email) => {
    SecureStore.setItem(AUTH_TOKEN, authToken);
    SecureStore.setItem(FIRST_NAME, firstName);
    SecureStore.setItem(LAST_NAME, lastName);
    SecureStore.setItem(EMAIL, email);
    this.setState({
    authToken, firstName, lastName, email
    });
};

render() {
    const {children} = this.props;

    return (
    <UserContext.Provider
        value={{
        ...this.state,
        setUserContext: this.setUserContext,
        }}
    >
        // TODO: Render UserContext presentation component here

        <React.Fragment>
        {children}
        </React.Fragment>
    </UserContext.Provider>
    );
}
}

export const UserContextConsumer = UserContext.Consumer;

Here is part of my App.js code, where I use the UserContextProvider. Please note this is the root of my app:
import { UserContextProvider } from "./contexts/UserContext";

export default () => {
return (
    <ApolloProvider client={client}>
    <UserContextProvider componentChildren={Root}>
        <Root/>
    </UserContextProvider>
    </ApolloProvider>
);
}

I use the UserContextConsumer in one my screens (or components) in the following manner. Please note, the error is thrown when I navigate to the screen in which the below code resides:
import { UserContextConsumer } from '../contexts/UserContext';

.
.
.
<Text style={styles.textLink}>
    <UserContextConsumer>
    {context => {
        return context.token
    }}
    </UserContextConsumer>
</Text>

I am getting the following error:
Invariant Violation: Objects are not valid as a React child (found: object with keys {_40, _65, _55, _72}). If you meant to render a collection of children, use an array instead.
in RCTText (at Text.js:202)
in Text (at LoginScreen.js:26)
in RCTView (at View.js:60)
in View (at createAnimatedComponent.js:154)
in AnimatedComponent (at TouchableOpacity.js:247)
in TouchableOpacity (at LoginScreen.js:24)
in RCTView (at View.js:60)
in View (at Form.js:10)
in Form (at connectStyle.js:384)
in Styled(Form) (at LoginScreen.js:18)
in RCTView (at View.js:60)
in View (at LoginScreen.js:17)
in RCTScrollContentView (at ScrollView.js:791)
in RCTScrollView (at ScrollView.js:887)
in ScrollView (at KeyboardAwareHOC.js:397)
in _class (at Content.js:125)
in Content (at connectStyle.js:384)
in Styled(Content) (at LoginScreen.js:15)
in RCTView (at View.js:60)
in View (at Container.js:15)
in Container (at connectStyle.js:384)
in Styled(Container) (at LoginScreen.js:14)
in LoginScreen (at SceneView.js:9)
in SceneView (at StackViewLayout.js:483)
in RCTView (at View.js:60)
in View (at createAnimatedComponent.js:154)
in AnimatedComponent (at screens.native.js:51)
in Screen (at StackViewCard.js:42)
in Card (at createPointerEventsContainer.js:26)
in Container (at StackViewLayout.js:507)
in RCTView (at View.js:60)
in View (at screens.native.js:76)
in ScreenContainer (at StackViewLayout.js:401)
in RCTView (at View.js:60)
in View (at StackViewLayout.js:400)
in StackViewLayout (at withOrientation.js:30)
in withOrientation (at StackView.js:49)
in RCTView (at View.js:60)
in View (at Transitioner.js:141)
in Transitioner (at StackView.js:19)
in StackView (at createNavigator.js:59)
in Navigator (at createKeyboardAwareNavigator.js:11)
in KeyboardAwareNavigator (at createNavigationContainer.js:376)
in NavigationContainer (at SceneView.js:9)
in SceneView (at SwitchView.js:12)
in SwitchView (at createNavigator.js:59)
in Navigator (at createNavigationContainer.js:376)
in NavigationContainer (at Root.js:24)
in RCTView (at View.js:60)
in View (at Root.js:22)
in Root (at App.js:58)
in UserContextProvider (at App.js:57)
in ApolloProvider (at App.js:56)
in Unknown (at registerRootComponent.js:35)
in RootErrorBoundary (at registerRootComponent.js:34)
in ExpoRootComponent (at renderApplication.js:33)
in RCTView (at View.js:60)
in View (at AppContainer.js:102)
in RCTView (at View.js:60)
in View (at AppContainer.js:122)
in AppContainer (at renderApplication.js:32)

This error is located at:
in RCTText (at Text.js:202)
in Text (at LoginScreen.js:26)
in RCTView (at View.js:60)
in View (at createAnimatedComponent.js:154)
in AnimatedComponent (at TouchableOpacity.js:247)
in TouchableOpacity (at LoginScreen.js:24)
in RCTView (at View.js:60)
in View (at Form.js:10)
in Form (at connectStyle.js:384)
in Styled(Form) (at LoginScreen.js:18)
in RCTView (at View.js:60)
in View (at LoginScreen.js:17)
in RCTScrollContentView (at ScrollView.js:791)
in RCTScrollView (at ScrollView.js:887)
in ScrollView (at KeyboardAwareHOC.js:397)
in _class (at Content.js:125)
in Content (at connectStyle.js:384)
in Styled(Content) (at LoginScreen.js:15)
in RCTView (at View.js:60)
in View (at Container.js:15)
in Container (at connectStyle.js:384)
in Styled(Container) (at LoginScreen.js:14)
in LoginScreen (at SceneView.js:9)
in SceneView (at StackViewLayout.js:483)
in RCTView (at View.js:60)
in View (at createAnimatedComponent.js:154)
in AnimatedComponent (at screens.native.js:51)
in Screen (at StackViewCard.js:42)
in Card (at createPointerEventsContainer.js:26)
in Container (at StackViewLayout.js:507)
in RCTView (at View.js:60)
in View (at screens.native.js:76)
in ScreenContainer (at StackViewLayout.js:401)
in RCTView (at View.js:60)
in View (at StackViewLayout.js:400)
in StackViewLayout (at withOrientation.js:30)
in withOrientation (at StackView.js:49)
in RCTView (at View.js:60)
in View (at Transitioner.js:141)
in Transitioner (at StackView.js:19)
in StackView (at createNavigator.js:59)
in Navigator (at createKeyboardAwareNavigator.js:11)
in KeyboardAwareNavigator (at createNavigationContainer.js:376)
in NavigationContainer (at SceneView.js:9)
in SceneView (at SwitchView.js:12)
in SwitchView (at createNavigator.js:59)
in Navigator (at createNavigationContainer.js:376)
in NavigationContainer (at Root.js:24)
in RCTView (at View.js:60)
in View (at Root.js:22)
in Root (at App.js:58)
in UserContextProvider (at App.js:57)
in ApolloProvider (at App.js:56)
in Unknown (at registerRootComponent.js:35)
in RootErrorBoundary (at registerRootComponent.js:34)
in ExpoRootComponent (at renderApplication.js:33)
in RCTView (at View.js:60)
in View (at AppContainer.js:102)
in RCTView (at View.js:60)
in View (at AppContainer.js:122)
in AppContainer (at renderApplication.js:32)

throwOnInvalidObjectType
AppEntry.bundle?platform=ios&dev=true&minify=false&hot=false&assetPlugin=%2FUsers%2FPasha%2Freact-native-projects%2Fexpo%2Fyumm%2Fnode_modules%2Fexpo%2Ftools%2FhashAssetFiles:9955:20
reconcileChildFibers
AppEntry.bundle?platform=ios&dev=true&minify=false&hot=false&assetPlugin=%2FUsers%2FPasha%2Freact-native-projects%2Fexpo%2Fyumm%2Fnode_modules%2Fexpo%2Ftools%2FhashAssetFiles:10650:37
reconcileChildrenAtExpirationTime
AppEntry.bundle?platform=ios&dev=true&minify=false&hot=false&assetPlugin=%2FUsers%2FPasha%2Freact-native-projects%2Fexpo%2Fyumm%2Fnode_modules%2Fexpo%2Ftools%2FhashAssetFiles:10749:52
reconcileChildren
AppEntry.bundle?platform=ios&dev=true&minify=false&hot=false&assetPlugin=%2FUsers%2FPasha%2Freact-native-projects%2Fexpo%2Fyumm%2Fnode_modules%2Fexpo%2Ftools%2FhashAssetFiles:10744:44
updateContextConsumer
AppEntry.bundle?platform=ios&dev=true&minify=false&hot=false&assetPlugin=%2FUsers%2FPasha%2Freact-native-projects%2Fexpo%2Fyumm%2Fnode_modules%2Fexpo%2Ftools%2FhashAssetFiles:11295:28
performUnitOfWork
AppEntry.bundle?platform=ios&dev=true&minify=false&hot=false&assetPlugin=%2FUsers%2FPasha%2Freact-native-projects%2Fexpo%2Fyumm%2Fnode_modules%2Fexpo%2Ftools%2FhashAssetFiles:14020:31
workLoop
AppEntry.bundle?platform=ios&dev=true&minify=false&hot=false&assetPlugin=%2FUsers%2FPasha%2Freact-native-projects%2Fexpo%2Fyumm%2Fnode_modules%2Fexpo%2Ftools%2FhashAssetFiles:14044:49
renderRoot
AppEntry.bundle?platform=ios&dev=true&minify=false&hot=false&assetPlugin=%2FUsers%2FPasha%2Freact-native-projects%2Fexpo%2Fyumm%2Fnode_modules%2Fexpo%2Ftools%2FhashAssetFiles:14070:23
performWorkOnRoot
AppEntry.bundle?platform=ios&dev=true&minify=false&hot=false&assetPlugin=%2FUsers%2FPasha%2Freact-native-projects%2Fexpo%2Fyumm%2Fnode_modules%2Fexpo%2Ftools%2FhashAssetFiles:14561:40
performWork
AppEntry.bundle?platform=ios&dev=true&minify=false&hot=false&assetPlugin=%2FUsers%2FPasha%2Freact-native-projects%2Fexpo%2Fyumm%2Fnode_modules%2Fexpo%2Ftools%2FhashAssetFiles:14493:32
performSyncWork
AppEntry.bundle?platform=ios&dev=true&minify=false&hot=false&assetPlugin=%2FUsers%2FPasha%2Freact-native-projects%2Fexpo%2Fyumm%2Fnode_modules%2Fexpo%2Ftools%2FhashAssetFiles:14473:22
batchedUpdates
AppEntry.bundle?platform=ios&dev=true&minify=false&hot=false&assetPlugin=%2FUsers%2FPasha%2Freact-native-projects%2Fexpo%2Fyumm%2Fnode_modules%2Fexpo%2Ftools%2FhashAssetFiles:14643:30
batchedUpdates
AppEntry.bundle?platform=ios&dev=true&minify=false&hot=false&assetPlugin=%2FUsers%2FPasha%2Freact-native-projects%2Fexpo%2Fyumm%2Fnode_modules%2Fexpo%2Ftools%2FhashAssetFiles:6775:33
_receiveRootNodeIDEvent
AppEntry.bundle?platform=ios&dev=true&minify=fal

Please let me know if you need additional information. Your help would be greatly appreciated.

Thank you.
Comment: How do you export and use your `UserContextProvider` component?
Comment: Thank you for your comment. I added some information to the question. Essentially, I wrap the root of my app with UserContextProvider and then use UserContextConsumer in of my screens. Does that answer your question?
Comment: You are welcome, but still, I can't see how you export it? Do you export it properly and import it again?
Comment: I added the import statements, import { UserContextProvider } from "./contexts/UserContext"; and import { UserContextConsumer } from '../contexts/UserContext';.
Comment: The exports are done in the UserContext.js file.
Comment: Sorry, I missed the export part of the provider. You are doing it right. Let me dig it up a little bit. If I can find something, I'll comment or provide an answer.
Answer: Ok, I don't how couldn't I see this at the first look but you are trying to render an object directly: token. Here:
<UserContextConsumer>
    {context => {
        return context.token
    }}
</UserContextConsumer>

So, you want to render a property of it maybe?
<UserContextConsumer>
    {context => {
        return context.token._40
    }}
</UserContextConsumer>

Or you can use it in other ways of course, but you can't render it directly.
Comment: Thank you, you are correct, I was convinced that context.token was a String type but you are correct it was actually an Object type.


Problem with create Bounty?

Question: I know this is not a drupal.stackexchange question, but I do have a question on which I am trying to grant bounty. I have 50+ Rep so I want to create a bounty for that question:
Fuzzy Search in Drupal 7 gives no results
I do not see "Start a bounty" option for this question, can someone please quickly guide me what is wrong here?
PS: Moderators can delete this question after someone has guided me on how to open a bounty for this question.
Also, I have tried reading FAQ etc. for bounties, everywhere it is mentioned that question once eligible we can create bounty from 50 to 500 reps, but I don't see that option anywhere!
Comment: Looks like a well described, decent question. We need more of this. I've put a bounty on for you, keep the points you've got so you can comment etc. shan't do this every time so if you're likely to need to start more bounties, pay it forward and participate where you can in the site :)
Comment: Thanks @Clive! So very kind of you!
Answer: You don't have reputation to set bounty. It takes 75 rep to set a bounty, so at the moment you need 6 more.

Problem with create Bounty?


MITM-attack? I have an untrusted certificate dns.hinet.net

Question: Since a few weeks a pop-up window appears (sometimes) after start-up of my Ubuntu 16.4 system, see this picture:

The title in the window bar says: "Untrusted certificate".
The 1st line in the window says: "Cannot safely/securely connect to ....".
The company to which ...stackstorage.com belongs, says that it does not use this certificate, and that from their perspective everything is okay. They say that my system might be under MITM-attack.
I have no idea what to do (and what the danger is). Please help!
(I do'nt use VPN, my ISP is Ziggo (Netherlands), according to my router the IP4 DNS Server is: 184.108.40.206 and 184.108.40.206)
Answer: Checking the hostname on mxtoolbox and ssltools.digicert confirm its down the chain from Chunghwa...
one of its SANs is hntp1.hinet.net / 22.214.171.124dnslytitcs
small extract from 2009 (not mine)

The Hinet.net domain belongs to Chunghwa Telecom Co., Ltd. According to Spamhaus.org (very authoritative), Chungwa a/k/a Hinet is the #4 spammer service company in the world. Like most Asian phone companies, they take nationalistic pride in ignoring complaints from the West. (Mainland China and South Korea are equally imperious, and Viet Nam is even worse.) So lots of email systems in the West are blocking Hinet. It is not to make a political statement. We know Hinet does not care, and does not take protesters seriously. It is a simple mechanical defense against the ongoing spam attack by Hinet's spammers.

I advise you check certificate stores for each browser you have installed these are separate from where you would usually find certs in /etc/ssl/...
Comment: I'd think deleting the archived cert a good idea, you can consider it an answer if the error doesn't come back !
Comment: Thanks for this information (this encourages me to be careful)! However, I still do not know what to do.
Comment: Can you find any certificates on your system containing the domain. https://askubuntu.com/q/1129300/529627
Comment: What service causes this error, maybe you should search the logs for some kind of SSL exception
Comment: I did the awk-command from the suggested askubuntu.com/q/1129300/529627 and in its output the following line occurs:
`subject= /C=TW/O=Chunghwa Telecom Co., Ltd./OU=ePKI Root Certification Authority`

I did not found any occurrences of `hinet` in the output, Also, I did not found any occurrences of either `Chunghwa` nor `hinet` in `/etc/ssl/certs` and `/usr/share/ca-certificates/mozilla/`
Comment: I have no idea how to "search the logs for some kind of SSL exception". I will try to Google for a suggestion.
Comment: In this mozilla.dev.security.policy post you can see 'Chunghwa Telecom eCA Root Inclusion Request' under the hinet.net alias be Denied.

https://groups.google.com/forum/#!msg/mozilla.dev.security.policy/W4VK1JPgiZA/8pCsp9D-AwAJ
Comment: https://bugzilla.mozilla.org/show_bug.cgi?id=1532436

there is on going discussion about 'Chunghwa Telecom' in the Mozilla(bugzilla) forum specifically about the misused certificates and their status as a eCA. Currently they are not in the CA EV list for mozilla.

If you can find and remove the cert from your system that should be enough.
If it re appears you want to block them specifically as a CA from issuing another cert  you would need to do so from your own DNS server using CAA lines https://en.wikipedia.org/wiki/DNS_Certification_Authority_Authorization.
Comment: I found in my browser Firefox a window with the following title (translated from Dutch): "You have archived certificates that identify the following certificate authorities" and in the list there occurs this one: "Chunghwa Telecom Co., Ltd. (ePKI Root Certification Authority  ---  Builtin Object Token)". Should I select this item and press Delete? (IF so, should I formulate this action as a/the answer to my question?)
Answer: Following @Wiper I deleted in Firefox>Preference>Privacy&Security>Certificates>View Certificates...>tab Authoroties the certificate authority ChuChunghwa Telecom Co., Ltd. (ePKI Root Certification Authority --- Builtin Object Token).
Also I have reset to factory settings my modem/router, since internet connection in our house was broken several times a day.
These two together seemed sufficient: no problems anymore.
(But now I've also done a fresh install of Ubuntu 20.04.)


In the last for loop I will to exclude execution of loop when Y=0 is met. How to I do it?

Question: import matplotlib.pyplot as plt
import numpy as np
import math

epsr = float(input('Enter the relative permittivity of waveguide material ')) #permittivity
mur=float(input('Enter the relative permeabilty of waveguide material ')) # permeability
f0= float(input('Enter the operating frequency ')) #operating frequency
LWG= float(input('Enter the length of the waveguide ')) #length of waveguide
rho=float(input('Enter the conductivity of the waveguide material '))# Conductivity
thickness=float(input('Enter the thickness of the waveguide ')) #Thickness
c= 300000000 #Speed of light
lamda0=c/f0 #wavelength in free space
mu0=1.25663706e-6 #permeability of free space
eps0= 8.854187817e-12 # permittivity of free space
k=2*math.pi*math.sqrt(mur*epsr)/lamda0 ##wavenumber
print(k)
N= float(input('Enter the number of slots ')) #No of slots
ln= float(input('Enter the length of the slot ')) #Length of the slot
xn= float(input('Enter the offset of the slot ')) #offset of the slot
#Width of the waveguide
a=float(input('Enter the width of the waveguide ie long dimension  '))
#Height of the waveguide
b=float(input('Enter the height of the waveguide ie short dimension '))
Z0=120*math.pi #impedence of free space
print(Z0)
AOS=(a*b-(a-2*thickness)*(b-2*thickness)) #area of cross section of the waveguide
print(AOS)
G0=rho*AOS/LWG #Conductance of the waveguide
fc=c/(2*a) #cut off frequency
nsa = 1/N #normalized slot admittance
beta=2*math.pi*f0*math.sqrt(1-(pow((fc/f0),2)))/c #factor beta
fn=(math.cos(beta*ln)-math.cos(k*ln))*math.sin(math.pi*xn/a)/math.sin(k*ln)
K1=-1j*math.sqrt(8*(a/b))/(pow(math.pi,2)*Z0*G0*(beta/k))
#K1=pow(math.pi,2)*Z0*G0*(beta/k)
nsv=nsa/(K1*fn*math.sin(k*ln))
lamdag=lamda0/math.sqrt(1-pow((fc/f0),2))
theta = np.linspace(0, 180, 1001)
G=[]
AF=[]
F=[]
print(theta)
for i in  range(1001):
    if math.sin(theta[i])==0:
        G.insert(i,0)
    else:
        p=(math.cos(k*ln*math.cos(theta[i]))-
math.cos(k*ln))/math.sin(theta[i])
        G.insert(i,p)
for q in  range(1001):
    if math.cos(theta[q])==0:
        AF.insert(q,0)
    else:
        m=pow(math.e,(1j*N*k*lamdag/2*math.cos(theta[i])))
        AF.insert(q,m)
for n in  range(1001):
        h=N*nsv*G[n]*AF[n]
        Y=h.real
        if
        Y=0
        print(Y)
        p=math.log10(Y)
        F.insert(n,p)

This is a code to develop the radiation pattern of a rectangular array. I get an error if the log encounters 0 as log10(0) is undefined. Any help in the above topic will be highly appreciated.
The inputs used are in the following sequence:
1.46, 1, 10000000000, 0.5, 35380000, 0.05, 4, 0.05, 0.005, 0.2, 0.1.
Comment: The last `for` loop of your code is syntactically wrong. Please fix it. Also, remove all unnecessary code.
Comment: as a general advice for debugging and to help your questions being better  received, read [mcve] (the missing part here is "minimal")
Answer: I think you are saying "if Y not equal to 0, then...", which programmatically is:
if Y != 0
Updating your loop. I'm guessing you want to avoid the insert into F as well when Y is 0.
for n in  range(1001):
        h=N*nsv*G[n]*AF[n]
        Y=h.real
        if Y!=0:
            print(Y)
            p=math.log10(Y)
            F.insert(n,p)

Answer: This part of your last loop
    if
    Y=0
    print(Y)
    p=math.log10(Y)
    F.insert(n,p)

is not syntactically correct; you probably meant
    if Y==0:
        print(Y)
    p = math.log10(Y)
    F.insert(n, p)

But the log10(0) will still be evaluated, so add the else branch:
    if Y==0:
        print(Y)
    else:
        p = math.log10(Y)
        F.insert(n, p)

and if you want print nonzero values of Y, too, put the print() function just before if:
    print(Y)
    if Y==0:
        pass             # do nothing, but syntactically something here is needed
    else:
        p = math.log10(Y)
        F.insert(n, p)

But in this case, you don't need two branches, so only negate your condition:
    print(Y)
    if Y != 0:
        p = math.log10(Y)
        F.insert(n, p)

or - as the nonzero values are in the if statement evaluated as True:
    print(Y)
    if Y:
        p = math.log10(Y)
        F.insert(n, p)

Note that I did some small style changes in your code in concordance with PEP 8 -- Style Guide for Python Code.


Intellij can't load ModelBuilderService$Ex class

Question: I was working normally with the IDE when this message appeared:
enter image description here
At first the problem appears only in one project but then many other projects started failing.
How can i fix it?
I'm using gradle 4.10 (this is the standard in my work so i can't update the version) and the intellij is the 2020.3.
Comment: Did you lately upgrade the IntelliJ version? If yes try to completely reinstall IntelliJ and Gradle. When I updated to version some of the plugins I had completely stopped working. But I fixed it with reinstalling the software.
Comment: Have you updated Kotlin plugin? Looks like [KTIJ-866](https://youtrack.jetbrains.com/issue/KTIJ-866). Please make sure to use the latest IDE version https://www.jetbrains.com/idea/download and the latest Kotlin plugin.
Answer: I was having the same issue, I fixed it by going to File > Close Project then to Help > Check for Updates and installing the updates, had to Check for Updates twice to get them all, your mileage may vary.


Trying to get specific values from a custom made drop down menu

Question: I'm trying to create a custom select menu(I just wanted to see if I could do it) and I'm having some issues.  When the user clicks on the box, I want the user to be able to select an option and have it show up in that particular box.  The problem I'm having is that the selected text shows up in each box, regardless of which menu they're selecting from.  How do I fix this?
Here's my pen.
http://codepen.io/RobbyT15/pen/LIKsJ
select

Hello

Goodbye

A

B

C

script
$(document).ready(function(){
    var select = $(".select");
    $(select).on("click", function(){
        $(this).find(".option-menu").each(function(){
            $(this).toggle();
        })

        $(".option").on("click", function(){
            $(".active").removeClass("active");
            $(this).addClass("active");
            $(select).children("p").remove();
            var option = $(this).text();
            console.log(option);
            $(select).prepend("
" +option +"
");
        })
    })
})

Answer: When you click on some option yo are refering to the variable select

var select = $(".select");

That calls all the elements with class select, you nedd to make more specific the selector. Try adding this line:
$(select).on("click", function(){
    select = $(this); //ADD THIS
    $(this).find(".option-menu").each(function(){
    $(this).toggle();
})

Check the Demo http://codepen.io/anon/pen/GaemF
Answer: You have to use specific container div

Hello

Goodbye

var select = $(".container1 .select");
    $(select).on("click", function(){
        $(this).find(".option-menu").each(function(){
            $(this).toggle();
        })

        $(".container1 .option").on("click", function(){
            $(".active").removeClass("active");
            $(this).addClass("active");
            $(select).children("p").remove();
            var option = $(this).text();
            console.log(option);
            $(select).prepend("
" +option +"
");
        })
    })

Your problem is you are using same classes for 2 elements.
If I were you, I write this kind of code as jquery plugin.
// With plugin you can create your code with one line of code.
$('#container').createSelectMenu();
Comment: I would like to make this a plugin, but I haven't got the slightest clue as to how.  Perhaps I should research it.


I know that the binary and hexadecimal are useful, but what are the point of other bases, for example base 12?

Question: I know about the uses of binary and hexadecimal, but what are the uses of other bases, for example base 12? (or duodecimal)
Comment: In base 12, a dozen eggs becomes 10.
Comment: Mostly they're useful for understanding the arbitrariness of base ten. (That being said, people [have built ternary computers](https://en.wikipedia.org/wiki/Setun)...)
Comment: @GerryMyerson That sounds like reason enough to switch to a more sensible system, like base 6, where your dozen becomes 20 instead.
Comment: There is nothing gained by forbidding other bases.
Answer: We use base 60 for time and for degrees.
I don't know any practical use of base 12, but it would certainly be nicer than base 10. For instance, in base 12 the number 1/3 is not periodic: you have $$1/3=4/12=4\times 12^{-1}=0.4_{12}.$$
Comment: They certainly did know how to deal with fractions. The reason for base 60 was due to its convenience in scientific computations. Much like we use binary today due to its convenience with digial representations of numbers.
Comment: This is the exact reason for bases 12 and 60: the ancient mathematics did not know how to deal with fractions, but with base 12 you have integer numerators for all the fractions with denominators with 3 and 4 as factors. In base 60 you have the same result with denominators multiple of 3, 4 and 5.
Comment: @N74 I don't think "didn't know how to deal with fractions" is a fair characterization; see Plimpton 322, which seems to suggest that $1 + 24/60 + 51/60^2 + 10/60^3 \approx \sqrt 2$
Comment: @pjs36 still they did not use the zero or the decimal point and all the fractions had base 60 (or multiples). They surely got amazing results but limited by the "refuse" of numbers incompatible with the chosen base. Probably they thought $1/7$ as "irrational" as $\sqrt{2}$.
Answer: Conversion between different bases turns out to be a useful way to talk about various pathological functions in analysis.
Some examples of this:

The Cantor function $c$: the base-2 expansion of $c(x)$ is closely related to the base-3 expansion of $x$.
The Conway base-13 function $f$: the base-$10$ expansion of $f(x)$ is closely related to the base-$13$ expansion of $x$ (or, more generally, you could have a version of it where the base-$k$ expansion of $f(x)$ was closely related to the base-$(k+3)$ expansion of $x$, for any $k \geq 2$).
Answer: The theory for developing and computing the binary or hexadecimal representation of a number applies equally well to other bases. They may or may not be useful. If some species of alients have 12 fingers they may find base 12 useful.
Having too large base has one practical difficulty: finding names for the numbers and remembering them. Too small a base makes even a moderately small number requiring large number of digits to write down.
Civil engineers may have the right math that tell us how deep a foundation has to be to build a 500-storey building. Will we build it?
Comment: All bases except base 1 offer essentially the same efficiency when it comes to number of digits required for writing a number down.
Comment: @IttayWeiss: I don't understand what you mean by 'same efficiency'. I will make my meaning clearer: The number of days in a year can be written in base 10 using 3 digits, and  the same in base 2 requires 9 digits (or bits).
Comment: I mean that the difference in number of digits required between two different bases (not equal to 1) is negligible compared to the magnitude of the number being represented.
Comment: I understand now.
Answer: Their use is precisely the use you have for base $10$: they provide a means of representing numbers concretely. The only difference between  $17_{10}$ and $10_{17}$ is that you are accustomed to the former representation rather than the latter to represent the number of periods in the quoted symbol ".................".


change application name in openshift after myapp.war deployed

Question: i have been trying to change my openshift cloud app name from
appname-domain.rhcloud.com to appname-domain.rhcloud.com/myapp/

as mentioned in this link i have deployment my own custom war file in openshift jboss server.
but how to change my cloud url to this appname-domain.rhcloud.com/myapp/, where initially i deployed ROOT.War file, which now i want to deploy my war file as myapp.war file.
Answer: To deploy a WAR file you have to put the WAR file inside deployments directory of your OpenShift application. Rename the ROOT.war to myapp.war and copy it to deployments directory. Then run the following commands.
git add .
git commit -am "added myapp.war"
git push

Comment: i have followed your steps still no luck


"Noscript" Shows Raw HTML when the Page is Reloaded without JavaScript

Question: I have a pop up message that tells the user when JavaScript is disabled.  The problem is happening in Chrome.
Here's the site with just my : Cloud9 Website.  It's blank if you have JavaScript enabled.  Here's how to duplicate my experience:

View the blank page.
Disable JavaScript.
Reload the page.

You should be able to see the raw HTML that's inside the .  If you reload the page again, then the proper message pops up.
I also tested this locally with XAMPP: same thing.
This is my HTML:

This website requires JavaScript to run.  Pleaseenable it or use a web browser that supports JavaScript.

Comment: Here's a [Chromium bug report](https://code.google.com/p/chromium/issues/detail?id=232410&q=noscript%20reload&colspec=ID%20Pri%20M%20Iteration%20ReleaseBlock%20Cr%20Status%20Owner%20Summary%20OS%20Modified) for this issue.
Comment: Do you know how often Chrome is updated for bug fixes?  I see that the issue was reported on April 17th.
Comment: They prioritize, and this is sort of an annoyance that can happen in this unusual circumstance, but it's not a critical issue, so don't hold your breath. One thing you could do would be to put a very visible HTML comment above the rest of the HTML instructing Chrome users that if they can see the message, it's a bug in Chrome, and they should refresh their browser. Also, "star" that but report if you haven't yet.
Answer: While this is a bug, you could use this work around:

This website requires JavaScript to run. Please enable it or use a web browser that supports JavaScript.


Prevent apps from being launched by monkey test

Question: I'm currently running a continuous monkey test to test the stability of a device, and I've noticed that when using monkey, it's able to change settings, including developer options and whatnot. Is there any way to prevent it from being launched, without limiting it to a specific package?
I've tried using chmod 600 /system/priv-app/Settings.apk, but it could still be launched, and I'm not sure where it would be installed to otherwise.
Would the best option just to be manually list out all packages in the system, and then use -p for all of them?
Thanks!
Answer: Yes, it will as Monkey Test as the name suggests is used to create a random sequence of user touches for your app and those touches can be anything including opening other apps, what exactly are you looking for
Answer: It turns out there's a flag you can use to provide a text file with a list of names of packages you want to exclude (--pkg-blacklist-file path/to/blacklist.txt, and it won't launch those at all (since the monkey test launches applications via intents, not the launcher).
More info: android monkey test exclude some packages
Answer: You can use
adb shell pm disable $apk

to disable a specific package in your devices.
For example, if you want to disable system setting package.
First, use:
adb shell pm list packages | grep setting

to list all the packages in your devices, and find the system settings package: com.android.settings
Then use:
adb shell pm disable com.android.settings

to disable system settings.
After test, use
adb shell pm enable com.android.settings

to enable system settings.


Azure AD B2C date attribute without Custom Policies

Question: I need users to enter a date when signing-up or editing their profile in Azure AD B2C. Is there any way to do this without using Custom Policies?
I see two options:

Use a string extension attribute with a text input. But you cannot do client-side validation...
Use 3x string extension attributes (day, month, year) with 3x single-select drop-down inputs. I think this is the way I will need to do it.

Is there a simpler way? Am I missing something?
Why not use Custom Policies? This is the only functionality I am missing using the built-in policies, so it seems like overkill to introduce the additional complexity of getting everything working with Custom Policies, just to get a valid date. Plus Custom Policies are in preview at the time of asking, so are subject to change etc.
Many thanks!
Answer: I opened a question on the MSDN forums to see if I could get an answer there.
To sum it up, you need to use Custom Policies.
My concern regarding using features in Public Preview was addressed like so:

We recommend built-in policies for most scenario's. However, for specific requirement (scenario) built-in policies may not fetch you the actual results. In that situation, you have to use custom policies. Yes, you're right, Microsoft does not recommend using preview features in production environment. It is good to be cautious and follow the recommendations.


How do I include my def clean_slug function into my views or template so that it will work and show "title alr exist"

Question: Hi I have written a def clean(self) function in forms to make sure that if there was previously already a post with the same title, they will return a message saying that the title already exists and hence the form cannot be submitted.
Problem now:
When I enter a title that already exists and I try to create the post, all data previously input will be removed and I will be redirected to a fresh form. No errors were raised. What I want is for the error to be raised and shown to the user when I try to click on the create button so all data remains there and the user knows and can change the title before attempting the create the blog post again.
return cleaned_data in forms.py is not defined too...giving a nameerror
Guideline:
Note! There is NO slug field in my form. The slug is only for the url for each individual blogpost. But basically the slug consists of the title. Eg if my username is hello and my chief_title is bye, my slug will be hello-bye. Both the slug and the title has to be unique as you can see in the model, but there is no slug in the form.
models.py
class BlogPost(models.Model):
 chief_title                    = models.CharField(max_length=50, null=False, blank=False, unique=True)
 brief_description = models.TextField(max_length=300, null=False, blank=False)
 author                     = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
 slug                   = models.SlugField(blank=True, unique=True)

views.py
def create_blog_view(request):
    context = {}
    user = request.user
    if not user.is_authenticated:
        return redirect('must_authenticate')
    if request.method == 'POST':
        form = CreateBlogPostForm(request.POST or None, request.FILES or None)

        if form.is_valid():
            obj= form.save(commit = False)
            author = Account.objects.filter(email=user.email).first()
            obj.author = author
            obj.save()
            obj.members.add(request.user)
            context['success_message'] = "Updated"
            return redirect('HomeFeed:main')
        else:
            form = CreateBlogPostForm()
            context['form'] = form
    return render(request, "HomeFeed/create_blog.html", {})

forms.py
class CreateBlogPostForm(forms.ModelForm):
    class Meta:
        model = BlogPost
        fields = ['chief_title']

    def clean(self):
        chief_title = self.cleaned_data['chief_title']
        qs = BlogPost.objects.filter(chief_title=chief_title)
        if qs.exists():
            raise forms.ValidationError('Post already exists')
        return cleaned_data

html
  <form class="create-form" method="post" enctype="multipart/form-data">{% csrf_token %}

    {% if form.non_field_errors %}
   {{form.non_field_errors}}
    {% endif %}

    Chief Title!
    <input class="form-control" type="text" name="chief_title" id="id_title" placeholder="Title" required autofocus>

   {{form.chief_title.errors}}

   <button class="submit-button btn btn-lg btn-primary btn-block" type="submit">CREATE</button>

  </form>

Comment: if you refresh the page obviously data is lost. Workarounds are to save that data is a session and if object exists in the session use it as initial data.
Comment: Use a form view. It will take care of that automatically by the  form_invalid method.
Comment: Did you find a solution? Would you like to share if none of the answers are offering one?
Comment: @raratiru didnt work :(
Comment: You aren't a [Dutch](https://zen-of-python.info/), are you?
Answer: Well you can create a custom validator to check if the slug exists:
from django.core.exceptions import ValidationError

def validate_slug_exists(value):
    blog_post = BlogPost.objects.filter(slug=value)
    if blog_post.exists():
        raise ValidationError('The post with a given title already exists')

Then in your form add this validator to the fields validators list:
class CreateBlogPostForm(forms.ModelForm):
    chief_title = forms.CharField(validators = [validate_slug_exists])

UPDATE
You can also try using validate_unique() in your form class:
def validate_unique(self, exclude=None):
    qs = BlogPost.objects.all()

    if qs.filter(chief_title=self.chief_title).exists():
        raise ValidationError("Blog post with this title already exists")

Comment: hi bro, the custom validator is in views.py is it?
Comment: Anywhere you want to put it, I recommend putting it in your `forms.py` file so you don't have to import it
Comment: hey bro getting an error, I have updated the question for you to see the error
Comment: right, my mistake, check out the edited version
Comment: Hmm, try using `{{ form.non_field_errors }}.`
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/227795/discussion-between-sldem-and-leung2).
Answer: You can raise a ValidationError as shown in the docs. This would then be displayed in the form for the user.
    def clean_slug(self):
        slug = slugify(self.cleaned_data.get("chief_title")) if len(self.cleaned_data.get("slug", )) == 0 \
            else self.cleaned_data.get("slug", )
        if BlogPost.objects.filter(slug=slug).exists():
            raise ValidationError(_('Slug already exists.'), code='invalid')
        return slug

Comment: hello, do I need to add anything to my views.py and template? I have replaced my code with yours but basically the form still wasnt valid and no error was raised
Comment: in my form, there is only a chief_title form for them to fill, and the chief_title will be part of the slug field. Is the clean_slug function written correctly?
Comment: How are you rendering the entire form? Are you not using this approach? https://docs.djangoproject.com/en/3.1/topics/forms/#rendering-fields-manually
Comment: hey bro, I have updated the question and the codes in the question so hopefully everything's clearer. You could check it out to see if the problem can be solved :) @dacx
Answer: If you set unique = True Django takes care of checking whether another entry already exists in the database and adds an error in ModelForm.errors.
This is happening inModelForm.validate_unique.
There is no need to bother with this method unless you want to add more info in the error, such as the url of the existing object (it will cost 1 db hit).
Otherwise, the error already exists and you can just return the form with its errors instead of returning a new instance of the form as you currently do in views.py.
Therefore the following views.py as explained in this post should do what you are trying to do:
app/views.py:
def create_blog_view(request):
    context = {}
    # ...
    if request.method == 'POST':
        form = CreateBlogPostForm(request.POST or None, request.FILES or None)
        if form.is_valid():
            # do your thing
        else:
            context['form'] = form
    return render(request, "HomeFeed/create_blog.html", context)  # context instead of {}

If you want to get fancier and hit the db once more, you can add the url of the existing object in the errors list as such:
project/settings.py
...
# If you want to provide more info
MY_UNIQUE_BLOGPOST_ERROR_MESSAGE = "This BlogPost already exists"
...

app/models.py
from django.db import models
from django.conf import settings
from django.urls import reverse

class BlogPost(models.Model):
    # ...
    slug = models.SlugField(
        blank=True,
        unique=True,
        error_messages={"unique": settings.MY_UNIQUE_BLOGPOST_ERROR_MESSAGE),
    )

    def get_admin_url(self):
        return reverse("admin:app_blogpost_change", args=(self.id,))
    ...

app/forms.py
from django import forms
from django.conf import settings
from django.utils.html import format_html
from itertools import chain
from app.models import BlogPost

class CreateBlogPostForm(forms.ModelForm):
    class Meta:
        model = BlogPost
        fields = '__all__'

    def validate_unique(self):
        '''
            If unique error exists, find the relevant object and return its url.
            1 db hit
            There is no other need to override this method.
        '''
        super().validate_unique()
        if settings.SHOP_ENTITY_UNIQUE_ERROR in chain.from_iterable(
            self.errors.values()
        ):
            instance = BlogPost.objects.get(slug=self.instance.slug)
            admin_url = instance.get_admin_url()
            instance_name = instance.__str__()

            self.add_error(
                None,
                forms.ValidationError(
                    format_html(
                        "This entry already exists: {1}",
                        admin_url,
                        instance_name,
                    ),
                    code="unique",
                ),
            )