text:
Q: Generic C for binary trees How is it possible to write generic c?
I started writing a collection of balanced trees (scapegoat, splay, aa and so on) and find many things in common. Example is destroy function found below.
Can such function and those similar be defined with void pointers without causing "dereferencing void* pointer error"?
Example destroy function
void splay_node_linked_destroy(SplayNode **this) {
 72   if(*this == NULL) {
 73     return;
 74   }
 75   SplayNode *root = (*this)->root, *previous, *next;
 76   while(root) {
 77     if(previous == root->parent) {
 78       // todo use funcs for comparisons for generic
 79       if(root->left) {
 80         next = root->left;
 81       } else if(root->right) {
 82         next = root->right;
 83       } else {
 84         next = root->parent;
 85       }
 86     } else if(previous == root->left) {
 87       if(root->right) {
 88         next = root->right;
 89       } else {
 90         next = root->parent;
 91       }
 92     } else {
 93       next = root->parent;
 94     }
 95     previous = root;
 96     if(next == root->parent) {
 97       splay_node_destroy(&root);
 98       // todo use callback here to make generic
 99     }
100     root = next;
101   }
102 }

A: Actually it's quite possible, and reasonably easy, to write C functions which handle "arbitrary" (generic) data types for a given algorithm.
One trick is to use void pointers and to design APIs in such a way that you use wrapper functions to translate the pointers to their actual types and thus benefit with as much type checking and safety as C will allow for.  The only hard part is the compiler doesn't normally help you with passing type information to your implementation, though some compilers do support the typeof() extension which makes it possible to write wrapper macros that will do the job for you.
Some Examples:
This example appears to use typeof() in the way I suggested:  https://github.com/troydhanson/uthash/tree/master/src
This is an interesting pre-processor macro based library inspired by the Standard Template Library:  http://sglib.sourceforge.net/
This is perhaps one of the most complete examples of generic algorithms for generic types in C, though it is a bit ugly and very wordy and perhaps not as efficient:  http://home.gna.org/gdsl/
This answer gives good advice, though it uses an embedded union instead of a void pointer.  A union is ideal if you know ahead of time what all the possible types of data will be:
https://stackoverflow.com/a/2891570/816536
Another interesting way to build high-level structures (like lists) out of generic data structures is what might be described as the inside-out technique (I like this one too!).  What I would consider the canonical implementation of that inside-out technique is found in the 4.4BSD queue(3) and tree(3) macros with some more readable explanations and examples here:

*

*http://unixjunkie.blogspot.ca/2006/12/lists-and-queues.html

*http://blog.jasonish.org/2006/08/19/tailq-example/

*http://hackab.it/2014/01/generic-linked-list-in-c/
This answer describes a heavily pre-processor dependent technique, though it requires that you either know in advance what all the object types will be, or force the user to write the intermediate header for their specific data type:  https://stackoverflow.com/a/10430893/816536
See also these answers:

*

*https://stackoverflow.com/a/668567/816536

*https://stackoverflow.com/a/13225017/816536

*https://stackoverflow.com/a/28139957/816536

*https://stackoverflow.com/a/649673/816536

A: Here is an example of a generic tree destroy:
// GenericTree.h

void genericTreeDestroy(void *treeNode,  void (*fUserFree)(void *));

// GenericTree.c
typedef struct TREE_NODE {
    struct TREE_NODE *left;
    struct TREE_NODE *right;
};
void genericTreeDestroy(struct TREE_NODE *treeNode,  void (*fUserFree)(void *))
{
    if (treeNode->left)  genericTreeDestroy(treeNode->left,  fUserFree);
    if (treeNode->right) genericTreeDestroy(treeNode->right, fUserFree);
    if (fUserFree) fUserFree(treeNode);
    free(treeNode);
}

// UserStuff.c
#include "GenericTree.h"
typedef struct MY_TREE_NODE {
    struct MY_TREE_NODE *left;
    struct MY_TREE_NODE *right;
    int some_value;
    char *name;
};
void my_freedata(struct MY_TREE_NODE *node);

void main(void)
{
    struct MY_TREE_NODE *myTree= calloc(1,sizeof(struct MY_TREE_NODE));
    myTree->name= malloc(strlen("Hello world")+1);
    genericTreeDestroy(myTree, my_freedata);
}

void my_freedata(struct MY_TREE_NODE *node)
{
    free(node->name);
}

The trick is that ALL trees must start with the left and right member. The .h file defines the genericTreeDestroy with void * parameter and the .c file defines it as struct TREE_NODE *. In this way the user can pass it any tree node type.
Next the user can define any tree node type (as long as it beings with the left and right member) and call the generic function to destroy it. The generic function can be given a function to do any clean-up of the user defined node type, or null if that is not needed.
In the same way you can define other functions. Here is a search function:
// .h
void *generic_tree_search (void *tree, void *value, int (*fUserCmp)(void *value, void *node));

// .c
void *generic_tree_search (struct TREE_NODE *treeNode, void *value, int (*fUserCmp)(void *value, void *node))
{
    while (treeNode) {
        switch (fUserCmp(value,treeNode) {
        case -1: if (treeNode->left) treeNode= treeNode->left; else return(0); break;
        case  0: return(treeNode);
        case +1: if (treeNode->right) treeNode= treeNode->right; else return(0); break;
        }
    }
    return(0);
}


text:
Q: Can't find my trashcan? I have tried to find my trashcan in order to free some space on the disc.
I have tried the suggested commands How can I empty the trash using terminal? but it seems like I don't have any local folder.
I have tried to list all hidden folders aswell, without finding any local or trash folder.
Are removed files stored somewhere else or how to restore space from the delete files if no trashcan found?
I'm using the terminal.

A: Pre-Author's Note:
Read through all of this post until you find a satisfactory solution. If not, add a comment telling me I am the worst wannabe in the world. ;)
Also, the Trash is not what is taking up all of your space. You do not have a Trash Can created, below are instructions of how to make one. In the terminal, when you delete something it is gone forever, except if you use a recovery program like foremost (see below.)
The Location of the Trash Folder
The trash folder is located at /home/username/.local/share/Trash/. This folder may not be there because of you running from terminal, but keep reading! It is only created once a file has been moved there with a GUI (I'm not 100% about this part, but my LXDE setup only created it when I moved a file to there with the file manager).
Explanation:
Due to @Zacharee1, I have realized the true nature of your question. Thank you for that @Zacharee1. So, a Trash Folder doesn't exist in terminal-land, so you have to either create your own or be OK with having the danger of losing important files forever. Of course, that means that the space usage is not caused by that.
If you have a Trash Folder Already Created:
The items inside the Trash folder will be inside another folder, the items folder. Now, if you want to clear this use two separate commands.
rm /home/username/.local/share/Trash/items/*
rm /home/username/.local/share/Trash/info/*

If You Just Want To Restore Some Files:
Take a look into the forensics program foremost. You can download with
sudo apt-get install foremost

Look at online instructions for using it, use the man page or look below at my extremely limited understanding of how this works. Let me stress that, I just found this and am not knowledgeable in this area, so do not think everything I say is true. On HowToForge (https://www.howtoforge.com/recover-deleted-files-with-foremost) it tells you to run
foremost -t filetype -i /dev/sda1

(Obviously) Replace filetype with the type of file you need to recover. For example, if I wanted to recover pdfs I would do
foremost -t pdf -i /dev/sda1

You will find what is recovered in a folder in the directory you are in called output. If you want to do it multiple times in the same directory, do
foremost -t filetype -T -i /dev/sda1

The extra -T stands for timestamp so the separate outputs won't mess eachother up. For a better understanding of foremost, check out the link provided or do your own research.enter code here
If You Don't Have a Trash Folder Created (And You Want One):
This one is probably you! So, you might have to try two separate things.
The first, and probably most unappealing, is to figuratively make your own Trash folder, set up a timer for it and a system for the files inside to be deleted. You can do this by adding a script to your crontab, which has a timer of 1 month. When the timer gets high enough, BAM,
rm /path/to/trash/*
If you Don't Want to Do It Yourself:
Alright soldier! There are a couple of things you need to know. The crontab. A useful tool which lets you run scripts and commands at startup. We probably will be using this. There is a big flaw to the idea that I just proposed. The timer will it only run if your computer is on. AHA, I've got a (slightly) better idea!
The Slightly Better Idea!
Alright, this will involve a python script and a .txt! Hurray! You will need an empty txt file in the same folder as this one called garbage.txt. So,
basically, these are the contents:
#!/usr/bin/env python3
#Comment: This Will Be Called Trash.py

import datetime
import subprocess

with open("garbage.txt", "r+") as garbage:
     x = int(garbage.read(1))
     now = datetime.datetime.now()
     month = now.month
     if month != x:
         subprocess.Popen(['rm', '-rf', '/where/ever/trash/folder/is/)
         subprocess.Popen(['mkdir', '/where/ever/trash/folder/is/'])
         with open("garbage.txt", 'w+') as sadness:
         sadness.write(str(month))

Now then, add this script to the crontab. I'll assume for benefits of the reader that you don't know how to do this. So, create a bash script in the same directory as trash.py. Call it trashshell.sh. In it write:
#!/bin/bash
python3 trash.py

Save that, then type in the command crontab -e to the terminal.
Select the terminal editor nano and then write
@reboot sh /path/to/trashshell.sh

Hope this helped!
Optional: An Easy Delete!
Put this:
function trasher(){
     mv "$1" /path/to/trash
}

into your .profile or your .bashrc (Do bashrc if it exists).
This will all you to move items to trash with trasher itemname.
For example, trasher new.txt
A probably False Idea!
Try recreating a Trash folder in the spots it would be, like the Trash folder, the expunged folder, the files folder, and the info folder.
Wait 30 days. This probably won't work!!!
Author's Note:
Do not copy and paste the code I wrote. The indentation is almost 100% messed up, because cannot do formatting on Stack Overflow! Some one teach me please!!! If you made your own trash folder and you're feeling adventurous you can change some stuff up a bit, like the length of the timer.

A: From what I've seen, Trash is just an indexing feature. When a file is deleted from the file manager, it's moved to ~/.local/share/Trash/, which it's directory structure kept intact. (EG: if you delete ~/testfolder/testfile.sh, testfile.sh will go to ~/.local/share/Trash/testfolder/testfile.sh.)
(If you use sudo or gksudo to open a file manager, /root/.local/share/Trash is the trash directory used for that session.)
Unfortunately, that's a GUI thing. The terminal doesn't do that. rm actually deletes the file; it doesn't just move it to a trash folder to later be recovered or deleted, it skips the trash completely. If course, you can recover files, but only if you haven't overwritten the space on the hard drive they used to occupy.
You have to be much more careful in the terminal, since it's not exactly designed for ease of use and convenience. Since there's no trash, deleting files is more dangerous. Also since there's no trash, there's no trash to delete to save space. Something else is filling up your hard drive.

A: Open nautilus or whatever filemanager you use and type in the addressbar (ctrl+l)
trash:///
Then you should be in your trashcan.
I compared the content of my trash from nemo (my filemananger in Linux Mint) with the content of the output of ll -R ~/.local/share/trash. And it looks like what I see in the filemanger is located in the subfolder info.
From the terminal:
rm -rf ~/.local/share/Trash/info
But as you said, you don't have any Trash. That's odd unless you removed your files from the terminal. If you did that, the files are really deleted and not moved to the trash!
No ~/.local/ in a server installation after a fresh installation

redpajama_set_name: RedPajamaStackExchange


text:
Q: c# send uploaded file through email daily using asp.net web application I just want to know, how to make a web-application which takes input of Excel files from user and send an email daily if that excel file has any new data available.
Should I use web service (with installation of that service in local computer) ? and yes then how to add Upload User-Interface. or Should I use only a web application and Should I add web-service in that application ?
Pls give way to come out of this problem.
Thankyou.

A: Depends on the nature of the application you're building:

*

*If you want the user to access this over internet, create it as an ASP.NET application (UI) and a Windows Service / Windows Task Scheduler on the Server to send out scheduled emails.

*If you want the user to run the application from his/her local machine/server, create a windows forms application (UI) and a Windows Service / Windows Task Scheduler on the local machine to send out scheduled emails.

A: No need of installations to the user computer. You need a simple Web Application and a web server, of course. There are many tutorials about getting started with web applications here are some links:

*

*ASP.NET WebForms - obsolete, yet powerful web app paradigm.
However, I do recommend the next option, especially if you don't have any previous experience with desktop applications.

*ASP.NET MVC - this is the modern way of building web applications.
Once you made your mind about what technology to use, you gonna need so called SMTP server; usually the ISP provides one for you and you gonna need to add a configuration to the web.config, such as:
<system.net>
    <mailSettings>
        <smtp deliveryMethod="Network">
            <network host="*SMTP server IP address*" port="25" />
        </smtp>
    </mailSettings>
</system.net>

You can take a look at this SO post for details on how to accomplish this in ASP.NET MVC.

A: If you really want to it as background job on a Asp.Net WebApp you should look into:

Quartz.Net
Create a job to send e-mail
public class SendMailJob : IJob
{
    public void Execute(IJobExecutionContext context)
    {
        ...Do your stuff;
    }
}

Then configure your job to execute daily
// define the job and tie it to our SendMailJob class
IJobDetail job = JobBuilder.Create<SendMailJob>()
    .WithIdentity("job1", "group1")
    .Build();

// Trigger the job to run now, and then repeat every 24 hours
ITrigger trigger = TriggerBuilder.Create()
    .WithIdentity("trigger1", "group1")
    .StartNow()
    .WithSimpleSchedule(x => x
        .WithIntervalInHours(24)
        .RepeatForever())
    .Build();

HangFire
RecurringJob.AddOrUpdate(
    () => YourSendMailMethod("email@email.com"),
    Cron.Daily);

IHostedService (only in Asp.Net Core)
public class SendMailHostedService : IHostedService, IDisposable
{
    private readonly ILogger<SendMailHostedService> _logger;
    private Timer _timer;

    public SendMailHostedService(ILogger<SendMailHostedService> logger)
    {
        _logger = logger;
    }

    public Task StartAsync(CancellationToken stoppingToken)
    {
        _logger.LogInformation("Hosted Service running.");

        _timer = new Timer(DoWork, null, TimeSpan.Zero,
            TimeSpan.FromSeconds(5));

        return Task.CompletedTask;
    }

    private void DoWork(object state)
    {
        //...Your stuff here

        _logger.LogInformation(
            "Timed Hosted Service is working. Count: {Count}", executionCount);
    }

    public Task StopAsync(CancellationToken stoppingToken)
    {
        _logger.LogInformation("Timed Hosted Service is stopping.");

        _timer?.Change(Timeout.Infinite, 0);

        return Task.CompletedTask;
    }

    public void Dispose()
    {
        _timer?.Dispose();
    }
}

In your startup.cs class. add this at configure method.
services.AddHostedService<SendMailHostedService>();

If do not need to host it as a backgroud job on your WebApp, then you can create a Windows Service that runs every day on the time you need.
See this question: Windows service scheduling to run daily once a day at 6:00 AM


text:
Q: comparative of the adjective "grave" I had written

The effect of traumatic experience may be graver if...

and the editor has corrected it to

The effect of traumatic experience may be more grave if...

Surely grave conforms to the regular rules for comparatives? Am I missing something? (I note that graver is also a tool for making engravings - but that's irrelevant.)

A:
The Oxford Learner's Dictionaries gives "grave, graver, gravest". Collins also gives "comparative graver, superlative gravest." If the topic was bereavement, perhaps the editor would avoid that word altogether and use "more serious".

Credit: Weather Vane


text:
Q: Is there a better way to do this jQuery code? I am currently creating a navbar for mobile devices that will expand when the button is pressed. It expands a certain amount of pixels for the content. When the close button appears it should close back down to the original size of the button. It sizes up properly but will not resize down. Here is the basic version of my code.
I've tried creating variables and loads of other stuff that I honestly can't remember what exactly I have done.
My HTML:

×

My CSS:
.mobile-navbar-button {
  background-color: blue;
  width: 90px;
  height: 90px;
  border-radius: 50%;
  position: fixed;
  left: 2vw;
  top: 30px;
  transition: 0.5s;
  z-index: 0;
}

.navbar-background {
  background-color: rgba(0, 0, 0, 0.9);
  width: 100vw;
  height: 100vh;
  position: fixed;
  top: 0;
  left: 0;
}

.closebtn {
  color: white;
  font-size: 100px;
  position: fixed;
  top: -80px;
  left: 35px;
  display: none;
  transition: 0.8s;
}
.bar-1 {
  background-color: white;
  width: 54px;
  height: 3px;
  position: fixed;
  top: 65px;
  left: 37px;
}
.bar-2 {
  background-color: white;
  width: 54px;
  height: 3px;
  position: fixed;
  top: 85px;
  left: 37px;
}

My jQuery:
$(document).ready(function() {
  $(".mobile-navbar-button").on('touchstart', function() {
    $('.mobile-navbar-button').css('width', '1425px');
    $('.mobile-navbar-button').css('height', '1200px');
    $('.mobile-navbar-button').css('left', '-400px');
    $('.mobile-navbar-button').css('top', '-400px');
    $('.mobile-navbar-button').find('.bar-1').css('display', 'none');
    $('.mobile-navbar-button').find('.bar-2').css('display', 'none');
    $('.closebtn').css('display', 'block');
  });
  $(".closebtn").on('touchstart', function() {
    $('.mobile-navbar-button').css('width', '90px');
    $('.mobile-navbar-button').css('height', '90px');
    $('.mobile-navbar-button').css('left', '2vw');
    $('.mobile-navbar-button').css('top', '30px');
    $('.mobile-navbar-button').find('.bar-1').css('display', 'block');
    $('.mobile-navbar-button').find('.bar-2').css('display', 'block');
  });
});

I would like the .mobile-navbar-button width and height to reflect back to 90px for the width and height. But currently this does not happen. The width and height sort of "sticks" at 1425px width and 1200px height and will not go back to what I have set up in .closebtn function.

A: Here's a code somewhat simpler:

$(document).ready(function() {
  $(".mobile-navbar-button").on('click touchstart', function() {
    $('.mobile-navbar-button').css({
      "width": 1425 + "px",
      "height": 1200 + "px",
      "left": -400 + "px",
      "top": -400 + "px",
    });

    $('.mobile-navbar-button').find('.bar-1, .bar-2').css('display', 'none');

    $('.closebtn').css('display', 'block');
  });

  $(".closebtn").on('click touchstart', function() {
    $('.mobile-navbar-button').css({
      "width": 90 + "px",
      "height": 90 + "px",
      "left": 2 + "vw",
      "top": 30 + "px",
    });

    $('.mobile-navbar-button').find('.bar-1, .bar-2').css('display', 'block');
    $('.closebtn').css('display', 'none');
  });
});
.mobile-navbar-button {
  background-color: blue;
  width: 90px;
  height: 90px;
  border-radius: 50%;
  position: fixed;
  left: 2vw;
  top: 30px;
  transition: 0.5s;
  z-index: 0;
  cursor: pointer;
}

.navbar-background {
  background-color: rgba(0, 0, 0, 0.9);
  width: 100vw;
  height: 100vh;
  position: fixed;
  top: 0;
  left: 0;
}

.closebtn {
  color: white;
  font-size: 100px;
  position: fixed;
  top: -80px;
  left: 35px;
  display: none;
  transition: 0.8s;
  cursor: pointer;
}

.bar-1 {
  background-color: white;
  width: 54px;
  height: 3px;
  position: fixed;
  top: 65px;
  left: 37px;
}

.bar-2 {
  background-color: white;
  width: 54px;
  height: 3px;
  position: fixed;
  top: 85px;
  left: 37px;
}

×

The closebtn had to be taken out of the .mobile-navbar-button element to get it to work correctly, and also its click / touchstart function had to be modified (a CSS display hidden added as the last line).
It works with click and touchstart events, and uses the object syntax for jQuery CSS.
It's usually a good idea to separate the unit from the number in jQuery CSS, because this way it may be used as a number instead of a string (1425 is an int, but 1425px is a string).

A: Here is the solution!

$(document).ready(function () {

    // Proper way of using multile CSS
    $('#div').css({
        'width': '500px',
        'height': '500px',
        'background': '#eee',
        'border-top-left-radius': '40px',
        'display': 'none'
    });

    $('#close').css({
        'display': 'none'
    });

    $('#open').click(function () {
        $('#div').css({
            'display': 'block'
        });
        $('#close').css({
            'display': 'block'
        });
        $(this).css({
            'display': 'none'
        });
    });

    $('#close').click(function () {
        $('#div').css({
            'display': 'none'
        });
        $('#open').css({
            'display': 'block'
        });
        $(this).css({
            'display': 'none'
        });
    });
});
button {
    background-color: blue;
    width: 90px;
    height: 90px;
    border-radius: 50%;
    position: fixed;
    left: 2vw;
    top: 5px;
    transition: all 1s ease;
    z-index: 0;
    cursor: pointer;
    color: #fff;
    font-size: 30px;
    border: none;
}

<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.1/css/all.css" integrity="sha384-50oBUHEmvpQ+1lW4y57PTFmhCaXp0ML5d60M1M7uH2+nqUivzIebhndOJK28anvf" crossorigin="anonymous">

  <button id="open"></button>
  <button id="close"></button>

I have also showed the proper way of using multiple css. Hope that'd help.

A: I got it to work guys! A little bit of extra coding work around that may not be 100% practical but it works the way I want! Thank you for everyone for contributing! If you would like to see what I have done I will post it in this answer.
My HTML:

×

I added the class navbar-background behind mobile-navbar-button so that the user would not be able to see it.
My CSS:
.mobile-navbar-button {
  background-color: blue;
  width: 90px;
  height: 90px;
  border-radius: 50%;
  position: fixed;
  left: 2vw;
  top: 30px;
  transition: 0.5s;
  z-index: 3;
}

.navbar-background {
  background-color: blue;
  width: 90px;
  height: 90px;
  border-radius: 50%;
  position: fixed;
  left: 2vw;
  top: 30px;
  transition: 0.5s;
  z-index: 2;
}

.navbar-fullscreen-background {
  background-color: rgba(0, 0, 0, 0.9);
  width: 100vw;
  height: 100vh;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 1;
  transition: 0.5s;
  display: none;
}

.closebtn {
  color: white;
  font-size: 100px;
  position: fixed;
  top: -80px;
  left: 35px;
  display: none;
  transition: 0.8s;
}

.bar-1 {
  background-color: white;
  width: 54px;
  height: 3px;
  position: fixed;
  top: 65px;
  left: 37px;
}
.bar-2 {
  background-color: white;
  width: 54px;
  height: 3px;
  position: fixed;
  top: 85px;
  left: 37px;
}

I then added navbar-background into the CSS and then gave mobile-navbar-button, navbar-fullscreen-background, and navbar-background a z-index to modify their stacking.
My jQuery:
$(document).ready(function() {
  $(".mobile-navbar-button").on('touchstart', function() {
    $('.navbar-background').css({'width': 1450 + 'px', 'height': 1200 + 'px', 'left': -400 + 'px', 'top': -400 + 'px',});
      $('.navbar-fullscreen-background').css('display', 'block');
        $('.mobile-navbar-button, .bar-1, .bar-2').css('display', 'none');
          $('.closebtn').css('display', 'block');
  });
  $(".closebtn").on('touchstart', function() {
    $('.navbar-background').css({'width': 90 + 'px', 'height': 90 + 'px', 'left': 2 + 'vw', 'top': 30 + 'px',});
      $('.mobile-navbar-button, .bar-1, .bar-2').css('display', 'block');
        $('.navbar-fullscreen-background').css('display', 'none');
          $('.closebtn').css('display', 'none');
  });
});

I finally took my jQuery (tidied up version) and fixed it to correspond correctly to my HTML and CSS changes and was able to make .mobile-navbar-button, .bar-1 and bar-2 display none so that instead will use the navbar-background as the grow and shrink area for the content.
Not 100% sure if it is the best way but it's a way that worked for me!

A: How come nobody has thought of just adding and removing a class to the nav button to signal state! manipulating style properties from JS/jQuery is horrible if you decide you want to change the applied styling. Just use a few extra CSS rules and toggle a class on the navbar. Much simpler and much easier to maintain
Simply toggle an open class on the navbarthe extra CSS will handle the display.
I've added the click event handlers to make a bit easier to use on devices without a touch screen ;)

$(document).ready(function() {
  var navButton = $(".mobile-navbar-button");
  var closeButton = $(".closebtn");

  navButton.on('click', function() {
          navButton.toggleClass('open')
      });

  closeButton.on('touchstart', function() {
          navButton.toggleClass('open');
      });

});
.mobile-navbar-button {
  background-color: blue;
  width: 90px;
  height: 90px;
  border-radius: 50%;
  position: fixed;
  left: 2vw;
  top: 30px;
  transition: 0.5s;
  z-index: 0;
}

.navbar-background {
  background-color: rgba(0, 0, 0, 0.9);
  width: 100vw;
  height: 100vh;
  position: fixed;
  top: 0;
  left: 0;
}

.closebtn {
  color: white;
  font-size: 100px;
  position: fixed;
  top: -80px;
  left: 35px;
  display: none;
  transition: 0.8s;
}

.bar-1 {
  background-color: white;
  width: 54px;
  height: 3px;
  position: fixed;
  top: 65px;
  left: 37px;
}

.bar-2 {
  background-color: white;
  width: 54px;
  height: 3px;
  position: fixed;
  top: 85px;
  left: 37px;
}

/* Change display when 'open' class is active on .mobile-navbar-button */
.mobile-navbar-button.open {
  height: 1200px;
  left: -400px;
  top: -400px;
}

.mobile-navbar-button.open .bar-1,
.mobile-navbar-button.open .bar-2 {
  display: none;
}

.mobile-navbar-button.open .closebtn {
  display: block;
  top: 30px;
  color: red;
}

×

EDIT removed 'touchstart' event handlers


text:
Q: ConfigError: no steps directory I'm facing a problem with behave. As I checked for some solutions there, they were supposing me to make sure my feature is in right place, but it is, and anyway it doesn't work. I get an error: ConfigError: No steps directory .......
I tried to execute it by using behave command.
My tree looks like this:

A: You need to add an empty __init__.py file in your sub-directories (zad1, features, steps) for behave to access the file in steps/.
src probably needs it too.


text:
Q: Cryptographic Hash to verify identification key Let's say I want to pass information to the user that includes the user's unique id. Then, I want to use that id for CRUD operations. Is it a viable, or even recommended, option to store a cryptographic hash of that data, which would remain static using something like SHA-2 and then verify that what the user passed to me was what I sent them? Or, should I never send them the information in the first place and just look up the information from a table?
My issue now is that I am using AWS Cognito and using the sub as the unique identifier. So, I do not want to 'trust' the end user with sending me that sub after cognito provides them with it.


text:
Q: why deinit of view controller is not calling using RXSwift? I tried a few things but couldn't find a solution. I am navigating the controller in the onNext block but the deinit is not calling. I have also declared the self as weak in the rx closures.
Below is the complete class code.
Please correct if I am doing anything wrong:
class LoginVC: UIViewController {

    //MARK:- Variables & Consts
    private let tag = "LoginVC"
    private let loginViewModel = LoginViewModel()
    private let disposeBag = DisposeBag()

    //MARK:- IBOutlets
    @IBOutlet weak var tfUsername: MFTextField!
    @IBOutlet weak var tfPassword: MFTextField!
    @IBOutlet weak var btnLogin: UIButton!

    //MARK:- View Controller Life Cycle
    override func viewDidLoad() {
        super.viewDidLoad()

        setupBindings()
    }

    ///deinit
    deinit {
        print(" deinit")
    }

    //MARK:- Custom Methods

    private func setupBindings() {
        loginViewModel
            .loginResponse
            .observeOn(MainScheduler.instance)
            .subscribe(onNext: { [weak self] loginResponse in
             let vc = UIStoryboard(name: Constants.MAIN, bundle: nil).instantiateViewController(withIdentifier: Constants.HOME_VC)
                self?.navigationController?.pushViewController(vc, animated: true)
            }, onError: { [weak self] error in
                self?.removeLoader()
            }, onCompleted: {  [weak self]  in
                self?.removeLoader()
            }, onDisposed: { [weak self] in
                print("\(self?.tag ?? "") onDisposed")
            })
        .disposed(by: disposeBag)

        btnLogin.rx.tap.bind{ [weak self] in
            self?.loginViewModel.login(username: self?.tfUsername.text ?? "", password: self?.tfPassword.text ?? "")
        }.disposed(by: disposeBag)
    }
}

Any help would be appreciated.

A: You are pushing the next view controller here.
self?.navigationController?.pushViewController
When you do this, LoginVC never gets deallocated because it's still in the memory and navigation controller's stack. So there's no reason for deinit to be called.
deinit will only get called if you dismiss LoginVC. And if your LoginVC is your root viewcontroller it will never call it's deinit.
This has nothing to do with RxSwift.

A: You are strongly capturing self in your observable chain. Then putting the disposable that holds the subscription into a disposeBag that is a property of self.
This means that you have a reference cycle. Your view controller has captured itself in itself.


text:
Q: Django Debug Toolbar doesn't show I'm using Django But Django Debug Toolbar doesn't show on Chrome & Firefox. I have done all steps for config, that said on the official site of Django-debug-toolbar.
Django Version: 3.1.4
Python Version: 3.9.0

A: Problem Solved, I tested 127.0.0.1:8000 on Microsoft edge and everything was ok but on chrome, firefox and ie the toolbar did not show.
If you have configured correctly and can't see the toolbar please check with other browsers, like edge
Thanks all.


text:
Q: Is it possible to distinguish between different unnamed exceptions in Python? I am working with a Python library, specifically a function that runs a SQL query in a database. This function has a bad habit of throwing generic Exceptions when it fails. For example, when I don't have rights to query a database, I see this error:
 Exception: None: b'You may not submit queries to this connection'

When there is an error in the query, I get this error:
Exception: None: During query 'SELECT count(*) as count from customers where birthdate=0':
Operand type clash: date is incompatible with tinyint, caused by: SQLServerException:
Operand type clash: date is incompatible with tinyint

I would like to handle the connection error differently from the query error, but I don't know how to distinguish between them because they don't have a specific type.


text:
Q: How to Remove Duplicates From Array in Javascript? Here I have two multiline textboxes and enter some data in two textboxes like
txt1
1,1,1,2,2,2,3
txt2
1,2,3,4,5,
when i press Filter button it shows the data in thirdtextbox like
txt3
4,5 (both the textboxes are having these numbers)
My snippet is

and my controls are

        Enter Numbers:
         <asp:TextBox ID="txt1" TextMode="MultiLine" runat="server"></asp:TextBox>
        Enter Numbers:
        <asp:TextBox ID="txt2" TextMode="MultiLine" runat="server"></asp:TextBox>

        <input type='button' value='Get Distinct Items' onclick='GetDistinctElements(<%= txt1.ClientID %>,<%= txt2.ClientID %>,<%= txt3.ClientID %>); return false;' />
        <asp:TextBox ID="txt3" TextMode="MultiLine" runat="server"></asp:TextBox>

when I tried this snippet, I didn`t get the expected output.

A: Replace this:
var Array = input.concat(input1);
var distinctArray = Array.filter(function (item, pos) {
    return Array.indexOf(item) == pos;
});

by this:
var input2 = input.concat(input1);
input2.sort(function(a,b){return a-b});
var prev= null;
var distinctArray = input2.filter(function (item, pos) {
    if (item == prev){
      return false;
    }
    prev = item;
    return true;
});

A: I got the Answer
 function GetDistinctElements(source,source1, target) {
        // Get the items in your input
        var input = source.value.trim().replace(';', ',').split(',');
        var input1 = source1.value.trim().replace(';', ',').split(',');
        input1 = input1.filter(function (val) {
            return input.indexOf(val) == -1;
        });
        // Output the result in  target area
        target.value = input1.join(',');


text:
Q: Python waiting for subprocess to finish I'm really new to Python and I got a little problem with the subprocess class.
I'm starting an external Program with :
      thread1.event.clear()
      thread2.event.clear()
      print "Sende Motoren STOP"
      print "Gebe BILD in Auftrag"
      proc = Popen(['gphoto2 --capture-image &'], shell=True, stdin=None, stdout=None, stderr=None, close_fds=True)
      sleep (args.max+2)
      thread1.event.set()
      thread2.event.set()
      sleep (args.tp-2-args.max)

My Problem is that in my shell where I Started the Python script, I still get the outputs of GPHOTO2 and I think Python is still waiting for GPHOTO to finish.
Any ideas?

A: The documentation for subprocess.Pope states:
stdin, stdout and stderr specify the executed programs' standard
input, standard output and standard error file handles, respectively.
[...]
With None, no redirection will occur; the child's file handles will be
inherited from the parent.

So you might want to try something along the lines of this. Which btw. blocks until completion. So you might not need the sleep() (here the wait() from subprocess.Popen might be want you want?).
import subprocess

ret_code = subprocess.call(["echo", "Hello World!"], stdout=subprocess.PIPE);


text:
Q: Cannot access value from JSON file received from $http.post I have this problem. I have grocery list item app written in AngularJS. I symulated a connection to server through AJAX request made to local files written in JSON format.
I have for example one file which returns me a fake serwer status:
[{
    "status": 1
}]

I try to receive that value of this status by writing code:
groceryService.save = function(entry){

        var updatedItem = groceryService.findById(entry.id);
        //We update the existing item
        if(updatedItem){

            $http.post("data/updated_status.json", entry)

                .success(function(data){

                  //HERE IS PROBLEM -------------------
                  if(data.status == 1){
                  //END OF PROBLEM --------------------

                    updatedItem.completed = entry.completed;
                    updatedItem.itemName = entry.itemName;
                    updatedItem.date = entry.date;
                   }
            })

                .error(function(data,status){

            });
   //We creating new item
   else{

   }

As I see I cannot access this status value and I don't know why. In Chrome Browser I don't receive any error code. Apparently as I see AngularJS must send back this JSON data in changed format which I must access differently, but how ?
I thought that AngularJS parses value 1 from int to string but I made small try and It failed.
I attach of course $http service in my service directive:
app.service("GroceryService", function($http){

I run my files on xampp local server.
If someone could help me solve this problem it would be great :-).
Thanks in advance.
EDITED: -------------------------------------------
I found out that the problem is with $http.post() AngularJS method. When I switch in my code to get() method everything work well.
I get error 404 from chrome browser when I trigger $http.post(). My code looks like this:
$http.post('data/ai.json', entry)

And this:
$http.post('data/update_status.json', entry)

Thirst I thought I made a mistake in file name so I changed it to ai.json but it is not a problem. I don't know where might be the problem, I use brackets IDE and it has option live preview of written code in brower. It creates some serwer to do this.
I attach also screenshot of directory of my files and screenshot of error 404 from chrome.
Still I need help in solving this problem. Thanks in advance :-).
Error 404 from Chrome when I click save button.
Directory of files. In data folder are all my .json files
During searching in Internet for solution I found this one:
$http.post("data/update_status.json", entry, {
    headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
  })

But I implemented it in my code and got the same Error 404 result. I am hoping for some help :-).
EDITED -------------------------------------------
Hi
I still didn't solved this error issue. I uploaded my files to coding ground on tutorialspoint to find out if it is not server issue. When I invoke $http.post() method I still get Error 404. I am 100% sure I wrote correct paths to files.
Can anyone help me in solving this. The obvious conclusion is that the error is in my code because server of coding ground should work well.
Any help folks ? :-)
Thanks

A: The construct in the file looks like an array so you might want to try the code below instead.
if(data[0].status == 1)


text:
Q: Using XML to populate Model not a Database I have recently began my journey learning WPF and MVVM. However a lot of guides and discussions I have found have been with the MVVM Data accessing at Database.
I simply want to be able to load a XML file instead of going through a Database but I don't have much knowledge in the area or the best practice of using a XML as a Data source in MVVM.
Any help what so ever would be appreciated.

A: Your question doesn't appear to have anything to do with WPF or MVVM, it looks like your questions are related to using XML for data access. One such way is Linq to XML?
XDocument xmlDocument = XDocument.Load(filename);

var data = (from item in xmlDocument.Descendants()
            select new
            {
                Customers = (from customers in item.Descendants("Customer")
                             select new Customer
                             {
                                 Name = customers.Element("Name").Value,
                                 Address = customers.Element("Address").Value
                             }).ToList(),
                Manufacturers = (from manufacturers in item.Descendants("Manufacturer")
                                 select new Manufacturer
                                 {
                                     Name = manufacturers.Element("Name").Value,
                                     Phone = manufacturers.Element("Phone").Value
                                 }).ToList()
            }).SingleOrDefault();


text:
Q: How to get LogLiklihood value from logistic regression in R Question:

*

*Is it possible to get log liklihood values for my stepwise glms?

Context:
I am able to get a logliklihood value using lmer with the following model. My study involves unbalanced repeated females, two sites (females don't exchange between sites), 8 predictors, and a response.
    (glmfit1 <- lmer(Response ~ 1 + SITE + (1|SITE:FEMALE) + Variable A + Variable B +
                        Variable C, data = data))

Removing the repeated females and taking out the Site factor gives me this formula.
(lrfit1 <- glm(Response ~ 1+Variable A + Variable B + Variable C, data = data))
summary (lrfit1) #just gives me p values for my variables and an AIC but NO LOGLIK.

A: Have you tried logLik(lrfit1)?


text:
Q: How to run Apache module with superuser privileges? I am using Apache 2.4 on Ubuntu. I have written one module in C language and integrated it into Apache server using Apache Extension tools (apxs). There is some part of my code where I am calling executable using exec function but I want to call that executable as superuser. so I want to run my module with superuser privileges but by default Apache is running as www-data user and asking for password for www-data.
Is there any way to run this module using superuser privileges?
Otherwise is there any other way to run root command in C within Apache module?
Is it possible to use suExec module for this?

A: No, it's not possible to run the Apache module under a different user from the Apache server itself. But there are several strategies to workaround that limitation.
1) You can set the "setuid bit" on the executable you want to run from Apache, like this:
chown root:root executable
chmod 06755 executable

Then, when you run this executable (say, with fork + exec or with system) from the Apache module, the executable will run from under the root user, with root permissions.
2) You can configure the /etc/sudoers file in a way that will allow the www-data to run the executable in question with the root priviledges with the help of the sudo command.
3) You can have a separate process running with root priviledges and receiving commands from the Apache module with any kind of IPC/RPC.
Please note, that you should avoid using the root priviledges if it all possible since running your code under root might pose a security risk. Unless, of course, you're absolutely sure that your code won't have any bugs.


text:
Q: Splitting html string after so many words I have a string that if it is longer than lets say 10 words, I want to split it into two parts. The second part will be included else-where after a 'more' link.
The string will hold html tags too though.
For an example the string could be:

This is just a test string with more words than the amount allow before split, blah blah blah

So in the case I would want:
$string[0] //
This is just a test string with more words than
;
$string[1] //
the amount allow before split, blah blah blah
;

Thanks in advance

A: Well, I've had the same issues. I solved this in letting my news-writers allow to use "[intro]...[/intro]"-Tags within their texts. Then I parsed the tags with a regex.
If the cutting should be done automatically without using special tags, it's a bit more difficult. You could use the substr()-function. But then you would have problems with the html-tags. Therefore I would cut them as well with something like: substr(strip_tags($text), 0, 50). This would allow 50 chars to be displayed, exclusive the html-tags.
Maybe this can help you :)

A: It's not trivial, but here's an idea:

*

*Iterate through the string, character by character

*keep at least these state variables:

*

*$inTag – whether you're inside a tag

*$inAttribute – whether you're inside a tag attribute (where ">" doesn't end the tag)

*$currentTagSoFar – all the characters of the current tag. Would start with "s", then "st", "str", etc., until "strong"

*$openedTags – stack variable where you put the currently opened tags (push when you find an opening tag, pop when you find a closing one)

*$wordsSoFar – the number of words you've found so far

*maybe also $insideComment, depending on how thorough you want to be

*When you reach your target number of words, pop the tags from the stack and add the remaning closing tags to the string.


text:
Q: first letter up all uppercase words in string data with jquery my string data as as follow.
var HmtlStr = "My names is KERBEROS. AGE: 29, my eyes BROWN.</span"

result must be like this which i want;
My names is Kerberos. Age: 29, my eyes Brown.</span

thank you very much for your help, already now.

A: Perhaps the CSS text-transform: capitalize would work?

A: Use a function in a replace to change the strings:
HmtlStr = HmtlStr.replace(
  /([A-Z])([A-Z]+)/g,
  function(a,m1,m2) {
    return m1 + m2.toLowerCase();
  }
);

Edit:
The built in toLowerCase method handles most characters, you just have to include them in the set in the regular expression ([A-ZÖİŞÜĞÇ]) so that they are handled. To handle the few characters that the built in method doesn't cope with, you can make a function that replaces those first:
function localLowerCase(str) {
  str = str.replace(
    /İ/g,
    function(m){
      var i = "İ".indexOf(m);
      return i != -1 ? "ı"[i] : m;
    }
  );
  return str.toLowerCase();
}

You can easily add more characters for the function to handle by adding them in the /İ/ pattern, the "İ" string and the replacement in the "ı" string.

A: Try this  one:
   'apple cat dog stack overflow'.replace(/(\b)([a-zA-Z])/g,
       function(firstLetter){
          return   firstLetter.toUpperCase();
       })

:)


text:
Q: The middle mouse button loses its function and cursor moves uncontrollably First of all, I've checked similar questions. But I couldn't find a solution.
I have Ubuntu 20.04.5 LTS on my laptop, and the GNOME version is 3.36.8.
My mouse is connected over Bluetooth, Logitech MX Anywhere 2S. It works on Windows without a problem. But I have two issues with Ubuntu:

*

*Sometimes middle click loses its function (close tab, open link in a new tab etc.) abruptly.

*Sometimes mouse cursor begins to move by itself very fastly, and the mouse left clicks uncontrollably.
I turn off the mouse, the problem persists, I turn off the touchpad, but the problem still does not go away.
These problems happened after a significant update, but I don't remember exactly what update it was.


text:
Q: Pytest intermittenty failing using multiprocessing.pool.ThreadPool I have the following function:
def parallel_ping(ip_addresses, deadline=1.0, interval=None, attempts=None, pool_size=20):
    try:
        pool = ThreadPool(processes=pool_size)
        args = ((ip, deadline, interval, attempts) for ip in ip_addresses)
        result = pool.map_async(ping_check, args)
        return result.get()
    finally:
        pool.close()

ping_check is a function that actually pings the devices (ip_addresses)
in my test, I have mocked out the ping_check function (replaced it with a function that returns the packet_loss).
sometimes when the test runs it raises an exception:
UnboundLocalError: local variable 'pool' referenced before assignment

My test function is inside a test_class that inherits from unittest.TestCase, and has a
def setUp(self):
    self.old_function = ping_check

and a
def tearDown(self):
    ping_check = self.old_function

function.
In the test function, I am assigning ping_check = mock_ping_check
and then calling the parallel_ping function in there.
I am not sure why this exception is raised sometimes, and not others.

A: The exception is raised when your ThreadPool(processes=pool_size) fails. When that happens, an exception is raised instead of the pool being created, which means the pool variable is never assigned.
The finally block is then immediately executed, and tries to call pool.close(), which, since pool was never assigned, raises UnboundLocalError.
Move your pool = ThreadPool(pool_size) line out of the try block. It will have the added benefit of telling you exactly why the line fails.


text:
Q: shadow dom script to watch for changes in host I am creating an app where I need to manage a collection of elements that take advantage of the shadow dom. Since the template tag encapsulates content, I can keep the style and script with the elements in order for them to act on events. What I would like to know is if it is possible for script inside the shadowRoot to observe changes to properties of the host.
My proposed path is to attach a data attribute to the host and have shadow script listen for changes to it and then update elements inside the shadowRoot. I am aware that it is possible to use javascript to access elements in the shadowRoot and change them, but my desire is to experiment in modularization and reusability. I ultimately would like for this component to be reusable and react to changes in the hosts attributes.

A: I found a solution and figured I would share. It is likely not yet compatible with all browsers, but such is life.
In my script, I have a iffe/monad that processes my custom html tags, creating shadow roots and clones of a template as content. One of the arguments for the monad is the array of nodes that match my custom tag. While looping over them, I create a MutationObserver to watch for a particular attribute change in order to use the created shadow root in a closure.
            (function (tags, template) {
            Array.prototype.forEach.call(hexagons, function (v, k) {
                    var shadow = v.createShadowRoot();
                    shadow.appendChild(template.content.cloneNode(true));

                    /* mutation observer */
                    var observer = new MutationObserver(function (mutations) {
                            mutations.forEach(function (mutation) {
                                shadow.querySelector('.seconds')
                                   .innerText(
                                      mutation.target.getAttribute(mutation.attributeName)
                                   )
                            });
                        });
                    observer.observe(v, { attributes: true, attributeFilter: ['bgcolor'] });
                }
            );
        }(document.querySelectorAll('time'), document.querySelector('template#time')));

The above works in Chrome and Firefox latest. I will keep looking for mroe browser friendly solutions.


text:
Q: CSS: Can't get text in relative-positioned div to center align? The text in my TextWrapper div won't center align. text-align: center worked when I didn't use position: relative and : absolute on them, but they are necessary for my jQuery code. How do I get the text to center align in the div?

A: Absolute positioning removes the default behavior of block elements to fill the width of their parent element. Either add width: 100% or left: 0; right: 0; to the absolutely positioned divs.

$(function(){
 $("#TextWrapper div:gt(0)").hide();
 setInterval(function(){
  var current = $('#TextWrapper div:visible');
  var next = current.next().length ? current.next() : $('#TextWrapper div:eq(0)');
  current.fadeOut(500);
  next.fadeIn(500);
 }, 1000);
});
.Border {
 border: 1px solid black;
 display: inline-flex;
 height: 110px;
}
#ImgAndText {
 text-align: center;
}
.Img {
 width: 75px;
 height:75px;
}
#TextWrapper {
 font-family: Helvetica;
 font-size: 13px;
 padding: 5px 5px 5px 5px;
 position: relative;
 text-align: center;
}
#TextWrapper div {
 position: absolute;
 text-align: center;
    left: 0;
    right: 0;
}

Text

Other


text:
Q: make: *** No targets specified and no makefile found. Stop I got this while installing gnome-calender on Ubuntu 14.04 LTS.
home@JP-PC:~/Documents/gnome-calendar-3.22.1$ ./configure
checking whether make supports nested variables... yes
checking for a BSD-compatible install... /usr/bin/install -c
checking whether build environment is sane... yes
checking for a thread-safe mkdir -p... /bin/mkdir -p
checking for gawk... gawk
checking whether make sets $(MAKE)... yes
checking whether UID '1000' is supported by ustar format... yes
checking whether GID '1000' is supported by ustar format... yes
checking how to create a ustar tar archive... gnutar
checking whether to enable maintainer-specific portions of Makefiles...     yes
checking whether NLS is requested... yes
checking for intltool >= 0.40.6... 0.50.2 found
checking for intltool-update... /usr/bin/intltool-update
checking for intltool-merge... /usr/bin/intltool-merge
checking for intltool-extract... /usr/bin/intltool-extract
checking for xgettext... /usr/bin/xgettext
checking for msgmerge... /usr/bin/msgmerge
checking for msgfmt... /usr/bin/msgfmt
checking for gmsgfmt... /usr/bin/msgfmt
checking for perl... /usr/bin/perl
checking for perl >= 5.8.1... 5.18.2
checking for XML::Parser... ok
checking for pkg-config... /usr/bin/pkg-config
checking pkg-config is at least version 0.22... yes
checking for _NL_TIME_FIRST_WEEKDAY... checking for style of include used              by make... GNU
checking for gcc... gcc
checking whether the C compiler works... yes
checking for C compiler default output file name... a.out
checking for suffix of executables...
checking whether we are cross compiling... no
checking for suffix of object files... o
checking whether we are using the GNU C compiler... yes
checking whether gcc accepts -g... yes
checking for gcc option to accept ISO C89... none needed
checking whether gcc understands -c and -o together... yes
checking dependency style of gcc... gcc3
yes
checking for library containing strerror... none required
checking how to run the C preprocessor... gcc -E
checking for grep that handles long lines and -e... /bin/grep
checking for egrep... /bin/grep -E
checking for ANSI C header files... yes
checking build system type... i686-pc-linux-gnu
checking host system type... i686-pc-linux-gnu
checking how to print strings... printf
checking for a sed that does not truncate output... /bin/sed
checking for fgrep... /bin/grep -F
checking for ld used by gcc... /usr/bin/ld
checking if the linker (/usr/bin/ld) is GNU ld... yes
checking for BSD- or MS-compatible name lister (nm)... /usr/bin/nm -B
checking the name lister (/usr/bin/nm -B) interface... BSD nm
checking whether ln -s works... yes
checking the maximum length of command line arguments... 1572864
checking how to convert i686-pc-linux-gnu file names to i686-pc-linux-gnu         format... func_convert_file_noop
checking how to convert i686-pc-linux-gnu file names to toolchain          format... func_convert_file_noop
checking for /usr/bin/ld option to reload object files... -r
checking for objdump... objdump
checking how to recognize dependent libraries... pass_all
checking for dlltool... no
checking how to associate runtime and link libraries... printf %s\n
checking for ar... ar
checking for archiver @FILE support... @
checking for strip... strip
checking for ranlib... ranlib
checking command to parse /usr/bin/nm -B output from gcc object... ok
checking for sysroot... no
checking for a working dd... /bin/dd
checking how to truncate binary pipes... /bin/dd bs=4096 count=1
checking for mt... mt
checking if mt is a manifest tool... no
checking for sys/types.h... yes
checking for sys/stat.h... yes
checking for stdlib.h... yes
checking for string.h... yes
checking for memory.h... yes
checking for strings.h... yes
checking for inttypes.h... yes
checking for stdint.h... yes
checking for unistd.h... yes
checking for dlfcn.h... yes
checking for objdir... .libs
checking if gcc supports -fno-rtti -fno-exceptions... no
checking for gcc option to produce PIC... -fPIC -DPIC
checking if gcc PIC flag -fPIC -DPIC works... yes
checking if gcc static flag -static works... yes
checking if gcc supports -c -o file.o... yes
checking if gcc supports -c -o file.o... (cached) yes
checking whether the gcc linker (/usr/bin/ld) supports shared libraries...       yes
checking whether -lc should be explicitly linked in... no
checking dynamic linker characteristics... GNU/Linux ld.so
checking how to hardcode library paths into programs... immediate
checking whether stripping libraries is possible... yes
checking if libtool supports shared libraries... yes
checking whether to build shared libraries... yes
checking whether to build static libraries... no
checking langinfo.h usability... yes
checking langinfo.h presence... yes
checking for langinfo.h... yes
checking locale.h usability... yes
checking locale.h presence... yes
checking for locale.h... yes
checking for string.h... (cached) yes
checking for floor... no
checking for memset... yes
checking for nl_langinfo... yes
checking for pow... no
checking for setlocale... yes
checking for strstr... yes
checking for pkg-config... (cached) /usr/bin/pkg-config
checking pkg-config is at least version 0.16... yes
checking for glib-mkenums... /usr/bin/glib-mkenums
checking whether C compiler accepts -Werror=unknown-warning-option... no
checking whether C compiler accepts -fno-strict-aliasing... yes
checking whether C compiler accepts -Wall... yes
checking whether C compiler accepts -Wextra... yes
checking whether C compiler accepts -Wundef... yes
checking whether C compiler accepts -Wnested-externs... yes
checking whether C compiler accepts -Wwrite-strings... yes
checking whether C compiler accepts -Wpointer-arith... yes
checking whether C compiler accepts -Wmissing-declarations... yes
checking whether C compiler accepts -Wmissing-prototypes... yes
checking whether C compiler accepts -Wstrict-prototypes... yes
checking whether C compiler accepts -Wredundant-decls... yes
checking whether C compiler accepts -Wno-unused-parameter... yes
checking whether C compiler accepts -Wno-missing-field-initializers... yes
checking whether C compiler accepts -Wdeclaration-after-statement... yes
checking whether C compiler accepts -Wformat=2... yes
checking whether C compiler accepts -Wold-style-definition... yes
checking whether C compiler accepts -Wcast-align... yes
checking whether C compiler accepts -Wformat-nonliteral... yes
checking whether C compiler accepts -Wformat-security... yes
checking whether C compiler accepts -Wsign-compare... yes
checking whether C compiler accepts -Wstrict-aliasing... yes
checking whether C compiler accepts -Wshadow... yes
checking whether C compiler accepts -Winline... yes
checking whether C compiler accepts -Wpacked... yes
checking whether C compiler accepts -Wmissing-format-attribute... yes
checking whether C compiler accepts -Wmissing-noreturn... yes
checking whether C compiler accepts -Winit-self... yes
checking whether C compiler accepts -Wredundant-decls... (cached) yes
checking whether C compiler accepts -Wmissing-include-dirs... yes
checking whether C compiler accepts -Wunused-but-set-variable... yes
checking whether C compiler accepts -Warray-bounds... yes
checking whether C compiler accepts -Wimplicit-function-declaration... yes
checking whether C compiler accepts -Wreturn-type... yes
checking whether C compiler accepts -Wswitch-enum... yes
checking whether C compiler accepts -Wswitch-default... yes
checking whether C compiler accepts -Wno-error=unused-parameter... yes
checking whether C compiler accepts -Wno-error=missing-field-    initializers... yes
checking whether C compiler accepts -Werror=unknown-warning-option...     (cached) no
checking whether the linker accepts -Wl,--no-as-needed... yes
checking for CALENDAR... no
configure: error: Package requirements (
              gmodule-export-2.0
              gio-2.0 >= 2.43.4
              glib-2.0 >= 2.43.4
              goa-1.0 >= 3.2.0
              gtk+-3.0 >= 3.21.6
              libecal-1.2 >= 3.13.90
              libedataserver-1.2 >= 3.17.1
              libedataserverui-1.2 >= 3.17.1
              libical >= 1.0
              gsettings-desktop-schemas >= 3.21.2) were not met:

Requested 'gio-2.0 >= 2.43.4' but version of GIO is 2.40.2
Requested 'glib-2.0 >= 2.43.4' but version of GLib is 2.40.2
No package 'goa-1.0' found
Requested 'gtk+-3.0 >= 3.21.6' but version of GTK+ is 3.10.8
No package 'libecal-1.2' found
No package 'libedataserver-1.2' found
No package 'libedataserverui-1.2' found
No package 'libical' found
No package 'gsettings-desktop-schemas' found

Consider adjusting the PKG_CONFIG_PATH environment variable if you
installed software in a non-standard prefix.

Alternatively, you may set the environment variables CALENDAR_CFLAGS
and CALENDAR_LIBS to avoid the need to call pkg-config.
See the pkg-config man page for more details.

Now after "./configure" running make command shows
"make: *** No targets specified and no makefile found.  Stop."
home@JP-PC:~/Documents/gnome-calendar-3.22.1$ make
make: *** No targets specified and no makefile found.  Stop.
home@JP-PC:~/Documents/gnome-calendar-3.22.1$

I read on some other thread to first run "make clean" then "./configure".
But "make clean" show this error.
home@JP-PC:~/Documents/gnome-calendar-3.22.1$ make clean
make: *** No rule to make target `clean'.  Stop.

So can anyone help me to solve this.
Thank you

A: you have a configure error, you need to fulfil the dependencies. as stated at the end of ./configure output


text:
Q: How can I downgrade Homebrew to an older version? Currently I have the latest version 2.2.17, I want to downgrade to version 2.2.12.
Brew does not have a downgrade option, just an upgrade. Is the process to uninstall brew and re-install it again?

A: If you used the normal installation way via the install script:
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"

Then take a look at the brew install script (it has its own repo).
It downloads the actual Homebrew repo to /usr/local/Homebrew.
...
HOMEBREW_PREFIX="/usr/local"
HOMEBREW_REPOSITORY="/usr/local/Homebrew"
...

BREW_REPO="https://github.com/Homebrew/brew"
...

ohai "Downloading and installing Homebrew..."
(
  cd "${HOMEBREW_REPOSITORY}" >/dev/null || return

  # "git remote add" will fail if the remote is defined in the global config
  execute "git" "config" "remote.origin.url" "${BREW_REPO}"
  execute "git" "config" "remote.origin.fetch" "+refs/heads/*:refs/remotes/origin/*"
  ...

  execute "ln" "-sf" "${HOMEBREW_REPOSITORY}/bin/brew" "${HOMEBREW_PREFIX}/bin/brew"
  ...
}
...

==> This script will install:
/usr/local/bin/brew
/usr/local/share/doc/homebrew
/usr/local/share/man/man1/brew.1
/usr/local/share/zsh/site-functions/_brew
/usr/local/etc/bash_completion.d/brew
/usr/local/Homebrew
...

The script installs the latest copy of the Homebrew repo. So the answer to "Is the process to uninstall brew and re-install it again?" would be a "NO". Instead, install it first normally, and then after, go over to /usr/local/Homebrew and checkout the version you want.
~$ cd /usr/local/Homebrew

Homebrew$ brew --version
Homebrew 2.3.0
Homebrew/homebrew-core (git revision d41d92; last commit 2020-05-29)

Homebrew$ git fetch --tags
Homebrew$ git checkout 2.2.12
Note: switching to '2.2.12'.

You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by switching back to a branch.

If you want to create a new branch to retain commits you create, you may
do so (now or later) by using -c with the switch command. Example:

  git switch -c <new-branch-name>

Or undo this operation with:

  git switch -

Turn off this advice by setting config variable advice.detachedHead to false

HEAD is now at 2ae26808a Merge pull request #7301 from Bo98/cmake-sdkroot

Homebrew$ brew --version
Homebrew 2.2.12

Homebrew$ cd /usr/local/bin
bin$ ./brew --version
Homebrew 2.2.12
Homebrew/homebrew-core (git revision d41d92; last commit 2020-05-29)

I recommend doing a brew doctor after just to make sure everything's still OK.
Then, unfortunately, Homebrew always auto-updates itself every time you install something. So it will always update the repo at /usr/local/Homebrew up again to the latest version. You can disable that by exporting HOMEBREW_NO_AUTO_UPDATE as mentioned here https://github.com/Homebrew/brew/issues/1670.
~$ export HOMEBREW_NO_AUTO_UPDATE=1
~$ brew install python@3.8

You'll need to create an alias or auto-export that env var to your bash_profile (or whatever is the equivalent for the terminal you use), so that it takes effect every time you use brew.


text:
Q: Python for loop with condition I am quite new to Python (have a C++ background). I have a function in my Python code that returns an array of some objects (on which I don't have any control) like below:
def _get_object_array():
    object_array[]
    # Magically get array contents from somewhere
    # The objects have some fields like id, name etc.
    return object_array

Then in another function I call _get_object_array() to retrieve only the id's of the objects returned.
What I have is following:
id_array = []
id_array = [x.id for x in _get_object_array()] #<--

But I don't want the ids of all the objects in the returned array. Instead I only want to store the ids for array elements which meet some criteria (e.g. id is an even number?)
Is there a way I can do that in the same line marked with <-- like below (which btw is just a pseudo code)?
id_array = [if x.id % 2 == 0: x.id for x in _get_object_array()]

Thanks in advance.
/R

A: Yep: same words, you just got the syntax backwards.
id_array = [x.id for x in _get_object_array() if x.id % 2 == 0]

List comprehensions are amazing, and can do a lot more work than most people realise; have a read of the relevant PEP.

A: Yes, and you were very close:
id_array = [x.id for x in _get_object_array() if x.id % 2 == 0]


text:
Q: Project Euler problems which are not so math oriented I have started to solve PE problems a year ago, but within this year, I realised, that finding a problem which would be fun for me to think of is quite hard. I would like to solve problems more related with classic algorithms (graph theory, game theory, dynamic programming, divide and conquer...) and not so much of number theory and geometry (althought I like them too, but there was so much of them so far).
Any tips? (first 50 problems already solved and second half of first hudnred almost too, so I would like to get some tips for problems from 100-200. 200+ are quite hard for me, I think)

A: Try the following Project Euler questions:

*

*185

*186

*212

*215

*237

A: 314 - The Mouse on the Moon

A: There is PE page that lists details of all problems on one page, which may make it easier to find problems that suit your interests.

A: From 100+, intersected with the ones that I've solved, those that might be interesting to you are:

*

*#107 (graph theory)

*#114, #115, #116, #117 (combinatorics, dynamic programming)

*#122 (some algebra, but hardly any)

*#206 (numerics, but hardly number theory)


text:
Q: How to NOT delete existing translations with "react-intl-translations-manager"? I use React-Intl in my app and it works great, but to be easier to manage new keys to translate I started using "react-intl-translations-manager".
My problem is that some of my translations are used through a notification system and the babel extractor don't recognize them because it's outside of his scan scope.
So when I run "react-intl-translations-manager" it deletes all the keys relatives to notifications and other non-scanned translations.
Here is my question: is there any method to "say" to "react-intl-translations-manager" that it's forbidden to delete those keys ?
I tried multiple solutions including whitelists and other but nothing is working.
Here is my translationRunner.js (the configuration file)
const manageTranslations = require('react-intl-translations-manager').default;

 manageTranslations({
    messagesDirectory: 'src/messages/',
    translationsDirectory: 'src/locales/',
    languages: ['en_GB', 'fr_FR']
 });

A: There are two ways to do this. One is to use hooks and another way is to override the module where deletion of the actual code happens.
To do the same we can override the getLanguageReport module from react-intl-translations-manager/dist/getLanguageReport
getLanguageReport = require('react-intl-translations-manager/dist/getLanguageReport');
getLanguageReport.original = getLanguageReport.default
getLanguageReport.default = function(defaultMessages, languageMessages, languageWhitelist) {
    data = getLanguageReport.original(defaultMessages, languageMessages, languageWhitelist)
    // this whitelist ids can be read through a config file as well
    whitelisted_id = ['helloworld2', 'helloworld']
    deleted = data.deleted;
    re_add = []
    for (var i=0; i < deleted.length; ) {
        if (whitelisted_id.indexOf(deleted[i].key)>=0) {
            // we are removing a record so lets not increment i
            removed_element = deleted.splice(i,1)[0];
            data.fileOutput[removed_element.key] = removed_element.message;
        } else {
            i++;
        }
    }
    return data;
}
 const manageTranslations = require('react-intl-translations-manager').default;

manageTranslations({
    messagesDirectory: 'build/messages/src/extracted/',
    translationsDirectory: 'src/translations/locales/',
    languages: ['de'] // Any translation --- don't include the default language
}
);

This method works fine and will keep the helloworld2 message even if it is not there in new code.
Hooks approach
In this we use the hook reportLanguage and override it to change the data
const manageTranslations = require('react-intl-translations-manager').default;
const writeFileSync = require('fs').writeFileSync
const stringify = require('react-intl-translations-manager/dist/stringify').default;

stringifyOpts = {
    sortKeys: true,
    space: 2,
    trailingNewline: false,
  };

manageTranslations({
    messagesDirectory: 'build/messages/src/extracted/',
    translationsDirectory: 'src/translations/locales/',
    languages: ['de'], // Any translation --- don't include the default language
    overrideCoreMethods: {
        reportLanguage: function(langResults) {
            data = langResults.report;
            // this whitelist ids can be read through a config file as well
            whitelisted_id = ['helloworld2', 'helloworld']
            deleted = data.deleted;
            re_add = []
            for (var i=0; i < deleted.length; ) {
                if (whitelisted_id.indexOf(deleted[i].key)>=0) {
                    // we are removing a record so lets not increment i
                    removed_element = deleted.splice(i,1)[0];
                    data.fileOutput[removed_element.key] = removed_element.message;
                } else {
                    i++;
                }
            }
            // original definition of reportLanguage from manageTranslations.js
            // unfortunately the original core method is not exposed for us to re-use
            // so we need to copy the code again
            if (
                !langResults.report.noTranslationFile &&
                !langResults.report.noWhitelistFile
              ) {
                // printers.printLanguageReport(langResults);

                writeFileSync(
                  langResults.languageFilepath,
                  stringify(langResults.report.fileOutput, stringifyOpts)
                );
                writeFileSync(
                  langResults.whitelistFilepath,
                  stringify(langResults.report.whitelistOutput, stringifyOpts)
                );
              } else {
                if (langResults.report.noTranslationFile) {
                  printers.printNoLanguageFile(langResults);
                  writeFileSync(
                    langResults,
                    stringify(langResults.report.fileOutput, stringifyOpts)
                  );
                }

                if (langResults.report.noWhitelistFile) {
                  printers.printNoLanguageWhitelistFile(langResults);
                  writeFileSync(
                    langResults.whitelistFilepath,
                    stringify([], stringifyOpts)
                  );
                }
            }
        }
    }
});


text:
Q: Adding a tooltip to a IXLCell in a IXLWorksheet What is the syntax to add a tooltip to a IXLCell in a IXLWorksheet?
I'm trying this approach but it isn't working..........
    Dim xlDoc As New XLWorkbook()
    xlDoc.AddWorksheet(filename)
    Dim xlWS As IXLWorksheet = xlDoc.Worksheets(0)
    xlWS.Range("A1", "I177").Style.Font.SetFontName("Arial")
    xlWS.Range("A1", "I177").Style.Font.SetFontSize(10)
    xlWS.Range("A1", "I177").Style.Fill.BackgroundColor = XLColor.FromArgb(253, 233, 217)
    xlWS.Protect().SetSelectLockedCells(False)
    Dim rowInt As Integer = 5
    While rowInt <= 177
        xlWS.Rows(rowInt).Height = 14.25
        xlWS.Rows(rowInt).Style.Alignment.SetVertical(XLAlignmentVerticalValues.Center)
        rowInt = rowInt + 1
    End While

xlWS.Cell("H30").Hyperlink.Tooltip = "Tooltip text string goes here"

A: This works but there's probably a more elegant way of doing it like wrapping the comment box size rather than setting the dimensions manually
    xlWS.Cell("H30").Comment.Style.Size.SetHeight(50)
    xlWS.Cell("H30").Comment.Style.Size.SetWidth(50)
    xlWS.Cell("H30").Comment.AddText("Tooltip text 1")
    xlWS.Cell("H30").Comment.AddNewLine()
    xlWS.Cell("H30").Comment.AddNewLine()
    xlWS.Cell("H30").Comment.AddText("Tooltip text 2").Bold = True


text:
Q: 2D Slot machine type animation on GTK+ I have written a basic slot machine simulation using C and GTK under Linux. The slot machine is 5 reels with each reel having 3 symbols. To "animate" the spinning action I'm just using an animated GIF with an array 3,5 of GtkImages.
I'd like to actually have it look like a proper slot machine where a vertical animation is done for each reel. I would imagine that I'd need to build a pixmap or pixbuf from the symbols on the reel, use g_timer_add() to change the visiable portion of the pixmap on the GtkImage. I'm new to Gtk+ so if anybody has some simple example of this type of animation or good documentation, I would be forever grateful.
Thank you.

A: Use a GtkDrawingArea instead of a GtkImage, so you can draw there as you want. Put all your possible images in a vertical PNG image, as if you had unrolled the reels. Then load this into a pixbuf, create a surface for it using cairo. You'll just have to draw a small subset of that big image using cairo, which you can refer to by a vertical offset to that big image. Use a timer with g_timer_add to make it refresh with a enough frames per second (calculate the speed you need). Don't take the timer callback for granted, there may be delays in the firing of the callback. Best is achieved by using a GTimer, starting it a the time you want to make the reels spin, and in the g_timer_add callback, measure the time elapsed since you started the GTimer. This will allow you to calculate the offset to your image.


text:
Q: How to query for installed "packaged COM" extension points I work on a plugin-based application that is currently scanning the Windows registry for compatible COM servers that expose certain "Implemented Categories" entries. This works well for "regular" COM servers installed through MSI installers.
However, I'm now facing a problem with COM servers installed through MSIX installers that expose COM extension points through the "Packaged COM" catalog as described in https://blogs.windows.com/windowsdeveloper/2017/04/13/com-server-ole-document-support-desktop-bridge/ . These COM servers can still be instantiated through CoCreateInstance, but RegOpenKey/RegEnumKey searches aren't able to detect their presence.
I'm not sure how to approach this problem. The best outcome would be some sort of Windows API for querying the "Packaged COM" catalog for installed COM servers that I can run in addition to the registry search. However, I don't know if that even exist? I'm also open for other suggestions, as long as they still allows my application to dynamically detect the presence of new COM-based plugins.

A: PLEASE DISREGARD THIS ANSWER. There's a better answer based on ICatInformation::EnumClassesOfCategories below.
Answering myself with sample code to query the "Packaged COM" catalog for installed COM servers. Based on suggestion from @SimonMourier.
using System.Collections.Generic;
using System.IO;

/** Use Target Framework Moniker as described in https://learn.microsoft.com/en-us/windows/apps/desktop/modernize/desktop-to-uwp-enhance */
class PackagedComScan {
    static void Main(string[] args) {
        var packageManager = new Windows.Management.Deployment.PackageManager();
        // this call require the "packageQuery" capability if called from a UWP app (add <rescap:Capability Name="packageQuery" /> to the appxmanifest)
        IEnumerable<Windows.ApplicationModel.Package> my_packages = packageManager.FindPackagesForUser("");

        foreach (var package in my_packages) {
            try {
                ParseAppxManifest(package.InstalledLocation.Path + @"\AppxManifest.xml");
            } catch (FileNotFoundException) {
                // Installed package missing from disk. Can happen after deploying UWP builds from Visual Studio.
            }
        }
    }

    static void ParseAppxManifest(string manifest_path) {
        var doc = new System.Xml.XmlDocument();
        using (var fs = new FileStream(manifest_path, FileMode.Open, FileAccess.Read, FileShare.Read))
            doc.Load(fs);

        var nsmgr = new System.Xml.XmlNamespaceManager(doc.NameTable);
        nsmgr.AddNamespace("a", "http://schemas.microsoft.com/appx/manifest/foundation/windows10"); // default namespace
        nsmgr.AddNamespace("com", "http://schemas.microsoft.com/appx/manifest/com/windows10");

        // detect exported COM servers
        var nodes = doc.SelectNodes("/a:Package/a:Applications/a:Application/a:Extensions/com:Extension/com:ComServer/com:ExeServer/com:Class/@Id", nsmgr);
        foreach (System.Xml.XmlNode node in nodes)
            System.Console.WriteLine("Exported COM CLSID: {0}", node.Value);
    }
}

This is admittedly a bit ad-hoc since it relies on parsing the AppxManifest.xml files. Still, it seems to get the job done. Please note that UWP applications that runs within sandboxed AppContainer processes only seem to have read access to some of the AppxManifest.xml files, and not all. The code therefore only works for "regular" Win32 or .Net processes.

A: Answering myself with sample code to query all installed COM servers, including the "Packaged COM" catalog, using ICatInformation::EnumClassesOfCategories. Based on suggestion by Aditi_Narvekar:
#include <atlstr.h>
#include <vector>

static void CHECK(HRESULT hr) {
    if (FAILED(hr))
        abort(); // TODO: More graceful error handling
}

/** Return COM classes that implement any of the provided "Implemented Categories". */
inline std::vector<CLSID> GetClassesWithAnyOfCategories(std::vector<CATID> impl_categories) {
    CComPtr<ICatInformation> cat_search;
    CHECK(cat_search.CoCreateInstance(CLSID_StdComponentCategoriesMgr));

    CComPtr<IEnumGUID> class_list;
    CHECK(cat_search->EnumClassesOfCategories((ULONG)impl_categories.size(), impl_categories.data(), -1, nullptr, &class_list));

    std::vector<CLSID> app_clsids;
    app_clsids.reserve(64);
    for (;;) {
        CLSID cur_cls = {};
        ULONG num_read = 0;
        CHECK(class_list->Next(1, &cur_cls, &num_read));
        if (num_read == 0)
            break;

        // can also call ProgIDFromCLSID to get the ProgID
        // can also call OleRegGetUserType to get the COM class name

        app_clsids.push_back(cur_cls);
    }

    return app_clsids;
}


text:
Q: java-script input field validation I have a field called price, now how to validate this field by java script? It will take only integer value and dot. It may take decimal point or not.
   e.g 200,200.00 both are valid.
How shall I do that?

A: There are many ways to achieve this.
Without the use of any 3rd party libraries i would recommend using regular expressions.
A possible pattern used to validate price would be
\d[\d\,\.]+

here is a tutorial on using regular expressions to validate fields in java-script
Tutorial
Hope this helps


text:
Q: Java client/server communication, what I need to learn I'm new to Java Networking (not Java), I trying to develop a client application that connect to a server, so the server can receive database table and store them online, activate the application: when the user enter activation information, the application connect to the server, send those information, and then the server reply. what I need to know is what technologies/classes can acheive this?? what I need to learn?? is it Java RMI or {InetAdress, URL/URI, URLConnection, Socket, ServerSocket, UDP..} Stuff or what exaclty ??
I'm currently reading Java Network Programming, Elliotte Rusty Harold, is this what I need to learn??
I developed a JavaFX 8 application and it's out there, it's free, now I'm trying to develop a payed version, and one of the thing I will add is client/server communication. Thanks a lot

A:
what I need to know is what technologies/classes can achieve this??
  what I need to learn?? is it Java RMI or {InetAdress, URL/URI,
  URLConnection, Socket, ServerSocket, UDP..} Stuff or what exactly ??

As per the given requirement, it'd be enough for you to learn coding with Java Socket Programming. You don't need a URL/URI unless you're going to connect it to the internet.
And, you should start with sockets/server-sockets, then TCP/UDP is easy to decide based upon the requirement of the application. If the data is critical, you should go for TCP, which is slower as compared to UDP, which in fact doesn't guarantee the packets will arrive in order, or, even if they'd arrive or not. So, you could go with DatagramSocket/Packet OR normal Socket based on whether you use UDP/TCP.
Talking about Java RMI, that is a way too old technology. But, it is good to know this technology. That technology could be used to implement distributed application programming, so obviously you can achieve even the Client-Server communication with that. But, that's somewhat imprecise to use RMI for such an easy task.
My personal suggestion --- Learn some basic networking with the book mentioned below by the author Esmond Pitt, who is among us even here as a fellow member of this community.

I'm currently reading Java Network Programming, Elliotte Rusty Harold,
  is this what I need to learn??

I also started learning Java Network programming with the same book,but, the author has made the book too complex for a beginner.It is OK to continue if you want to make a career in Java Network Programming. If not, then you should start with some easier text book like Fundamental Networking in Java, though this book is somewhat outdated and still revolves around JDK 1.5 as no new publishing has been done for this book after 2006. That is an easier to read book, and even the author of the book(EJP) is active here on Stack Overflow. You shouldn't get dumbstrucked if he answers your questions here. BTW, I got to know about his books very recently and I enjoyed having a review of that book.


text:
Q: undefined method `original_filename' for Upload Can't seem to identify why I would be getting a undefined method original_filename, trying to do a file upload that checks the file extensions. Any ideas where im going wrong here
class SpreadsheetTagService
  include Roo

  def initialize(uploaded_file)
    open_spreadsheet(File.new(uploaded_file.tempfile.path))
    read_file(open_spreadsheet)
  end

  private
    def read_file(file)
      @spreadsheet = open_spreadsheet(file)

      @spreadsheet.each_with_pagename do |name,sheet|
        Rails.logger.debug( sheet )
      end
    end

    def open_spreadsheet(file)
      case File.extname(file.path)
        when ".csv" then Csv.new(file.path, nil, :ignore)
        when ".xls" then Excel.new(file.path, nil, :ignore)
        when ".xlsx" then Excelx.new(file.path, nil, :ignore)
        else raise "Unknown file type: #{file.original_filename}"
      end
    end
end

Controller
class SpreadsheetServiceController < ApplicationController

  def new
  end

  def create
    parser = SpreadsheetTagService.new(params[:spreadsheet][:file])

    respond_to do |format|
      format.all {render :json => 'Done'}
    end
  end
end

A: This one worked for me, removed the #{file.original_filename} from raise exception, modified the code so the file extension is saved properly:
class SpreadsheetTagService
  include Roo

  def initialize(uploaded_file)
    ext = File.extname(uploaded_file.original_filename)
    @tmp_destination = "#{Rails.root}/tmp/tag-import#{ext}"
    @file_path = save_file_to_tmp(uploaded_file)
    @file = File.new(@file_path)
    read_file(@file)
  end

  private
  def save_file_to_tmp(uploaded_file)
    FileUtils.mv(uploaded_file.tempfile, @tmp_destination )
    @tmp_destination
  end

  def read_file(file)
    @spreadsheet = open_spreadsheet(file)
    @spreadsheet.each_with_pagename do |name,sheet|
      Rails.logger.debug( sheet )
    end
  end

  def open_spreadsheet(file)
    case File.extname(file.path)
    when ".csv" then Csv.new(file.path, nil, :ignore)
    when ".xls" then Excel.new(file.path, nil, :ignore)
    when ".xlsx" then Excelx.new(file.path, nil, :ignore)
    else raise "Unknown file type"
    end
  end
end


text:
Q: Variables not being pulled from GET I have an sql statement that uses php variables, but they don't seem to be getting pulled from the URL through a GET. Here are my variables:
$firstname = $_GET['firstname'];
$lastname = $_GET['lastname'];
$firstseason = $_GET['firstseason'];

Then I have my URL:
np2pp2.php?firstname=t9&lastname=t9&firstseason=1900

When my SQL statement runs, I get this error:
Error: You have an error in your SQL syntax; check the manual that corresponds
to your MySQL server version for the right syntax to use near 'SELECT playerID
FROM players WHERE firstname='' AND lastname='' AND firstseason=' at line 2

So it looks like it's not pulling the variables, but I don't know why. Any help is appreciated, thanks.
EDIT: I should have added the SQL query:
$sql2="INSERT INTO playerRegSeason
       (playerID, year, teamID, gp, minutes, pts, oreb, dreb, reb,
        asts, stl, blk, turnover, pf, fga, fgm, fta, ftm, tpa, tpm)

       SELECT playerID, $year, '$team', $gp, $minutes, $pts, $oreb,
         $dreb, $reb, $asts, $stl, $blk, $turnover, $pf, $fga, $fgm,
         $fta, $ftm, $tpa, $tpm FROM players WHERE firstname='$firstname'
       AND lastname='$lastname' AND firstseason=$firstseason";

A: when including variables in your query always put inside curly brackets like:
select * from table where year = '{$year}'

see if that helps
also if you don't you code is much more inject-able.

A: First, double-check that the $_GET variables are populating by throwing an if statement up top:
if ($firstname != "" && $lastname != "" && $firstseason != "") {
    // do SQL
} else {
    // output error
}

If that shows you the error, try:

*

*echoing the variables

*echoing the $_GET items directly

*using $_REQUEST instead of $_GET

Also, your SQL may need quotes around '$firstseason'.

A: Try this:
$sql2="INSERT INTO playerRegSeason
       (playerID, year, teamID, gp, minutes, pts, oreb, dreb, reb,
        asts, stl, blk, turnover, pf, fga, fgm, fta, ftm, tpa, tpm)
       SELECT playerID, year, team, gp, minutes, pts, oreb, dreb, reb,
       asts, stl, blk, turnover, pf, fga, fgm, fta, ftm, tpa, tpm
       FROM players WHERE firstname='".$firstname."'
       AND lastname='".$lastname."' AND firstseason='".$firstseason."'";

If the values in the select statement are php variables you need to use ''.
SELECT playerID, '".$year."', '".$team."', '".$gp."', '".$minutes."', '".$pts."'


text:
Q: ERR 403 - (User Rate Limit Exceeded) when listing files in V3 I  want to get the files name from one folder Using  Files.List using the Google Drive v3 API and the Google PHP Client library.
I don't want to check the moved files to trash from that folder, so I used Drive API function getExplicitlyTrashed() to find what are the files in trash to filter those files
Latest release of Google PHP client library: 1.1.7
Google Drive V3 file: https://gist.github.com/bshaffer/9bb2cdccd315880ab52f
Also used src/Google/Http/REST.php in Drive v3 only updated as per below post reply:  Download CSV file using Google Drive V3(V2 works perfect) throws error 403
Sample Script Using Drive V3 method Files: List - List files from Folder not in trash
<?php
error_reporting(0);
set_include_path( get_include_path() . PATH_SEPARATOR . 'Google' );
require_once 'Google/autoload.php';
require_once 'Google/Client.php';
require_once 'Google/Service/Drive.php';
$service=get_service_document();
$folderid="FOLDER_ID";
$list_files=GetAllFilesName($service,$folderid);
for($i=0;$i<count($list_files);$i++){
    $id= $list_files[$i][0];
    $name=$list_files[$i][1];
    echo 'ID:'.$id.'
NAME:'.$name.'
';
}

function GetAllFilesName($service,$folderid){
// v3 To check explicitly trashed function we shld use optional parameter
try{
            $optParams = array(
            'fields' =>'explicitlyTrashed'
        );
//Get list of files from folder
        $children1 = $service->files->listFiles(array(
            'q' => "'$folderid' in parents "));
        $filenamelist=array();
        foreach ($children1 as $child) {
                if ($service->files->get($child->getId(), $optParams)->getExplicitlyTrashed() == 1) continue;
                $fileid = $service->files->get($child->getId())->id;
                $filename = $service->files->get($child->getId())->name;
                $filenamelist[] = [$fileid,$filename];
              }
        return $filenamelist;
    }
    catch (Exception $ex) {
        echo $ex->getMessage();//$filenamelisterr;
    }
}
//function to get service
function get_service_document(){
    $userstamp='user@example.com';
     $driveService =buildServiceDrive($userstamp,"SERVICE-ACCOUNT","https://www.googleapis.com/auth/drive","key.p12");
    return $driveService;
}
//building service
function buildServiceDrive($userEmail,$service_id,$scope,$service_filename) {
    $key = file_get_contents($service_filename);
    $auth = new Google_Auth_AssertionCredentials(
        $service_id,
        array($scope),
        $key);
    $auth->sub = $userEmail;
    $client = new Google_Client();
    $client->setAssertionCredentials($auth);
    return new Google_Service_Drive($client);
}

My script could not list all files in that folder constantly. Each time calling some time working some time i m getting this below issue
Response:

2.Sample Script Using Drive V2 method Files: List - List files from Folder not in trash
Using Drive v2, my script working fine, I didn't get any 403 issue.
<?php
set_include_path( get_include_path() . PATH_SEPARATOR . 'GoogleV2' );
require_once 'GoogleV2/autoload.php';
require_once 'GoogleV2/Client.php';
require_once 'GoogleV2/Service/Drive.php';

$service=get_service_document();
$folderid="FOLDER-ID";
$list_files=GetAllFilesName($service,$folderid);
for($i=0;$i<count($list_files);$i++){
    $id= $list_files[$i][0];
    $name=$list_files[$i][1];
    echo 'ID:'.$id.'
NAME:'.$name.'
';
}
//print_r($list_files);

function GetAllFilesName($service,$folderid){
    try{
        $children1 = $service->children->listChildren($folderid);
        $filenamelist=array();
        foreach ($children1->getItems() as $child) {
            if($service->files->get($child->getId())->getExplicitlyTrashed()==1)continue;
            $fileid=$service->files->get($child->getId())->id;
            $filename=$service->files->get($child->getId())->title;
            $filenamelist[]=[$fileid,$filename];
        }
        return $filenamelist;
    }
    catch(Exception $ex){
        Echo $ex->getMessage();
    }
}
//function to get service
function get_service_document(){
  $userstamp='user@example.com';
  $driveService =buildServiceDrive($userstamp,"SERVICE-ACCOUNT","https://www.googleapis.com/auth/drive","KEY.p12");
    return $driveService;
}
//building service
function buildServiceDrive($userEmail,$service_id,$scope,$service_filename) {
    $key = file_get_contents($service_filename);
    $auth = new Google_Auth_AssertionCredentials(
        $service_id,
        array($scope),
        $key);
    $auth->sub = $userEmail;
    $client = new Google_Client();
    $client->setAssertionCredentials($auth);
    return new Google_Service_Drive($client);
}

Response:

Using Exponential Back up, we modified the script, But still 403 error is thrown..
<?php
set_include_path( get_include_path() . PATH_SEPARATOR . 'Google' );
require_once 'Google/autoload.php';
require_once 'Google/Client.php';
require_once 'Google/Service/Drive.php';

$service=get_service_document();
$folderid="FOLDER_ID";
$list_files=GetAllFilesName($service,$folderid);
for($i=0;$i<count($list_files);$i++){
    $id= $list_files[$i][0];
    $name=$list_files[$i][1];
    echo 'ID:'.$id.'
NAME:'.$name.'
';
}

function GetAllFilesName($service,$folderid){
    try{
        $n=5;
        $optParams = array(
            'fields' =>'explicitlyTrashed'
        );
        $children1 = $service->files->listFiles(array(
            'q' => "'$folderid' in parents "));
        $filenamelist=array();

        foreach ($children1 as $child) {
            try {
                if ($service->files->get($child->getId(), $optParams)->getExplicitlyTrashed() == 1) continue;
                $fileid = $service->files->get($child->getId())->id;
                $filename = $service->files->get($child->getId())->name;
                $filenamelist[] = [$fileid,$filename];
            }
            catch (apiServiceException $ex) {
                if ($ex->getCode() == 403
                    && ($ex->getErrors()[0]["reason"] == "rateLimitExceeded"
                        || $ex->getErrors()[0]["reason"] == "userRateLimitExceeded"
                        || $ex->getErrors()[0]["reason"] =="dailyLimitExceeded")
                ) {
                    // Apply exponential backoff.
                    usleep((1 << $n) * 1000000 + rand(0, 1000000));
                }
            }
        }
        return $filenamelist;
    }
    catch (Exception $ex) {
        echo $ex->getMessage();//$filenamelisterr;
    }
}
//function to get service
function get_service_document(){
     $userstamp='user@example.com';
     $driveService =buildServiceDrive($userstamp,"SERVICE-ACCOUNT","https://www.googleapis.com/auth/drive","key.p12");
    return $driveService;
}
//building service
function buildServiceDrive($userEmail,$service_id,$scope,$service_filename) {
    $key = file_get_contents($service_filename);
    $auth = new Google_Auth_AssertionCredentials(
        $service_id,
        array($scope),$key);
    $auth->sub = $userEmail;
    $client = new Google_Client();
    $client->setAssertionCredentials($auth);
    return new Google_Service_Drive($client);
}

Plz help me is there any other way on  how to use exponential back off, May be I didn't get it correctly on the application of the Expo. Back Off? We are running around it for the past 3 weeks, plz help. We need to deploy Drive V3. Any of ur suggestion/tips/ help would be really a great help for us.
Thanks a lot in advance.

A: The Documentation tells you how to deal with this error message.

403: User Rate Limit Exceeded
The per-user limit from the Developer Console has been reached.
{  "error": {   "errors": [    {
      "domain": "usageLimits",
      "reason": "userRateLimitExceeded",
      "message": "User Rate Limit Exceeded"    }   ],   "code": 403,   "message": "User Rate Limit Exceeded"  } }
Suggested actions:

*

*Raise the per-user quota in the Developer Console project.

*If one user
  is making a lot of requests on behalf of many users of a Google Apps
  domain, consider a Service Account with authority delegation (setting
  the quotaUser parameter).

*Use exponential backoff.

Basically you are encountering flood protection,  your code is running to fast you need to slow it down.  Why v2 doesn't show this and v3 does that is quite simply the fact that v3 is faster then v2 it is after all a newer API.
Solution:
Implementing exponential backoff
Exponential backoff is a standard error handling strategy for network applications in which the client periodically retries a failed request over an increasing amount of time. If a high volume of requests or heavy network traffic causes the server to return errors, exponential backoff may be a good strategy for handling those errors. Conversely, it is not a relevant strategy for dealing with errors unrelated to rate-limiting, network volume or response times, such as invalid authorization credentials or file not found errors.
Used properly, exponential backoff increases the efficiency of bandwidth usage, reduces the number of requests required to get a successful response, and maximizes the throughput of requests in concurrent environments.