WebView OutOfMemoryException

Question: I'm loading long pages into a WebView using loadData(), unfortunately after around 5 or 10 page links it gives an OutOfMemoryException. This is likely caused by the history holding the full data: url of every page.
I have a memory & cpu monitor in the status bar, and it always shows hardly any memory usage, so the app isn't using up all memory. Is there a way to allow my app to use more memory, similar to Java's command-line switches? Is there a way to make the webview more efficient, perhaps by making a cache on the sd card, to prevent this crash?
06-27 12:02:44.746: WARN/System.err(6692): java.lang.OutOfMemoryError
06-27 12:02:44.746: WARN/System.err(6692):     at java.lang.AbstractStringBuilder.enlargeBuffer(AbstractStringBuilder.java:97)
06-27 12:02:44.746: WARN/System.err(6692):     at java.lang.AbstractStringBuilder.append0(AbstractStringBuilder.java:157)
06-27 12:02:44.746: WARN/System.err(6692):     at java.lang.StringBuilder.append(StringBuilder.java:217)
06-27 12:02:44.746: WARN/System.err(6692):     at android.webkit.BrowserFrame.startLoadingResource(BrowserFrame.java:710)
06-27 12:02:44.746: WARN/System.err(6692):     at android.webkit.BrowserFrame.nativeLoadUrl(Native Method)
06-27 12:02:44.746: WARN/System.err(6692):     at android.webkit.BrowserFrame.loadUrl(BrowserFrame.java:248)
06-27 12:02:44.746: WARN/System.err(6692):     at android.webkit.WebViewCore.loadUrl(WebViewCore.java:1564)
06-27 12:02:44.746: WARN/System.err(6692):     at android.webkit.WebViewCore.access$1400(WebViewCore.java:52)
06-27 12:02:44.746: WARN/System.err(6692):     at android.webkit.WebViewCore$EventHub$1.handleMessage(WebViewCore.java:950)
06-27 12:02:44.746: WARN/System.err(6692):     at android.os.Handler.dispatchMessage(Handler.java:99)
06-27 12:02:44.746: WARN/System.err(6692):     at android.os.Looper.loop(Looper.java:123)
06-27 12:02:44.746: WARN/System.err(6692):     at android.webkit.WebViewCore$WebCoreThread.run(WebViewCore.java:623)
06-27 12:02:44.746: WARN/System.err(6692):     at java.lang.Thread.run(Thread.java:1096)
06-27 12:02:44.746: WARN/dalvikvm(6692): threadid=8: thread exiting with uncaught exception (group=0x40020ac0)
06-27 12:02:44.756: ERROR/AndroidRuntime(6692): FATAL EXCEPTION: WebViewCoreThread
06-27 12:02:44.756: ERROR/AndroidRuntime(6692): java.lang.OutOfMemoryError
06-27 12:02:44.756: ERROR/AndroidRuntime(6692):     at java.lang.AbstractStringBuilder.enlargeBuffer(AbstractStringBuilder.java:97)
06-27 12:02:44.756: ERROR/AndroidRuntime(6692):     at java.lang.AbstractStringBuilder.append0(AbstractStringBuilder.java:157)
06-27 12:02:44.756: ERROR/AndroidRuntime(6692):     at java.lang.StringBuilder.append(StringBuilder.java:217)
06-27 12:02:44.756: ERROR/AndroidRuntime(6692):     at android.webkit.BrowserFrame.startLoadingResource(BrowserFrame.java:710)
06-27 12:02:44.756: ERROR/AndroidRuntime(6692):     at android.webkit.BrowserFrame.nativeLoadUrl(Native Method)
06-27 12:02:44.756: ERROR/AndroidRuntime(6692):     at android.webkit.BrowserFrame.loadUrl(BrowserFrame.java:248)
06-27 12:02:44.756: ERROR/AndroidRuntime(6692):     at android.webkit.WebViewCore.loadUrl(WebViewCore.java:1564)
06-27 12:02:44.756: ERROR/AndroidRuntime(6692):     at android.webkit.WebViewCore.access$1400(WebViewCore.java:52)
06-27 12:02:44.756: ERROR/AndroidRuntime(6692):     at android.webkit.WebViewCore$EventHub$1.handleMessage(WebViewCore.java:950)
06-27 12:02:44.756: ERROR/AndroidRuntime(6692):     at android.os.Handler.dispatchMessage(Handler.java:99)
06-27 12:02:44.756: ERROR/AndroidRuntime(6692):     at android.os.Looper.loop(Looper.java:123)
06-27 12:02:44.756: ERROR/AndroidRuntime(6692):     at android.webkit.WebViewCore$WebCoreThread.run(WebViewCore.java:623)
06-27 12:02:44.756: ERROR/AndroidRuntime(6692):     at java.lang.Thread.run(Thread.java:1096)

The strange thing is, DDMS Heap view shows it had plenty of "Free" memory, but it still may give an error such as:
ERROR/dalvikvm-heap(10612): Out of memory on a 1153232-byte allocation.

I don't know if it's at all related, but sometimes it gives this warning when opening a page, before out-of-memory:
ERROR/Web Console(18033): SECURITY_ERR: DOM Exception 18: An attempt was made to break through the security policy of the user agent. at ...
Answer: Have you considered implementing onLowMemory() and using freeMemory on the WebView?  You could also use clearCache.  Another consideration would be to change the cache mode.
Comment: I put a Log.d in onLowMemory, it didn't even log before it ran out of memory and crashed. According to the docs: "This is called when the overall *system* is running low on memory..."
Comment: Setting cache mode to LOAD_NO_CACHE doesn't fix it either.
Comment: Take a look at the recommendation here: http://stackoverflow.com/questions/2881139/outofmemoryerror-what-to-increase-and-how  Appears you are building a StringBuilder which in turn may be breaking the Heap size so WebView is only part of the problem.
Answer: I switched to loadDataWithBaseURL, which doesn't require URLEncoder encoding the url, and doesn't keep huge data urls in the history. This seems to have fixed the high cpu use and memory leak, and the SECURITY_ERR:
WebView.loadDataWithBaseURL(url,data,"text/html","UTF-8",url);

WebView OutOfMemoryException


Do I lose mass faster as one big cell, or multiple small ones?

Question: From observing my mass count I've seen that the bigger a cell is, the faster that cell loses its mass. However, when you have multiple cells, each of the cells loses mass concurrently.
My question is, given the total amount of mass between all cells is the same, do you passively lose mass faster as one large cell or multiple smaller ones?
For example, if I were to split into two 50 mass cells then later rejoin, would I have lost the same, less or more mass than if I were to have stayed as an 100 mass cell?
Answer: After reading the source code here, the formula for decay is:

mass = mass * (1 - playerRate * gameRateModifier)

By default, playerRate is .002, and gameRateModifier is 1.
Because of the distributive property of multiplication, the decay rate is the same. Using your example, the first total mass post decay for the single hundred mass cell is:

100 (1 - (.002 * 1)) = 99.8

And the total for two cells of mass fifty:

2 * 50 (1 - (.002 * 1)) = 99.8

As you can see, the masses are the same. So to answer your question: No, there is no difference in the rate of decay based on distribution of mass across cells.
Answer: From the tests I have just done (I have tested being one big cell over a long period of time and tested being the same mass altogether but being divided into many smaller cells), it looks like there is no difference to the amount of mass lost dependent on the number of cells.
Comment: What was the test you did?
Comment: I'll edit the post.
Answer: While your rate of loss is the same regardless of splitting, your rate of GAIN from eating points is increased greatly by splitting, because both your speed and your width are increased.  This is most notable in a game that is down to only a few players; splitting into 16 and "sweeping" dense starfields can gain you a lot of mass quickly.  Of course, if anyone else is nearby, better not!


Why can this javascript function not access a variable in the same class?

Question: For some reason, the player_controller instance variable created on the asterisked line cannot be called in the update function below. When I run this code, the second asterisked line (the console.log) will recognize and print the specified variable from player_controller to the console. However, when I try to use player_controller in the update function below (the double asterisked line), I get the error: "TypeError: this.player_controller is undefined."
Also note that if the bold line is commented out, the other lines (which have similarly created variables) run without errors.
Can anyone tell me what's going on here?
    function Engine(){
    var GRAVITY = 0.3;

    this.map_loader = new MapLoader();
    *this.player_controller = new PlayerController();*
    this.map = this.map_loader.load_next_map();
    *console.log(this.player_controller.keys_down.A);*

    this.update = function(){
        **this.player_controller.handle_input(this.map.player);**
        gravity(this.map.player);
        this.map.player.x += this.map.player.dx;
        this.map.player.y += this.map.player.dy;
        ...
        ...

edit: Didn't realize I couldn't do formatting in code blocks.
Here is a link to the app, if you view the web console while on this page you'll see the error I'm talking about piling up. http://lukescode.net/senior_project_game/main.html
Comment: You might want to create an [SSCCE](http://www.sscce.org) to perfectly demonstrate your problem.
Comment: How is update being called? That's what determines the `this` value within the function.
Comment: update() is being called with `engine.update()` after creating an Engine object with `engine = new Engine()`.
Comment: Strange, that should work. Unfortunately I can't check your link right now (on iPad, no console).
Comment: Actually engine.update is called with `setInterval(engine.update, 1000/60)` sorry about that.
Comment: Then try `setInterval(function(){ engine.update() }, 1000/60)`. Callbacks to setInterval and setTimeout run with the global object as their `this`.
Answer: Possibly you create engine as
var engine = Engine();

instead of
var engine = new Engine();

Comment: I tried this and it gives a plethora more errors in places where I'm using the engine class, not to mention that I am generally looking to follow good object oriented practices in this project. Thank you for the suggestion though.
Answer: The problem ended up being that I was making the call to Engine.update with setInterval(engine.update, 1000/60) which, as bfavaretto mentioned in a comment, changes 'this' to be something other than the engine in the update function. The solution was to call the function like this:
setInterval(function(){return engine.update();}, 1000/60)
which causes 'this' to properly refer to the object the update function belongs to instead of the window. Thanks to bfavaretto for pointing me in the right direction.


Wordpress enqueue stylesheet only if a pattern is used

Question: Using Wordpress 6.3 Block Editor (Gutenberg) we can register block patterns. These patterns are a preconfigured collection of blocks.
add_action('init', function () {

    register_block_pattern(
        'my_test_pattern',
        array(
            'title' => 'My Test Pattern',
            "categories" => ['text'],
            'description' => 'Test',
            'content' => "

Something

            ",
        )
    );

});

We can check that this pattern is registered across the entire site:
WP_Block_Patterns_Registry::get_instance()->is_registered("my_test_pattern")

But is there a way to check when it is actually used so that we can enqueue a stylesheet on pages only when it is used.
With blocks, there is a function called has_block("block-name") but there is no similar function for has_pattern.
EDIT / IDEA
I think the problem may be whilst blocks are saved with their names in post_content, patters are not with their containing blocks stored in post_content.
On idea would be to create a custom block. Provide a field in the InspectorControl to give a custom pattern name and when that block renders it it ensues a css file with that provided pattern name if it has not already be enqueued. I'm sure that will work but it seems a little over the top.
Answer: Given a block pattern is a collection of blocks, and individual blocks have their own associated styles, maybe what you are looking for can be accomplished with Block Themes instead. This way, you could declare your required block pattern in the HTML template file as part of the theme and have finer control over the CSS styles via theme.json when the blocks appear together.
Another option is when you add a block pattern to a post/page, convert it into a synced pattern (formerly known as a reusable block). Now the synced pattern has a unique ID is associated with it that could be used to find out if it's in a post/page or include a custom CSS style to target it.
Comment: Both methods would load the styles regardless of whether the block was used. The idea is to only enqueue the stylesheet associated with the pattern when said pattern is used. I've found an alternative method creating template-specific stylesheets and with a custom block that loads assets when relevant. The only pitfall to both of these is that it requires the editor to be refreshed to see the styles added.


how to update multple rows in mysql with php

Question: i have a table like this
id | website | ping |  online |
-------------------------------
1  |xxxx.com | 30   | 1
-------------------------------
4  |xxxx.com | 46   | 1
-------------------------------
5  |xxxx.com | 10   | 0
-------------------------------
8  |xxxx.com | 90   | 1
-------------------------------
11 |xxxx.com | 200  | 0

i want to know how to update the ping and the online rows in all the table without changing the id and website i already have the ping and the online functions
Comment: This question does not show any research effort. It is important to **do your homework**. Tell us what you found and ***why*** it didn't meet your needs. This demonstrates that you've taken the time to try to help yourself, it saves us from reiterating obvious answers, and most of all it helps you get a more specific and relevant answer. [FAQ](http://stackoverflow.com/questions/how-to-ask).
Comment: http://dev.mysql.com/doc/refman/5.0/en/update.html
Comment: i know the update Syntax but i dont know how to update the whole table because the IDs are not successive
Comment: @user2295756 - would you add your UPDATE statement to the question?
Answer: You are going to have to read the entire table, and then iterate through that recordset, getting the ID and using that to UPDATE the table with the new value for that ID.
Something like (pseudocode)
records = db.executeSQL("SELECT * FROM TABLE");
foreach record in records
    $id = record.id
    $whateverping = the new ping for ID=$id
    $whateveronline = the new online for ID=$id
    result = db.executeSQL("UPDATE TABLE SET ping=$whateverping, online=$whateveronline WHERE ID=$id);


Apache2 reverse proxy multiple sources into one http connection

Question: I'm trying to create a proxy on my Apache2 web server. It's not really pertinent to the question, but I have a Raspberry Pi running a music player with an HTTP interface attached to an unrestricted internet connection. I want to be able to control the music from a work machine which is behind a content filter that blocks Spotify.
Client ---> Content Filter ----> My proxy ---> Unblocked target server
                                                       |
                                                       |
                                                      /
                                            Blocked content
I want clients to be able to connect to my proxy server and view the pages on my unblocked target server. I am currently able to do this using the following code in my VirtualHost section:
<Location "/foo">
    ProxyPass "http://targetserver/bar"
    Order allow,deny
    Allow from all
</Location>

This allows me to see the page when I visit http://myproxy/foo but it doesn't load completely. I know that this is from content that is being blocked by a content filter that I cannot influence.
How do I configure my Apache2 proxy server to also forward the content that the client would normally receive from external servers? I want my proxy server to provide all the content to the client for this web interface opaquely.
Thanks in advance for your time.
Answer: Solved it!
I needed to proxy the websockets as well. Adding the following lines worked:
ProxyPass /foo/ ws://targetserver/bar/
ProxyPassReverse /foo/ ws://targetserver/bar/


This appear after login with SSH: * Overheard at KubeCon: "microk8s.status just blew my mind"

Question: Anyone knows what does this message means? It started to appear after SSH login in a server Ubuntu 16.04. This is wierd Thank you.
Answer: That message is generated by the MOTD (Message of the Day) when you log into a system via ssh.  That message is actually generated from /etc/update-motd.d/50-motd-news by pulling the text from https://motd.ubuntu.com/
Example:
terrance@terrance-ubuntu:~$ /etc/update-motd.d/50-motd-news

 * Overheard at KubeCon: "microk8s.status just blew my mind".

     https://microk8s.io/docs/commands#microk8s.status

To configure if you see the news or not or if you want it to show something of your own look at editing /etc/default/motd-news where it is stated:
# This is a useful way to provide dynamic, informative
# information pertinent to the users and administrators
# of the local system

Comment: It also seems reasonable that one might be "worried" about not wanting to be forced to look at an arbitrary message over which they have no control every time they log into their system.
Disable this by editing /etc/default/motd-news
Set ENABLED=0
Comment: I do think that "nothing to worry about" is inappropriate in an answer, Answers should be kept factual and not based on personal opinion. Some people do not like arbitrary automated processes making connections to the internet.
Comment: To turn it off, edit /etc/default/motd-news and set `ENABLED=0`


demo application for user requirement specification

Question: I have to create a user requirements specification for an application. I will need treeviews, menus, gridviews (with data). What is the quickest way to do this with little or no code and no database data. The application would need to react as almost if it was the final product. My initial thoughts is to programatically populate the treeview and gridview from xml files so i can change without any coding.
Does this make sense or what do other people do?
Comment: Well, i don't know the complexity of your GUI and how "precise" your mockup must be. But when we in our teams do mockups, methods range from quickly hacking something together with VisualStudio's designer (preferably .NET WPF or WinForms, even if the GUI should later be realized in C++/wxWidgets) to photoshopping several UI elements and building interactive demo in Powerpoint (we even had a mockup that was based on scanned hand-drawn sketches...) -- choose whatever methods suits _YOU_ best and allows you to get results quickly.
Answer:
The application would need to react as almost if it was the final
  product.

I think your first step is to set more realistic expectations and explain (possibly to the stakeholders?) the difference between a demo and a full product. If you are going to put in all the effort to make it that close to the final product, then it's probably not a demo. You might as well release it as a "beta" version.
Why not take a step back and create wireframes in a tool like Balsamiq and a simple functional spec in a Word document, Google docs or a Wiki? That can be created in a comparatively small amount of time and will give you a much better foundation to build the actual product or, at least, take a step further and create a demo with limited functionality.


Deleting non-unique rows from an array

Question: I have an array a as follows:
a = [ 1 2; 3 4; 1 2 ];

I want to delete all rows appearing more than once in a and get c:
c = [ 3 4 ];

Please note that this is not the same operation as keeping unique rows, since I don't want rows that had duplicates to appear at all. How can I accomplish this?
Comment: Possible duplicate of [Eliminate/Remove duplicates from array Matlab](https://stackoverflow.com/questions/40393513/eliminate-remove-duplicates-from-array-matlab)
Answer: The third output of unique gives you the index of the unique row in the original array. You can use this with accumarray to count the number of occurrences, which can be used to select rows that occur only once.
For example:
A = [1 2; 3 4; 1 2];

[uniquerow, ~, rowidx] = unique(A, 'rows');
noccurrences = accumarray(rowidx, 1);

C = uniquerow(noccurrences==1, :);

Which returns:
>> C

C =

     3     4

Deleting non-unique rows from an array


write java file to C drive access error

Question: Hi how can I get rid of C drive access with java codes I can do this with manual but I want to do this with java codes
here is my code
File file=new File("C:\\Windows\\b.txt");
    if (!file.exists()) {
        try {

            file.createNewFile();
        } catch (IOException e) {
            System.out.println("file not created and");
            e.getMessage();
            e.printStackTrace();
        }

And my exceptions
java.io.IOException: Access is denied
at java.io.WinNTFileSystem.createFileExclusively(Native Method)
at java.io.File.createNewFile(File.java:1006)
at tekrar.Write.main(Write.java:26)`

Comment: Why do you want to write to `C:\Windows`?
Comment: This is expected behavior.  If Windows just let any old program write to `C:\Windows`, then it would be even more prone to malware than it already is.
Answer: you need to run the program as an administrator to edit the C:\Windows folder. this is a system folder that you should not access.
Answer: You cannot write anything in the system folder without administrator privileges in windows. As I understand you cannot request administrator access from within a Java program and you'll have to RUN the application in admin mode.
See this question for some tips: Run Java file as Administrator with full privileges
P.S. Do you really need to write into the windows folder?

write java file to C drive access error


Why there is a need for specifier-qualifier list?

Question: I compiled this (gcc compiler):
<code>#include <stdio.h>

main() {

    struct {
        a:1;
        b:2;
    } t;

    t.b=6;
    t.a=2;
    printf("%d %d",t.a,t.b);
}
</code>
Error shown was:
expected specifier-qualifier list before 'a'
Why it is needed when unnamed data variables are taken as int by default. Please explain...
Comment: "unnamed data variables are taken as int by default": looks like you have a very old version of C in mind. If you compile your program with `-Wall` you should also receive a warning for the "unconventional" declaration of `main`.
Comment: More comments on your code: `main()` should be `int main(void)`; bit fields should usually be declared as `unsigned`; the values you're assigning to `t.b` and `t.a` are outside the range of values they can necessarily hold.
Answer: This is required by the C language standard. According to section 220.127.116.11 part 4:

A bit-field shall have a type that is a qualified or unqualified version of _Bool, signed int, unsigned int, or some other implementation-defined type.


NAudio looking for a way to read from a Stream when changing pitch instead of a File

Question: I am using the Naudio lib in my project and I've used it already to combine MP3 files and use them.
I combined them using Mp3FileReader(Stream), so it is possible to read from a stream with this object but when I try to change the audio pitch and follow their tutorial this is how it goes:
<code>    using (var reader = new MediaFoundationReader(inPath)) //only reads from file
{
    var pitch = new SmbPitchShiftingSampleProvider(reader.ToSampleProvider());
    using(var device = new WaveOutEvent())
    {
        pitch.PitchFactor = (float)upOneTone; // or downOneTone
        // just playing the first 10 seconds of the file
        device.Init(pitch.Take(TimeSpan.FromSeconds(10)));
        device.Play();
        while(device.PlaybackState == PlaybackState.Playing)
        {
            Thread.Sleep(500);
        }
    }
}
</code>
now my problem is that MediaFoundationReader only reads from file, is there another way to load from a stream and change the pitch/ frequency.
any help will be appreciated.
Answer: I hope this code will help you:
This function receive a Stream instead a file path.
<code>using System;
using System.IO;
using System.Threading;
using NAudio.Wave;
using NAudio.Wave.SampleProviders;
namespace Test
{
    public class HelpOnStackOverFlow
    {
        public static void PlayShift(Stream stream)
        {
            var fr = new Mp3FileReader(stream);

            fr.ToSampleProvider();
            var pitch = new SmbPitchShiftingSampleProvider(fr.ToSampleProvider());

            var rates = new float[] { 1.0594630943593f, 1.12246204830937f, 1.18920711500272f, 1.25992104989487f };

            foreach (var rate in rates)
            {

                var device = new WaveOutEvent();
                pitch.PitchFactor = rate;
                device.Init(pitch.Take(TimeSpan.FromSeconds(1)));
                device.Play();
                Thread.Sleep(1000);
            }
        }
    }
}
</code>
Comment: While this might answer the question, if possible you should [edit] your answer to include a short explanation of *how* this code block answers the question. This helps to provide context and makes your answer much more useful for future readers.


Condenser fan quits on a Goodman heat/air unit

Question: I have an older Goodman heat and air outside unit. I can run the heat on it for awhile, sometimes 30 minutes sometimes 40 minutes and sometimes longer, but then the condenser fan just stops but the rest of the unit keeps running.
If I pull the main breaker outside by the unit and shut everything down, and then put the breaker right back in, it starts right up, fan and all, and runs fine for awhile, but it then does the same thing. I can also let it just sit for awhile without pulling the breaker and the fan will eventually kick back on and run fine, and does this cycle over and over the same way.
Any ideas what the problem might be?
Comment: Hello, and welcome to Stack Exchange. I've edited your question so it's easier to read; you can re-edit it to add more details if you like.\
Comment: A "Goodman" unit was previously sold under the Amana-Raytheon brand. You may have better luck searching for Amana Inc. Pre 1970's, Post 1970's Amana - a Raytheon Company, Post 1990's Amana - a Maytag company, 2000's Amana - Whirlpool ..... in HVAC "Amana® is a registered trademark of Maytag Corporation or its related companies and is used under license. All rights reserved." a Goodman Inc. Company - Now. Goodman seem's to have a good set of pdf's if you know your model. Good Luck. (I know Amana Inc, history, lived in Amana, Iowa 25 years.)
Comment: Has the fan been serviced? At that age the bearings may be dry and causing the motor to overheat. There are also start/run capacitors that could be failing, I usually check fan speeds with a tachometer to verify the motor is getting to speed, at more than a few minutes run time I would be looking at the run capacitor and the bearings.
Comment: Thanks for your answer and No the fan has never been serviced but the motor is cool to the touch when it happens I talked to a tech yesterday and he said it sounds like a defrost mode on the unit did they have defrosts on these it's probably 15 or more years old ?
Answer: I concur with Ed.  The condenser fan motor itself is suspect.  Those motors operate under severe weather conditions resulting in a very reasonable life expectancy. Those bearing are factory sealed; nonservicable.   SOP replace the motor.


wait() for the process child crash

Question: I have the following program
int external_apply(char *type)
{
    int pfds[2];
    if (pipe(pfds) < 0)
        return -1;

    if ((pid = fork()) == -1)
        goto error;

    if (pid == 0) {
        /* child */

        const char *argv[8];
        int i = 0;
        argv[i++] = "/bin/sh";
        argv[i++] = "script_file.sh";
        argv[i++] = "apply";

        close(pfds[0]);
        dup2(pfds[1], 1);
        close(pfds[1]);

        execvp(argv[0], (char **) argv);
        exit(ESRCH);

    } else if (pid < 0)
        goto error;

    /* parent */
    close(pfds[1]);

    int status;
    while (wait(&status) != pid) {
        printf("waiting for child to exit");
    }

    return 0;

error:
    close(pfds[0]);
    return -1;
}

The fork call my script file. The script file contains command that cause a pipe close (sometimes). If the pipe is closed by the scipt the wait will cause a crash of the program.
How to avoid the crash of the program when the pipe is closed by the script?
Comment: What do you mean by "it crashes"? Wait doesn't care for the pipes, it ponly waits for the child status to change.
Comment: crash. I mean the program close without displaying any message. event the dmesg does not contain any segmentation fault
Comment: What is the rest of the code doing? See my updated on my answer. To me it looks ok, so maybe your problem is somewhere else.
Answer: on the error replace return -1 with _exit(-1).
Answer: You are probably receiving a SIGPIPE signal and not handling, causing an exception instead.
Try
signal(SIGPIPE, SIG_IGN);

and see this question/answers for details (or google SIGPIPE).
Answer: Your code leaks filedescriptors in error cases. It also closes uninitialized filedescriptors in case of errors.
But the loop you are showing will only be entered when wait returns with a different pid (in case you have more childs running) or it was interrupted (in which case it returns -1). So to me this looks exactly as it should work. When the child is finished, the loop will never be entered.
If you think the program crashes, you should show the code calling this function.

wait() for the process child crash


Make a program automatically take higher priority?

Question: I'm using my Ubuntu OS to play Minecraft. I can get the game to run a little faster by closing my other programs and giving the Minecraft java process a higher priority via the System Monitor. The process is simply named "java" in the list.

How can I make Minecraft automatically take a higher priority when it starts?
Comment: How do you start minecraft?
Comment: Trae7: If the answer below helped you, don't forget to click the grey **☑** at the left of its text, which means [Yes, this answer is valid](http://askubuntu.com/help/accepted-answer)!  **;-)**
Answer: TL;DR You need nice for this:
sudo nice -n -20 <your_command>

Start minecraft with this command:
sudo nice -n -20 su -c java -jar minecraft.jar $USER

If you have a desktop file for minecraft then change the property Exec and install the package gksu, we need gksudo:
sudo apt-get install gksu

Example (Replace <your_username> with your username, the output of echo $USER. $USER doesn't works in a desktop file):
[Desktop Entry]
Type=Application
Name=Minecraft
GenericName=Game
Comment=Break and place blocks to build imaginative things
Exec=gksudo "nice -n -20 su -c 'java -jar /usr/share/minecraft/minecraft.jar' <your_username>"
Icon=minecraft
Categories=Game
StartupNotify=true
StartupWMClass=net-minecraft-bootstrap-Bootstrap

The Linux niceness scale goes from -20 to 19. The lower the number the
  more priority that task gets. If the niceness value is high number
  like 19 the task will be set to the lowest priority and the CPU will
  process it whenever it gets a chance. The default nice value is zero.

Source
from man nice:
-n, --adjustment=N
              add integer N to the niceness (default 10)


XSLT: removing elements with duplicate attribute values

Question: I have xml and I want to remove elements (Elephant) that have duplicate child element (Cost) attribute values (dollars and cents are equal with sibling elements) and leave only one (Elephant) element.
Source xml (it's just a snippet of full document):
<?xml version="1.0" encoding="UTF-8"?>
   <Day>
         <Queue id="460402">
            <Time>4</Time>
            <Elephant>
               <Cost dollars="14" cents="5" />
            </Elephant>
            <Elephant>
               <Cost dollars="14" cents="1" />
            </Elephant>
            <Elephant>
               <Cost dollars="14" cents="6" />
            </Elephant>
            <Elephant>
               <Cost dollars="14" cents="1" />
            </Elephant>
            <Elephant>
               <Cost dollars="1" cents="46" />
            </Elephant>
            <Elephant>
               <Cost dollars="55" cents="5" />
            </Elephant>
         </Queue>
         <Queue id="460404">
            <Time>3</Time>
            <Elephant>
               <Cost dollars="7" cents="1" />
            </Elephant>
            <Elephant>
               <Cost dollars="7" cents="1" />
            </Elephant>
            <Elephant>
               <Cost dollars="7" cents="2" />
            </Elephant>
            <Elephant>
               <Cost dollars="7" cents="2" />
            </Elephant>
            <Elephant>
               <Cost dollars="114" cents="5" />
            </Elephant>
         </Queue>
         <Queue id="4666047">
            <Time>7</Time>
            <Elephant>
               <Cost dollars="14" cents="1" />
            </Elephant>
         </Queue>
   </Day>

Expected outcome:
<?xml version="1.0" encoding="UTF-8"?>
   <Day>
         <Queue id="460402">
            <Time>4</Time>
            <Elephant>
               <Cost dollars="14" cents="5" />
            </Elephant>
            <Elephant>
               <Cost dollars="14" cents="1" />
            </Elephant>
            <Elephant>
               <Cost dollars="14" cents="6" />
            </Elephant>
            <Elephant>
               <Cost dollars="1" cents="46" />
            </Elephant>
            <Elephant>
               <Cost dollars="55" cents="5" />
            </Elephant>
         </Queue>
         <Queue id="460404">
            <Time>3</Time>
            <Elephant>
               <Cost dollars="7" cents="1" />
            </Elephant>
            <Elephant>
               <Cost dollars="7" cents="2" />
            </Elephant>
            <Elephant>
               <Cost dollars="114" cents="5" />
            </Elephant>
         </Queue>
         <Queue id="4666047">
            <Time>7</Time>
            <Elephant>
               <Cost dollars="14" cents="1" />
            </Elephant>
         </Queue>
   </Day>

I tried to run this xslt transformation but it is not working properly (more data are missing than it should be):
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
    <xsl:strip-space elements="*"/>
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()" />
        </xsl:copy>
    </xsl:template>
    <xsl:template match="Elephant[Cost/@dollars= following-sibling:: Elephant/Cost/@dollars and Cost/@cents= following-sibling:: Elephant/Cost/@cents]"/>
</xsl:stylesheet>

Comment: In XSLT 2.0 you can use the `xsl:for-each-group` instruction for this.
Answer: Found the solution:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    exclude-result-prefixes="#all"
    version="2.0">

    <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
    <xsl:strip-space elements="*"/>

    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()" />
        </xsl:copy>
    </xsl:template>

  <xsl:template match="Queue">
      <xsl:copy>
          <xsl:apply-templates select="*[not(self::Elephant)]|@*"/>
          <xsl:for-each-group select="Elephant" group-by="Cost/(@dollars + 0.01 * @cents)">
              <xsl:apply-templates select="."/>
          </xsl:for-each-group>
      </xsl:copy>
  </xsl:template>
</xsl:stylesheet>


Images lagging when i scroll how to fix that?

Question: I have created an app with android studio in tab1 Relative Layout I have 8 images but when I run my app and scroll it lags how to fix lagging when I scroll.
Here is the code
package com.example.drh3cker.ihebski_swip;

import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.PagerTabStrip;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

//this project developped by iheb ben salem@IBSSoft
public class MainActivity extends FragmentActivity {

ViewPager pager;
PagerTabStrip tab_strp;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_tab);
    ma_pager_adapter mapager=new ma_pager_adapter(getSupportFragmentManager());
    pager=(ViewPager)findViewById(R.id.pager);

    pager.setAdapter(mapager);
    tab_strp=(PagerTabStrip)findViewById(R.id.tab_strip);
    tab_strp.setTextColor(Color.WHITE);
 //   tab_strp.setTextSize(14,14);
   // tab_strp.setTabIndicatorColor(Color.WHITE);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.share) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

public void browser1(View view) {
    Intent browserIntent=new Intent(Intent.ACTION_VIEW, Uri.parse("http://example.com"));
    startActivity(browserIntent);

and
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:weightSum="1">

<ScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:fillViewport="true">

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

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:id="@+id/imageView"
        android:src="@drawable/fra"
        android:background="#f44437"
        android:contentDescription="@string/App_Title_Image" />

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="150dp"
        android:id="@+id/imageView2"
        android:src="@drawable/saavnmusicapp"
        android:paddingTop="8sp"
        android:onClick="browser1"
        android:contentDescription="@string/saavn_music_app"
        android:scaleType="fitCenter"
        android:layout_below="@+id/imageView"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        style="?android:borderlessButtonStyle"/>

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="150dp"
        android:id="@+id/imageView3"
        android:src="@drawable/earntalktime"
        android:layout_below="@+id/imageView2"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:contentDescription="@string/earn_talktime_image"
        android:onClick="browser2"
        style="?android:borderlessButtonStyle"/>

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="150dp"
        android:id="@+id/imageView4"
        android:src="@drawable/flipkart"
        android:onClick="browser3"
        android:contentDescription="@string/flipkart_app_image"
        android:layout_below="@+id/imageView3"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        style="?android:borderlessButtonStyle"/>

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="150dp"
        android:id="@+id/imageView5"
        android:layout_below="@+id/imageView4"
        android:layout_centerHorizontal="true"
        android:src="@drawable/paytmapp"
        android:contentDescription="@string/paytm_app_image"
        android:onClick="browser4"
        style="?android:borderlessButtonStyle"/>

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="150dp"
        android:id="@+id/imageView6"
        android:layout_below="@+id/imageView5"
        android:layout_centerHorizontal="true"
        android:src="@drawable/uc"
        android:onClick="browser5"
        style="?android:borderlessButtonStyle"
        android:contentDescription="@string/uc_browser_image" />

    <ImageView
         android:layout_width="match_parent"
         android:layout_height="150dp"
         android:id="@+id/imageView7"
         android:layout_below="@+id/imageView6"
         android:layout_centerHorizontal="true"
         android:src="@drawable/dailyhunt"
         android:onClick="browser6"
         style="?android:borderlessButtonStyle"
         android:contentDescription="@string/uc_browser_image" />

    <ImageView
         android:layout_width="match_parent"
         android:layout_height="150dp"
         android:id="@+id/imageView8"
         android:layout_below="@+id/imageView7"
         android:layout_centerHorizontal="true"
         android:src="@drawable/freepaisa"
         android:onClick="browser7"
         style="?android:borderlessButtonStyle"
         android:contentDescription="@string/uc_browser_image" />

    <ImageView
         android:layout_width="match_parent"
         android:layout_height="150dp"
         android:id="@+id/imageView9"
         android:layout_below="@+id/imageView8"
         android:layout_centerHorizontal="true"
         android:src="@drawable/mobikwik"
         android:onClick="browser8"
         style="?android:borderlessButtonStyle"
         android:contentDescription="@string/uc_browser_image" />

</RelativeLayout>
</ScrollView>

Stackoverflow is telling me to add more details I don't know why I have added the problem and the code and I want to know how can I fix that can anyone help me
Thanks.
Comment: @hasan83 sorry, my bad, i thought the OP had used a listview
Comment: @SarthakMittal he says that the scroller lags. the images gets loaded before he start scrolling. I don't think the problem is in images memory size. caching libraries won't solve the problem.
Answer: When loading an image in an ImageView use

imageview.setImageBitmap(BitmapFactory.decodeResource(getContext().getResources(), R.drawable.image);

than

imageview.setImageResource(R.drawable.image);

For my experience, it has lessen the Java and Graphics' memory consumption by up to 89% which makes the application run smoother and use less memory and by this, do less garbage collection as your application runs.
Next, set a constraint on the file sizes of your images to ensure highest performance possible

From:      image.jpg    |    1.2MB
To:          image.jpg    |    512KB

When the file is already in your resources folder, you can, in Mac, "reveal in Finder" or in Windows, "Open in Explorer", to show your files then you can...

Resize the image in Preview for Mac
Resize the image size or resize the file size of the image in Windows using Microsoft Office Picture Manager (still helps even nowadays)

Lastly, maybe you can find this article helpful for your problem

https://medium.freecodecamp.org/how-we-reduced-memory-footprint-by-50-in-our-android-app-49efa5c93ad8
Answer: A better option would be to use a Listview or even better a RecyclerView in place of many images in a ScrollView, because they recycle items that are not seen, and in that way giving performance boost. + Picasso (image processing and caching). https://github.com/square/picasso
Here is a example for implementation: https://futurestud.io/blog/picasso-adapter-use-for-listview-gridview-etc/
Code samples from Picasso GitHub:
https://github.com/square/picasso/tree/master/picasso-sample/src/main/java/com/example/picasso
But there are many good resources for implementation, just google - android ListView or Recycler view implementation.
If you still want to use ScrollView you could replace the RelativeLayout with a Linearlayout, that could give a small performance boost, because RelativeLayout is measured 2 times.
Comment: he says that the scroller lags. the images gets loaded before he start scrolling. I don't think the problem is in images memory size is the only problem here. caching libraries won't solve the problem alone. but the caching library with a recycler view may solve the problem.
Comment: +one for covering all possible well none suggestions


ArrayList<>, adding Objects on creation of another Object

Question: I'm trying to add a series of one Object to another Object in an ArrayList.
In this case, I have "Task", which is a series of Object type "SubTask". Whenever the user presses a specific button, it should add another SubTask to the Task. I have a few issues with doing this in the constructor, and generally transferring the ArrayList of SubTask to Task. The calculations of min time and max time I can probably figure out myself.
 public class Task {
    //our Task has a name, a number of SubTasks, cues and two calculated times (min and max)
    public String TaskName;
    public int calculatedMaxTime; public int calculatedMinTime; public int subtasks;
    public boolean cueEt; public boolean cueTo;

    //it has an ArrayList of SubTasks
    ArrayList<SubTask> myList = new ArrayList<SubTask>();

    //lets make a task
    public Task(String setName, int calcTimeMin,int calcTimeMax,
                  int calcSubs, boolean setCueOne, boolean setCueTwo) {

        //calcTimeMin = myList.
        //calcTimeMax =
        //we need to add subtasks in the constructor somehow
        //we need these subtasks to be specific to the task

        TaskName = setName;
        //set the Task's variables
        calculatedMaxTime = calcTimeMax; calculatedMinTime = calcTimeMin; subtasks = calcSubs;
        cueEt = setCueOne; cueTo = setCueTwo;
    }

}

public class SubTask {
    //vores underopgavbe har et navn, en minimum og en max tid
    String Name;
    int minTime; int maxTime;

    public SubTask(String setSubName, int setMinTime, int setMaxTime) {
        Name = setSubName;
        minTime = setMinTime; maxTime = setMaxTime;
    }
}

Please forgive the Danish words here and there, I haven't cleaned my code yet.
EDIT (question if you can't see it): How do I add (user-defined) SubTasks to the Task users are creating? Do I use the constructor or define a method for it?
Comment: There is no question here.
Comment: Where do you get the list of `SubTask`:s in the constructor? It seems like you want to populate `myList` with nothing to populate it with. Perhaps give a list of `SubTask`:s as an argument to the constructor?
Comment: You mean something like `myList.add(new SubTask(subname,minTime,maxTime));` ?
Comment: I guess your class `Task` is missing a method like `addSubTask()`?!
Answer: There are a few ways to pass the subtasks into the task array. The most obvious is to add an addSubTask(Subtask) method to the Task class, and then invoke that in whatever code creates the task.
In main code
Task task = new Task(args...); //put real args in actual code
//do stuff

public void onButtonPress(){
    SubTask subtask = new SubTask(args...); //put real args in actual code
    task.addSubTask(subtask);
}

In Task
public class Task{

    //already existing code

    public void addSubTask(SubTask subtask){
        myList.add(subtask);
    }

}

Alternatively you could add an ArrayList<SubTask> object to the Task constructor's arguments, which would let you pass in a whole bunch of sub-tasks at once - albeit without the ability to add new ones once the Task is constructed. This might be combined with the prior solution to allow you to add SubTasks after the object's creation is over.
Answer: You may try this way:
 ArrayList<Task> taskList = new ArrayList<Task>();

 Task task = new Task(...);
 SubTask subtask1 = new SubTask(...);
 task.myList.add(subtask1);
 SubTask subtask2 = new SubTask(...);
 task.myList.add(subtask2);
 SubTask subtask3 = new SubTask(...);
 task.myList.add(subtask3);
        ...
        ...

 taskList.add(task);


Flutter: How to control a PageView by GetxController?

Question: Subject: PageView and GetX
I'm having trouble detaching the controls on a PageView widget from the HomeView module. I have a GlobalController with its respective GlobalBinding that are instantiated when opening the HomeView. I would like to take the setPage(int page) method to the GlobalController that would eventually make the HomeView's PageView change pages. I don't know how to get PageController from PageView to GlobalController in order to make it work. How should I proceed?
Answer: Something Like this?
am using pageview in onboarding
class Onboard{

 final headTitle;
  final secondarytitle;
  final discription;
  final pngimage;
 Onboardslist(this.headTitle, this.secondarytitle, this.discription, this.pngimage);

}

then for the controller
class OnboardController extends GetxController{

  var selectedPagexNumber = 0.obs;
bool get isLastPage => selectedPagexNumber.value == onBoardPages.length -1;
var pageControll = PageController();

   forwardAct()
  {
    if(isLastPage) Get.offNamedUntil(signin, (route)=> false);

    else pageControll.nextPage(duration: 300.milliseconds, curve: Curves.ease);
  }

  List<Onboardslist> onBoardPages =
  [
    Onboardslist("title",
    "short description",
    "long description",
    imageString),
     Onboardslist("title",
    "short description",
    "long description",
    imageString),
    Onboardslist("title",
    "short description",
    "long description",
    imageString),
    Onboardslist("title",
    "short description",
    "long description",
    imageString)
  ];

}

then for the view i did was simply like this
class Onboarding extends StatelessWidget {

   final yourController= OnboardController();

  @override
  Widget build(BuildContext context) {
    SizeXGet().init(context);
     return Scaffold(
       backgroundColor: decent_white,
       appBar: AppBarCustom(
        title: 'Skip',
        button: ()=>Get.offNamedUntil(signin,(route)=>false),
      ),
      body: WillPopScope(
        onWillPop: () async => false,
          child: SafeArea(
            child: Stack(
              children: [
                PageView.builder(
                  controller: yourController.pageControll,
                  onPageChanged: yourController.selectedPagexNumber,
                  itemCount: yourController.onBoardPages.length,
                  itemBuilder: (context, index)
                  =>Padding(
                    padding: const EdgeInsets.only(left: 10,right: 10),
                    child: Container(
                      child:  SingleChildScrollView(
                          physics: BouncingScrollPhysics(),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.center,
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                            Container(
                              height: getHeight(150),
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.center,
                            mainAxisAlignment: MainAxisAlignment.center,
                                  children: [
                                     Padding(
                       padding: const EdgeInsets.only(left: 20,right: 20),
                       child: Text(yourController.onBoardPages[index].headTitle,
                       style: TextStyle(
                       color: darkish_color,
                        fontSize: getHeight(20),
                       fontFamily: 'Metropolis-SemiBold' ,
                       fontWeight: FontWeight.bold
                       ),),
                     ),
                     SizedBox(height: 15,),
                     Padding(
                     padding: const EdgeInsets.only(left: 50,right: 50),
                     child: Text(yourController.onBoardPages[index].secondarytitle,
                     style: TextStyle(
                                  color: not_sopure_black,
                                  fontSize: getHeight(26),
                                  fontFamily: 'Metropolis-Bold' ,
                                  fontWeight: FontWeight.bold
                                ),
                                ),
                              ),
                              SizedBox(height: 15,),
                              Padding(
                               padding: const EdgeInsets.only(left: 40,right: 40),
                                child: Text(yourController.onBoardPages[index].discription,
                                style: TextStyle(
                                  color: not_sopure_black,
                                  fontSize: getHeight(15),
                                  fontFamily: 'Metropolis-Regular' ,
                                ),
                                ),
                              ),
                                  ],
                                ),
                              ),
                              SizedBox(height: 15,),

                              Image.asset(yourController.onBoardPages[index].pngimage),

                            ],
                          ),
                        ),
                    ),
                  ),
                ),

              ],
            ),

        ),

      ),
      bottomNavigationBar: BottomAppBar(
        color: Colors.transparent,
        elevation: 0,
        child: Container(
          height: 75,
          width: MediaQuery.of(context).size.width,
          child:  Padding(
        padding: const EdgeInsets.only(left: 25,right:25,),
        child: Container(
          width: MediaQuery.of(context).size.width,
          child: Stack(
            children: [
                  Align(
                    alignment: Alignment.centerLeft,
                    child: Container(
                      child: Row(
                        children: List.generate(yourController.onBoardPages.length,
                        (index)=>Obx(()=>
                        AnimatedContainer(
                          duration: Duration(milliseconds: 200),
                          margin: EdgeInsets.only(right: 5),
                          height: 10,
                          width: yourController.selectedPagexNumber.value == index ? 20 : 10,
                              decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(60),
                              color: yourController.selectedPagexNumber.value == index
                              ? darkish_color
                              : not_sopure_black,),
                        ),
                        )),
                      ),
                    ),
                  ),

                Align(
                  alignment: Alignment.centerRight,
                  child: Container(
                    width: 130,
                    height: 52,
                    child: RaisedButton(
                      elevation: 0,
                      onPressed: yourController.forwardAct,
                      splashColor: not_sopure_black,
                      color: darkish_color,
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(100)
                      ),
                      child: Obx(() =>
                      Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Text(yourController.isLastPage ? 'Next' : 'Next',
                          style: TextStyle(
                            color: Colors.white,
                            fontFamily: 'Metropolis-Semibold',
                            fontSize: 16,
                          ),
                          ),
                        ],
                      ),
                      ),
                    ),
                  ),
                )
            ],
          ),
        ),
    ),
        ),
      ),
    );
  }
}


Extract two elements of list and pass the rest recursively

Question: I have a type def with 2 types and a list of the same type that may or may not be empty.
type Type1 = string
type Type2 = int
type Type3 = Sometype of Type1 * Type2 * Type3 list

I am trying to create a list of all the first two elements in the tuple, recursively passing along the last (a list of other type 3's), appending it to the list that I'm producing. Or at least that's what I'm trying. My function gives me an error:
let rec extSometypeInc d   =
   match d with
    | Sometype(n,i,[])         -> [(n,i)]
    | Sometype(n,i,r1::r2::rt) -> (n,i) :: extSometypeInc(r1,r2,rt)
    ;;

error FS0001: This expression was expected to have type
      Type3
  but here has type
      'a * 'b * 'c
Comment: please provide a clear, complete example on your problem - here we don't know anything about `Type1`, `Type2` and `extSometypeInc`... also the line where you get the error might help
Answer: I'm not fully sure of your end goal here, but in terms of the unexpected result type you seem to have a syntax error.
| Sometype(n,i,r1::r2::rt) -> (n,i) :: extSometypeInc(r1,r2,rt)

Will pass a single tuple of three values to extSometypeInc as its first argument.
I believe you want:
| Sometype(n,i,r1::r2::rt) -> (n,i) :: (extSometypeInc r1 r2 rt)

which will pass it three arguments.
However, at this point you will find that the compiler will insist that Type1, Type2 and Type3 are all the same type, as lists in F# are constrained to hold values of a single type. You will also get a warning of an incomplete pattern match, as your function does not accommodate lists with an odd number of values.
Without knowing more about the problem you are attempting to serve, I'm not sure what the best solution to those problems would be.
Comment: Edited with clarifying descriptions.
Comment: Looking at your clarification, I'm not sure Type3 is representing what you were expecting. Can I suggest you give some example input and output to help us understand the problem?


Can't install Ubuntu 12.04 over Windows. Youtube video showing problem

Question: The installation walk-through on Ubuntu website shows several windows giving the user options/preferences in the installation.(http://www.ubuntu.com/download/desktop/install-desktop-long-term-support) I never saw the option to install over windows which is what i'd like to do.
Here's a link to the YouTube video: http://www.youtube.com/watch?v=YpnUrnLR4vI
I'm using a Dell XPS 15 with Windows 7.
Answer: Perhaps that could be if its not able to detect your Windows.
Try to reboot the Live DVD and see if the option is available or not.
If its not, then-
If you want to replace Windows 7 by Ubuntu and dont have any data on the drive then you could use the option-
Erase everthing and install

Otherwise if you have a data partition, you will need to select the option
Something Else

for Custom Partitioning
if you choose custom partitioning-
Basic Partition Setup
Ubuntu basically needs just 2 partitions for installation:
    / partition (System), Mount Point '/', which holds all the base install. File system ext3/ext4, (ext4 is the default since 10.04 Lucid Lynx) and recommended minimum size is 8 GB.
Make it 30gb-50gb
Swap partition (Virtual RAM), mount point 'Swap'. If you intend to hibernate/suspend your Ubuntu install, size should be 2 X RAM or at least equal to RAM. If you've got large amounts of RAM say 2GB or more and don't want to hibernate/suspend, you can survive without a Swap partition but that is not recommended in most cases.
Make it 2gb- 4gb
Thats it.
If you have any queries please let us know.


Email file attachments using MIME in PHP

Question: I'm trying to use PHP to send an email with an attached file.
I've followed the excellent tutorial at http://webcheatsheet.com/PHP/send_email_text_html_attachment.php#attachment and made the following changes:
<code>--PHP-mixed-<?php echo $random_hash; ?>
Content-Type: application/txt; name="<?php echo $_POST[log_file]?>"
Content-Transfer-Encoding: base64
Content-Disposition: attachment
</code>
Neither the original script or my amended script seems to attach any files to my emails.
Anyone have any idea what I'm doing wrong.
Note: the files I'm attaching to my form are all text files (various file extensions e.g. .log, .txt etc).

OK, I've now proven I think that the MIME encoding part of this script isnt working.
I've placed a text file in my upload directory and changed the script to read:
<code>--PHP-mixed-<?php echo $random_hash; ?>
Content-Type: text/plain; name="<?php echo $_SERVER['DOCUMENT_ROOT']. '/upload/test.txt' ?>"
Content-Transfer-Encoding: base64
Content-Disposition: attachment
</code>
When looking at the email source on receipt I see the full path and document name under Content-Type: text/plain; name=, but theres no attachment, encoded or otherwise.
Anyone know how I get this to work?
I've tried the following:
<code>--PHP-mixed-<?php echo $random_hash; ?>
Content-Type: text/plain; name="<?php echo $_FILES['file']['name']; ?>"
Content-Transfer-Encoding: base64
Content-Disposition: attachment
</code>
This presents the file name in the email source, but no attachment, interestingly:
<code>--PHP-mixed-<?php echo $random_hash; ?>
Content-Type: text/plain; name="<?php echo $_FILES['file']['temp_name']; ?>"
Content-Transfer-Encoding: base64
Content-Disposition: attachment
</code>
Returns an empty file name and still not attachement, I can only assume the temp file has bee deleted by the time I execute this?
Comment: see if this helps:
http://stackoverflow.com/questions/6275070/php-mail-attachment-problems
Comment: Is the use of: name="" valid or do I have to store the file somewhere in a temporary location and refer to that location for retrieval before sending?
Comment: it looks valid. you just need to make sure that there is valid value in there ($_POST['log_file'])
Comment: change  to
Comment: @ Maximus2012 Thanks for this, but it made no difference. Looking at the received email source I see the following:

--PHP-mixed-edc3b09aea5aa11614b07dadbf00098f
Content-Type: application/txt; name="TEST.txt"
Content-Transfer-Encoding: base64
Content-Disposition: attachment

It seems to be finding the file name from my form i.e. $_POST[log_file] but it's not attaching/encoding the file?
Comment: I think my form file input field Attach Log File:  isn't storing the file anywhere so the mail script cant find it so encode. Anyone know how I define a default location in PHP for the form to store the files?
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/34071/discussion-between-taffman-and-maximus2012)
Comment: did you try the working solutions from the other stackoverflow question? is your mail server configured properly ?
Comment: I've been looking at http://stackoverflow.com/questions/3945330/php-filestmp-name and others, but no real clue as to why I dont recieve an attachemnt yet?
Comment: are you getting any specific error message? anything in the server log maybe ? its also possible that there might be error in some other parts of your application.
Answer: OK finally got this working by moving the temp file to another location on my server, then encoding that file.
Not sure why I can't encode the temp file without saving it, but at least I got it working now.
Thanks to everyone who took the time to reply to this, you help me a lot.


OpenGL transparency - object behind is not rendered

Question: I'm trying to implement voxel world using OpenGL (Core 3.3). I've come across a problem with transparency. It looks like sometimes GPU decides to not render stuff that would be important. Can you help me diagnose the problem, please?
(I thought this problem can be related to sorting (I don't perform any extra sorting at the moment), but I've changed "clear color" to glClearColor(1.0f, 1.0f, 1.0f, 0.01f); and the "gaps" are still noticeable)
EDIT: I've found a resource that claims that it is indeed  sorting problem and drawing background triangles at first should solve this issue. However every 'chunk' (16x16 blocks' column) is rendered as a separate batch with single draw call. Is there a way to preserve this batch rendering?
Here are some pictures:

The Ftagment Shader is very simple:
#version 330 core
out vec4 FragColor;
in vec2 v_TexCoord;

uniform sampler2D u_Texture;

void main()
{
    vec4 texColor = texture(u_Texture, v_TexCoord);
    if(texColor.a < 0.2)
        discard;
    FragColor = texColor;
}

Depth test and blending:
void Renderer::clear() const {
    glClearColor(0.53f, 0.8f, 0.92f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}

//Before render loop

glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_DEPTH_TEST);

Do you have any idea how can I fix this problem?
Answer: It depends on the order of rendering. When first rendering the object which is far away and then rendering the closer object, the transparency will work. Otherwise when first rendering the close object, you depthbuffer will block the object which is behind.
There are different ways to manage this issue:
1:First render all opaque geometries. and then render the transparent.
This gives you NOT the correct output, because other transparent objects which are behind transparent objects will cause the same problem you described. But opaque objects will always be visible.
2:Use other rendertechniques like Order independent transparencies (OIT)
Here you create a list of fragments (pixels) for each pixel on your screen. The list of fragments must hold the depth and color value. when all geometry is rendered, you can iterate through each list and sort the fragments by the depth value and render them again from back to front. This will give you a very good final image.
This technique can be improved when first enable depth writing, depth testing and rendering the opaque objects.
Disable depth writing, enable depth testing. And then render the transparent ones. This will shrink your list size.
Comment: In case using OIT: you can store the list in a Shader Storage Buffer Object (SSBO) and use atomicAdd(), atomicCompSwap() and other atomic functions within GLSL (shader) to avoid writing to the same memory location from different GPU "Threads" .
Comment: I'll implement this and hopefully it'll solve the problem. (Unfortunately I do not have enough reputation to cast a vote for you). Thank you for your answers.
Comment: @PawełPomierski you are welcome =)
Comment: @PawełPomierski have in mind, that you can also render your blocks from back to front... if your datastructure (chunks) allow this
Answer: I can't actually spot the problem from your pictures, but the problem you describe is a very common one for new developers trying to implement transparency, so I'll assume it's there.
The problem:
Let's consider what happens to a single pixel. In boring old opaque rendering, we expect the pixel to have the frontmost triangle at that pixel (closest to the camera, lowest Z value). This can be done with a depth buffer: the GPU stores the Z coordinate of the frontmost triangle that touches the pixel so far, and overwrites the pixel when drawing a triangle in front of that, and doesn't overwrite it when drawing a triangle behind that. Therefore the final result has the colour from the frontmost triangle.
However this simple algorithm only works for fully opaque triangles. With a translucent triangle, instead of just overwriting the colour of the pixel, the GPU combines it with the colour already in the colour buffer. If some of the triangles are skipped because of the depth buffer algorithm, the final colour is wrong. The only case when it's right is when the triangles are drawn in back-to-front order. And if you use the typical alpha blending algorithm for translucency, then you can't just solve it by turning off the depth buffer, because the colour is calculated differently depending on which order the triangles are rendered in, and it's only correct when they are drawn in back-to-front order (when you get the correct result whether the depth buffer is on or off).
The solution:
If you only have fully opaque and fully transparent pixels, a really easy solution is to enable alpha test. Pixels with 0 alpha will be fully discarded and won't update the depth buffer. Pixels with 1.0 alpha will act as opaque.
glEnable(GL_ALPHA_TEST); // <- literally that simple

If you have partially translucent pixels, then you have two options: either actually render front-to-back or implement one of the schemes of order-independent transparency. All of these options have significant tradeoffs. Fortunately, you appear to have only fully transparent pixels, so it is not necessary to delve into either.


Meaning of the Symbol of single apostrophe(') in Scala using Anonymous function under withColumn function?

Question: My questions is:
In line number 5: What is the operation of the symbol of single apostrophes(')? Cannot understand very clearly that how withColumn function is working over here. Also Please elaborate how it is displaying like these Column order- |id         |text    |upper   |.
Code:
 1. val dataset = Seq((0, "hello"),(1, "world")).toDF("id","text")
 2. val upper: String => String =_.toUpperCase
 3. import org.apache.spark.sql.functions.udf
 4. val upperUDF = udf(upper)
 5. dataset.withColumn("upper", upperUDF('text)).show

Output:
+---------+---------+---------+
|id       |text     |upper    |
+---------+---------+---------+
| 0       | hello   |HELLO    |
| 1       | world   |WORLD    |
+---------+---------+---------+

Comment: `withColumn` creates a new column if the first argument passed to it doesn't already exist in a dataframe. If it does, it overwrites the existing column. `'text` is used to select the column named `text`. In place of `'text`, you can also use `$"text"` or `org.apache.spark.sql.functions.col(text)`. The order is like that because the first two columns are `id` and `text` and `withColumn` is _appending_ a column which will get added at the end. You need to go through the documentation first. You'll find lots of interesting things there.
Comment: @philantrovert Thanks a lot
Answer: The ' symbol in Scala is syntax sugar for creating an instance of the Symbol. class. From the documentation

For instance, the Scala term 'mysym will invoke the constructor of the Symbol class in the following way: Symbol("mysym").

So when you write 'text, the compiler expands it into new Symbol("text").
There is additional magic here, since Sparks upperUDF method requires a Column type, not a Symbol. But, there exists an implicit in scope defined in SQLImplicits called symbolToColumn which converts a symbol to a column:
implicit def symbolToColumn(s: Symbol): ColumnName = new ColumnName(s.name)

If we extract away all the implicits and syntax sugar, the equivalent would be:
dataset.withColumn("upper", upperUDF(new Column(new Symbol("text").name))).show

Comment: @BhaskarDas I was just adding information to the answer. See it now.
Comment: Can you please elaborate the line number 5. Please


Switch Statement with Array condition

Question: I am having an impossible time trying to make this work. It is just a sample run of the code without the full options.
What is needed from the program is for the user to enter there choice, 1-3 or a-c. I am using a string in case the user enters more than just a single character. The switch case then should compare just the first char in the array to the cases. And the do while loop is to make sure it keeps going until they enter the right characters.
#include <stdio.h>
#define SIZE 81

void main(){
    char thing[SIZE] = {3};
    int rvalue;
    do
    {
        scanf_s("%s", thing);
        switch (thing[0])
        {
        case 'a':
        case 1:
            printf("first\n");
            rvalue = 1;
            break;
        case 'b':
        case 2:
            printf("second\n");
            rvalue = 2;
            break;
        case 'c':
        case 3:
            printf("third\n");
            rvalue = 3;
            break;
        default:
            printf("Wrong\n");
            rvalue = 4;
            break;
        }
    } while (rvalue == 4);
}

Comment: Just change `scanf_s("%s", thing);` to `scanf_s("%s", thing, SIZE);`.
Comment: Always tell your compiler to show all warnings possible and take them for serious.
Comment: [`scanf_s()`](https://msdn.microsoft.com/en-us/library/w40768et.aspx) doesn't work like that. You must specicy the string size. Always check the return value, I/O can fail!
Answer: Change
scanf_s("%s", thing);

To
scanf_s("%s", thing,(unsigned int)sizeof(thing)); //Read the comments to know why the cast is required

This done because scanf and scanf_s are different function. scanf_s has an additional argument present to prevent buffer overflows.
Also change these
case 1:
case 2:
case 3:

To
case '1':
case '2':
case '3':

Because the character 1('1') and the rest of them are different from the integer 1. The characters(those enclosed in single quotes) have their values represented in the ASCII table.
Comment: The result of `sizeof` is of type `size_t`, but MS `scanf_s()` expects `unsigned int` (C11 expects `rsize_t`).
Comment: @cremno , Dosen't `size_t` have type `unsigned int`?
Comment: No, it can be any unsigned integer type. For example, your code is broken on Windows x64 where `sizeof(unsigned int)` is 4, but `sizeof(size_t)` is 8.
Comment: @cremno , I see. So, would casting the result of `sizeof` to `unsigned int` work?
Comment: Of course (I know it's ugly. I also don't know why the person behind `scanf_s()` decided to use `unsigned int`.)
Answer: As far as it seems, you want to print first when the first character in the thing string is a or 1, and so on.
The problem is that case 1: is not same as case '1':. 1 is an int, '1' is a char, and as you are comparing the first character of the string, you need to change your casestatements a bit.
Code:
#include <stdio.h>
#define SIZE 81

void main(){
    char thing[SIZE] = {3};
    int rvalue;
    do
    {
        scanf_s("%s", thing,SIZE);
        switch (thing[0])
        {
        case 'a':
        case '1':
            printf("first\n");
            rvalue = 1;
            break;
        case 'b':
        case '2':
            printf("second\n");
            rvalue = 2;
            break;
        case 'c':
        case '3':
            printf("third\n");
            rvalue = 3;
            break;
        default:
            printf("Wrong\n");
            rvalue = 4;
            break;
        }
    } while (rvalue == 4);
}

Switch Statement with Array condition


Is there something like Cardano's method for a SOLVABLE quintic.

Question: So there is no quadratic formula equivalent for a GENERAL fifth degree equation, but is there an equivalent formula for a SOLVABLE fifth degree equation.
Comment: Galois theory shows how in principle one can use a chain of subgroups establishing that the Galois group is solvable to construct a chain of intermediate fields, each obtained by extension by radicals, ending in a splitting field for your polynomial. The explicit details depend on that chain, and can be quite messy. In fact even the general formula for the quartic is _extremely_ messy if you write it out in full.
Answer: Yes, there is a general expression for solutions of solvable quintics. A published account, including the relevant formulas, appears in

David S. Dummit. Solving solvable quintics, Math. Comp., 57 (195), (1991), 387–401. MR1079014 (91j:12005). Corrigenda, Math. Comp., 59 (199), (1992), 309. MR1166516.

The corrigenda is actually a microfiche supplement containing an appendix to the paper, that was inadvertently not published with the paper itself. It contains some of the formulas needed for the explicit computation of the roots. To give you an idea of the complexity of the task, the appendix runs for $43$ pages.
From the paper:

It is well known that an irreducible quintic with coefficients in the rational numbers $\mathbb Q$ is solvable by radicals if and only if its Galois group is contained in the Frobenius group $F_{20}$ of order $20$, i.e., if and only if the Galois group is isomorphic to $F_{20}$ , to the dihedral group $D_{10}$ of order $10$, or to the cyclic
  group $\mathbb Z/5\mathbb Z$.

Explicitly associated to an irreducible quintic $f$ there is a resolvent sextic that Dummit calls $f_{20}$, and $f$ is solvable by radicals iff $f_{20}$ has a rational root, in which case $f_{20}$ factors as a linear term times an irreducible quintic. When this happens, explicit criteria are given for which of the three possibilities above actually occurs, together with the relevant formulas. The paper includes examples showing all three cases are possible.
Answer: Marc is correct, the Galois group for a solvable irreducible quintic can only have order $5,10$ or $20,$ since these are the only orders of solvable subgroups of $S_5$ which have order divisible by $5,$ so in some ways the possible structures for the Galois group of a solvable quintic are less messy than the structure of the symmetric group $S_4.$ Following the arguments in Galois Theory texts for the relevant Galois groups should be feasible( and is probably already done explicitly somewhere). It might help to note that such an irreducible quintic has either $1$ or $5$ real roots.
Comment: If OP's earlier questions are anything to go by, OP is not just (perhaps not at all) interested in irreducible quintics, but in reducible ones, even (perhaps especially) quintics that split completely over the rationals. The possible structures for the Galois group of a solvable and not-necessarily-irreducible quintic include all those messy subgroups of $S_4$, as well as $S_3$, $S_2$, and $S_1$. I think there are over a dozen different kinds of solvable quintic if you include the reducible ones, which means OP needs a lot of formulas, not just one.
Comment: @Gerry Myerson : Yes, if you allow reducible quintics, then it's  different matter, but you can of course (in principle) solve the irreducible factors by radicals using the formula for quadratics,cubic and quartics, you don't need any "new" Galois theory. So the irreducible quintic is the only case not covered by the "standard" theory.
Answer: For any solvable polynomial equation $a_px^p+a_{p-1}x^{p-1}+\cdots+a_1x+a_0=0$ of odd prime degree $p$, the roots have the form:
$x=-\frac{a_{p-1}}{pa_p}+\omega\sqrt[p]{r_1}+\omega^2\sqrt[p]{r_2}+\cdots+\omega^{p-1}\sqrt[p]{r_{p-1}}$
Where $r_1,\cdots,r_{p-1}$ are solutions to a polynomial of degree $p-1$ with coefficients in the same base field as the original equation.
A to determine which polynomial, one method is to set each of these expressions equal to a different root and deriving elementary symmetric polynomials in the $r_i$, and solving a linear system.
Example: $x^5-5x+12$ with one real root and Galois Group $D_5$.
We know that the roots are
$x_1=a+b+c+d$
$x_2=a\text{ cis }\frac{2\pi}{5}+b\text{ cis }\frac{4\pi}{5}+c\text{ cis }\frac{6\pi}{5}+d\text{ cis }\frac{8\pi}{5}$
$x_3=a\text{ cis }\frac{4\pi}{5}+b\text{ cis }\frac{8\pi}{5}+c\text{ cis }\frac{2\pi}{5}+d\text{ cis }\frac{6\pi}{5}$
$x_4=a\text{ cis }\frac{6\pi}{5}+b\text{ cis }\frac{2\pi}{5}+c\text{ cis }\frac{8\pi}{5}+d\text{ cis }\frac{4\pi}{5}$
$x_5=a\text{ cis }\frac{8\pi}{5}+b\text{ cis }\frac{6\pi}{5}+c\text{ cis }\frac{4\pi}{5}+d\text{ cis }\frac{2\pi}{5}$
Here, $a,b,c,d$ are fifth-roots of solutions to a quartic.
If you ask Mathematica to solve the quintic in closed form, it will give you root objects. The first one is real, the next two are one complex conjugate pair, and the last two are the other complex conjugate pair.
The expressions of the pair $(x_1,x_4)$ are complex conjugates, and so are expressions for $(x_2,x_3)$. This gives you a limited number of possible candidates for which $x$ corresponds to which root object that Mathematica gave.
For each candidate assignment, ask mathematica to simplify fully with "FullSimplify", the elementary symmetric polynomials in $a^5,b^5,c^5,d^5$ and look for the case where only rational numbers are spat out. These are $\pm$ coefficients of the auxiliary quartic with $a^5,b^5,c^5,d^5$ as the roots. Mathematica may take a while in this step, so be patient.
In our case, the correct assignments are $x_1=r_1$, $x_2=r_3$, $x_3=r_4$, $x_4=r_5$, $x_5=r_2$.
Here, $r_i$ are the root objects Mathematica gave.
The elementary symmetric polynomials in $a^5,b^5,c^5,d^5$ come out:
$e_1=-4, e_2=\frac{4}{5}$, $e_3=\frac{8}{125}$, $e_4=-\frac{1}{3125}$.
The quartic: $u^4+4u^3+\frac{4}{5}u^2-\frac{8}{125}u-\frac{1}{3125}=0$
Solving it and matching up the expressions correctly to $a^5,b^5,c^5,d^5$, we are done.
Note that mathematica evaluates $n$th roots of negative real numbers to complex numbers with argument $\frac{2\pi}{n}$, instead of evaluating them to be equal to negative real when $n$ is odd. You must account for that to check your work by flipping sign on the entire expression in the fifth root and the sign in front of the fifth root if the inside expression is negative real.
Final answer (accounting Mathematica's $n$th root preferences):
$x= -\omega\sqrt[5]{1+\frac{2}{5}\sqrt{5}-\frac{3}{25}\sqrt{125+55\sqrt{5}}}+\omega^2\sqrt[5]{-1+\frac{2}{5}\sqrt{5}+\frac{3}{25}\sqrt{125-55\sqrt{5}}}-\omega^3\sqrt[5]{1-\frac{2}{5}\sqrt{5}+\frac{3}{25}\sqrt{125-55\sqrt{5}}}-\omega^4\sqrt[5]{1+\frac{2}{5}\sqrt{5}+\frac{3}{25}\sqrt{125+55\sqrt{5}}}$
Theoretically, these steps can be repeated for any quintic, and replicated on any polynomial of odd prime degree. The only obstacle is in solving the auxiliary polynomial of degree $p-1$, beginning with $p=7$ onwards, which would require finding an intermediate field in which it factors. This can be done by assuming factorization and solving a system in Mathematica.


Basic inequalities proof : if a > b - c implies a > c ?

Question: I have $a,b,c \in \mathbb{R}^{+*}$ (strictly positive real numbers) and $ a > b - c$. Does it imply that : $a > c $ ? if yes hints to the proof may be helpful.
Thanks in advance
Comment: $2 > 10 - 9$, but ...
Comment: Did you try some examples?
Comment: Did you try anything?  Maybe pick some particular values?
Comment: I think you should try some examples before writting the question.
Comment: where does you guess come from? It is of course not true in general
Comment: No. Let $a=5,b=7,c=6$. Then $5>7-6=1$, but $5\not > 6$.
Answer: If $b$ and $c$ are both small, your idea works fine. E.g. $5>4-1; 5>1$
However, if they are both large (relative to $a$) and close together, the theory falls apart. For example: $5>(10,005-10,001)$, but clearly $5\not>10,001$. I'm sure there are infinitely many such counterexamples.
Answer: This is going to be a short answer, which could very well just be a comment, but I would like for you to remember this in the future:

Substitute $b = a + c - 1$. Then, $a > a + c - 1 - c$ if and only if $a > a - 1$ or $1 > 0$, which is true. So, $b \leqslant a + c - 1$.

But, since all of them are positive, then if $a > b - c$, one has that $a > b$. I think this is what you meant, and not $a > c$.
Comment: Shall I put this as a comment? I think so...
Comment: @AlexSilva It has been edited. Thank you for letting me know. It was like saying if $x > y$ then $1/x > 1/y$, but as we all know, the larger the denominator...
Comment: Why $ b = a+c-1$?
Comment: @AlexSilva because $a,b,c$ are **strictly positive**. From the substitution, I get that $b\leqslant a + c - 1$.
Comment: I know. It does not answer my question. $a=4$, $b = 5$ and $c = 3$ are strictly positives and  $b\neq a+c-1$
Comment: @AlexSilva yes but $b \leqslant a + c - 1$ or more precisely, $b < a + c - 1$. I see your point though. It was perhaps a weird way to obtain the inequality


How to open TCP and UDP ports on Mac

Question: How can I open specific ports in order to use a SDK for a project?
I have already tried netcat, but it seems that you can only listen to a specific port or open a specific port if you have a hosting website.
Comment: Please clarify your question. Are you asking how to get a server process listening on a particular port (if so, what kind of server software, etc), or how to prevent a firewall from blocking access to that port (in which case, what firewall, what's the network setup, etc)?
Answer: To open a port and keep listening on it, on macOS this should be working:
nc -lk 8080

To test you can connect to the opened port by doing:
nc -vt 0 8080

To use UDP, you just need to use option -u, for example:
nc -u -lk 8080

To test you can connect:
nc -u -vt 0 8080

Output:
found 0 associations
found 1 connections:
     1: flags=82<CONNECTED,PREFERRED>
        outif (null)
        src 127.0.0.1 port 63214
        dst 127.0.0.1 port 8080
        rank info not available

Connection to 0 port 8080 [udp/http-alt] succeeded!

How to open TCP and UDP ports on Mac


Will gently hammering thumbtacks into my wall help them stay better?

Question: So I'm thinking about fake-upholstering a wall in my bedroom in my apartment to create a focal wall without having to paint. I don't want to drill holes 'cause I'll be moving out of there in like 9 months, so I figure I'll just thumbtack the fabric to the wall, hiding the tacks.
Would hammering in the thumbtacks/pushpins into the wall gently help these thumbtacks stay in the wall better? If not, what will? I know that not moving or re-tacking the thumbtack will help it stay, but any other suggestions would be awesome.
Comment: How about double sided tape.it might work
Answer: The thumb tacks will hold best if they go straight in to the wall without wiggling. If they move back and forth as they're going in, they'll create a larger hole from which they could more easily be pulled. If you can push the tacks all the way in without side to side movement without using a hammer, then there's no advantage to using one. If the hammer allows you to push them in more easily, push them in straighter, or if you can't push them in all the way without a hammer, then the hammer would be better.
Comment: I also worry about transferred force.  Hitting something with a hammer includes a lot more energy than pushing with a finger/thumb; and that energy could go into creating micro-fractures in the drywall around the tacks.  This might allow the tacks to loosen more easily.
Answer: A better option might be to use some small picture-hanging nails with a washer.

The whole it leaves is slightly bigger than a thumbtack, but still easy to patch up, and because it's longer, it will hold better. You should hammer it in so it's going into the wall at a downward angle.
You may need to stack a couple washers, getting bigger in size, in order to have enough area to hold the fabric (really, it depends on the weight- just need to use your best judgement).
The more nails you put in, the less weight each individual one holds, but of course the more holes that will have to be fixed later.
Comment: Hitting studs with the nails will hold better, so you'll require less nails. It can also have the added side effect of evenly spacing the nails, and providing a more uniform look.
Comment: But I think I have metal studs in my apartment. Ergo, nailing into studs = no go.
Answer: Sounds like a good project!
Try coating the part of the thumbtack/nail that will be in the wall with glue. A small amount of glue will fill fissures and allow the shank of the tack/nail to better hold by bonding with the gypsum in the Sheetrock. Since you will be wanting to remove the tack/nail at a future date, select a glue that is not too strong like a super-glue, but one that will still adhere to both the metal shank and the gypsum in the wall. I suggest looking at glues like Elmer's Glue ProBond Advanced; it is designed to attach porous materials like drywall and non-porous materials like metal.
Remember that the friction of the wall against the shank will push excess glue toward the head. A few test applications will give you the right amount of glue that will help hold while not getting onto the back of the thumbtack's head.
Answer: If it requires a hammer to get into the wall, then hammer away. If you can get the tack into the wall with just the force of your finger, then hammering may very well do more damage.
Be sure hammer straight to avoid bending the tack. To do this, take a pretend swing and look at where your hand is when you would hit the tack. If your hand is so far away from the wall that the hammer shaft isn't parallel to the wall, then you'll bend the tack (or nail) when you hit it.
Quick tip: make sure you have something under the tack that won't tear when you pull it so you can easily remove the tack with a tug. Otherwise, you'll have touch-up work to do when you move out after lots of failed attempts to pry out the tack.
Answer: The top of the fabric might be too heavy for thumbtacks to support. You might have to find the studs using a stud-finder, and then use a nail sort of like these tar paper/roofing tacks (which are like oversized pushpins) to affix the top.
Answer: An addition to the glue suggestion.
Since you will eventually be covering the tack heads with your wall covering, a suggestion is to create a tack strip. Using a very thin strip of plastic, paperboard (like a cereal box), or cardboard; place glue on the back of the thumbtack heads and push them through the strip. This will distribute the weight of the covering across the entire length of the strip, allowing the thumbtacks, or brad nails, to hold more weight and be more effective.