text:
Q: An elegant way on a stream to do forEach and count I want to process a list and then count how much item processed. My code is something like:
List<String> names = ...;
names.stream().filter(...).map(...) /* a list of time-consuming filters and maps */
        .forEach(...);
// Then count them:
int count = names.stream().filter(...).map(...).count();

If I want to simplify my code use Supplier like this: Copy a stream to avoid "stream has already been operated upon or closed" , I still need to do a list of time-consuming filters and maps twice.
So I have to do it in an ugly way, like:
List<String> filteredNames = names.stream().filter(...).map(...).collector(Collectors.toList());
filteredNames.forEach(...);
int count = filteredNames.size();

This may generate another huge list on Java heap.
An uglier but efficient way is like:
int[] count = {0}; // or use AtomicInteger(0);
names.stream().filter(...).map(...).forEach(s -> {
    // process
    count[0] ++;
});

Is there an elegant way to do this?

A: Iterating over a List is not expensive per se. The expenses of repeated Stream operations depend on the actual repeated intermediate operations. Due to the optimizing environment, the code is executed in, two single-purpose loops may turn out to be more efficient than putting two concerns into one loop.
Note that the count does not depend on the result of the map operation, hence, you can omit it for the count operation:
List<String> names = ...;
names.stream().filter(...).map(...).forEach(...);
// Then count them:
long count = names.stream().filter(...).count();

This is the variant to try and measure, for comparison with Stream approaches doing both actions at once.
Note that forEach does not guaranty your action to be performed in order and in case of a parallel stream, it could even get evaluated concurrently. Similar behavior would apply to peek, as well as any attempt to insert the actual action into a map function.
An attempt to use something like
long count = names.stream().filter(...).map(...)
    .map(x -> {                                   // don't do this
        // your action
        return x;
    }).count();

bears the additional problem that an implementation might consider the same thing as said above, the map function's result is irrelevant to the count, so it could get skipped, even if the current implementation does not.
Likewise, using
long count = names.stream().filter(...).map(...)
    .peek(x -> {                                  // don't do this
        // your action
    }).count();

bears some risk. The last map step is irrelevant to the final count, so it could get skipped, in which case the peek action must get skipped too, as the input for it doesn't exist. There is no guaranty that obsolete intermediate operations are kept only for the sake of peek operations. We can only speculate, how radical the implementers will exploit this aspect. But the only practical example in the current reference implementation, is the skipping of the entire pipeline when the count is predictable beforehand, which also skips all peek operations. This suggests that we should never rely on the execution of peek actions.
But when you use
int count = names.stream().filter(...).map(...)
    .mapToInt(x -> {                   // don't assume sequential in-order execution
        // your action
        return 1;
    }).sum();

the end result is dependent on the function containing the action, so it will always be evaluated. But unlike forEach, which can be replaced by forEachOrdered, to get guaranteed non-concurrent, ordered execution, there is no such option for the mapping function.

A: This is not particularly more elegant or efficient, but it's an alternative you didn't list (a mutable reduction):
AtomicInteger count = names.stream().collect(
        AtomicInteger::new,
        (sum, name) -> {
            //forEach action here
            sum.incrementAndGet();
        },
        (n1, n2) -> {
            n1.addAndGet(n2.get());
        });

A: If you have to process all the elements of the Stream anyway (and it seems like you do, since you are using forEach), why not collect them into a List before doing the processing? Then you can easily get the size of the List.
List<String> names = ...;
List<Something> result = names.stream()
                              .filter(...)
                              .map(...)
                              .collect(Collectors.toList());
result.forEach (...);
// Then count them:
int count = result.size ();


text:
Q: TYPO3 manual sorting of translated records When I use in the TCA ctrl-section of an record
'sortby' => 'sorting'

the translated items are on the same position as the default ones in the backend. But in the frontend the order is wrong. Espacially when some records are for all languages and some are only in the foreign language.
As an example you can use the news extension with manual sorting. This problem still exists in TYPO3 9.5.19.
The number of the ticket in TYPO3 forge is 70154. A solution could be to bind the sorting value on the default language.

redpajama_set_name: RedPajamaStackExchange


text:
Q: GET Requests fails with 401 Unauthorized Error when the url has query parameters I am making a Rest API call to Jira in C# using Oauth 1.0a. So far I have been able to get the access token and make API calls using this token to fetch the projects, issue, create tickets, and add attachments without any issue.
I am facing an issue when I have some query parameters in the URL wherein I am getting a response oauth_problem="signature_invalid"

"{WWW-Authenticate: OAuth
realm="https%3A%2F%2Fxxxx-stage.dummy.com%2Fjira", OAuth
realm="https%3A%2F%2Fxxxx-stage.dummy.com%2Fjira",
oauth_problem="signature_invalid",
oauth_signature="fxrHjNmz3C0gPClh667xKO93fU9PI%2FFAy2o%2B0tA98oso3d%2FiHF957LnMJdKWdmN1w6lJIgEYA5WLpvRuv65IIgAVeSWQWyyE2iqKY5NKpVe8w9lNKJpp6jVX3OzUfhZFsUmNcfwmrfEzDfq0DFKHbDltA9KX51daMWfE5bOxUwA%3D",
oauth_signature_base_string="GET%26https%253A%252F%252Fxxxx-stage.dummy.com%252Fjira%252Frest%252Fapi%252F2%252Fissue%252Fcreatemeta%26oauth_callback%253Doob%2526oauth_consumer_key%253DOauthKey-elite%2526oauth_nonce%253D161227630350881010%2526oauth_signature_method%253DRSA-SHA1%2526oauth_timestamp%253D1612276303%2526oauth_token%253DIuXbcYTqh5kAIbirTWg7zqzJhVITFHny%2526oauth_version%253D1.0",
oauth_signature_method="RSA-SHA1"
Date: Tue, 02 Feb 2021 14:34:19 GMT   Strict-Transport-Security:
max-age=16000000; includeSubDomains; preload   X-XSS-Protection:
1;mode=block   Referrer-Policy: strict-origin-when-cross-origin
X-Content-Type-Options: nosniff   X-Frame-Options: SAMEORIGIN
Content-Security-Policy: frame-ancestors 'self'
X-Permitted-Cross-Domain-Policies: none   X-Download-Options: noopen
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Content-Length: 654   }

The actual url is "https://xxxx-stage.dummy.com/jira/rest/api/2/issue/createmeta?projectKeys=Elite&issueTypeNames=Task&expand=projects.issuetypes.fields"
After sorting and encoding the url and the parameters I have the below string which I am signing using RSA-SHA1.

GET&https%3A%2F%2Fxxxx-stage.dummy.com%2Fjira%2Frest%2Fapi%2F2%2Fissue%2Fcreatemeta&expand%3Dprojects.issuetypes.fields%26issueTypeNames%3DTask%26projectKeys%3DSciFiProject%26oauth_callback%3Doob%26oauth_consumer_key%3DOauthKey-elite%26oauth_nonce%3D161227476865431774%26oauth_signature_method%3DRSA-SHA1%26oauth_timestamp%3D1612274768%26oauth_token%xxxxcYTqh5kAIbirTWg7zqzJhVITFHny%26oauth_version%3D1.0

And the query parameters are not added to the Authorization header. It only has the OAuth parameters.
Also, I noticed that in the encoded URL, the "GET" method name and the URL are separated by "&". And the first parameter "expand" and the end of the URL "createmeta" are separated by "&" but the other parameters which follow including the OAuth parameters are URL encoded. The strange thing is this works for other URLs with no query parameters.
This has been already answered here GET fails with 401 (Unauthorized) when query parameter is involved due to invalid OAuth signature, I have tried doing the steps mentioned there but I guess I might be missing something.
Can somebody guide me where I am going wrong?

A: I was able to figure out the problem myself. The issue was with the way the SignatureBaseString was formed. The parameters have to be sorted and then encoded. So in my case the issue was with the highlighted parameter .

GET&https%3A%2F%2Fxxxx-stage.dummy.com%2Fjira%2Frest%2Fapi%2F2%2Fissue%2Fcreatemeta&expand%3Dprojects.issuetypes.fields%26issueTypeNames%3DTask%26projectKeys%3DSciFiProject%26oauth_callback%3Doob%26oauth_consumer_key%3DOauthKey-elite%26oauth_nonce%3D161227476865431774%26oauth_signature_method%3DRSA-SHA1%26oauth_timestamp%3D1612274768%26oauth_token%xxxxcYTqh5kAIbirTWg7zqzJhVITFHny%26oauth_version%3D1.0

The highlighted parameter is supposed to be at the end of the encoded string. So basically the solution is to sort the parameters in the ascending order, Separate each parameter with "&" and then URL encode the parameter string. If two parameters have the same name, then order them based on their value.

GET&https%3A%2F%2Fxxxx-stage.dummy.com%2Fjira%2Frest%2Fapi%2F2%2Fissue%2Fcreatemeta&expand%3Dprojects.issuetypes.fields%26issueTypeNames%3DTask%26oauth_callback%3Doob%26oauth_consumer_key%3DOauthKey-elite%26oauth_nonce%3D161228695355767297%26oauth_signature_method%3DRSA-SHA1%26oauth_timestamp%3D1612286953%26oauth_token%3xcxccYTqh5kAIbirTWg7zqzJhVITFHny%26oauth_version%3D1.0%26projectKeys%3DElite

more info can be found here regarding encoding of parameters.
https://oauth.net/core/1.0/#encoding_parameters


text:
Q: Java Http redirection i use this code to send POST Http request:
String url1 = "URL1";
String url2 = "URL2";
URL obj = new URL(url1);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
this.setHeader(con,urlParameters.length());
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();

How can i do a redirection to URL2 if URL1 is down ?

A: obj.openConnection() should throw an Exception if the connection can't be established. I assume you function throws this exception. Instead you can catch it and try again. Please note that also writing and reading from the connection can throw exceptions. Think about how to handle each of them (try again, or throw to let the caller handle the problem)
URL obj;
HttpsURLConnection con = null;
try
{
    obj = new URL(url1);
    con = (HttpsURLConnection) obj.openConnection();
}
catch(Exception e)
{
    System.out.println("Error, redirecting to url 2");
    e.printStackTrace();

    try
    {
        obj = new URL(url2);
        con = (HttpsURLConnection) obj.openConnection();
    }
    catch(Exception e)
    {
         System.out.println("Error, url2 failed");
         throw e;  // This will make your function throw an exception when both urls are down.
    }
}

A: Try this code to post and Refactor it to your need. post data in java console application
    URL serverUrl =
            new URL("http://localhost:1611/POST/othersite.aspx");
    HttpURLConnection urlConnection = (HttpURLConnection)serverUrl.openConnection();
    urlConnection.setDoOutput(true);
    urlConnection.setRequestMethod("POST");
    Boolean isUrl1Down=false;
    try {
        BufferedWriter httpRequestBodyWriter = new BufferedWriter(new OutputStreamWriter(urlConnection.getOutputStream()));
        httpRequestBodyWriter.write("userName=Johnny+Jacobs&password=1234");
        httpRequestBodyWriter.close();
    }catch (IOException ie){
        isUrl1Down=true;
    }
    if(isUrl1Down){
        System.out.println("Try with secound URL");
    }
    // Reading from the HTTP response body
    Scanner httpResponseScanner = new Scanner(urlConnection.getInputStream());
    while(httpResponseScanner.hasNextLine()) {
        System.out.println(httpResponseScanner.nextLine());
    }
    httpResponseScanner.close();


text:
Q: How to use java like objects in php( CodeIgniter) I want to use objects(java style) in my PHP code after by instantiating objects after getting their properties from database and use them as objects from that point on. Does this work in PHP? If yes,where should I place my classes in the codeigniter directories?
$object=object_constructor($this->model_name->function_that_fetches_object_properties());

A: What you are looking for is what is called an ORM which codeigniter does not have "out of the box".
There are some that integrate it with Doctrine, I would recommend you look at other php frameworks that have a built in ORM, one that is somewhat similar to codeigniter in approach is FuelPHP.  It is approaching a stable release and has been enjoyable for me to work with.
ORM example in FuelPHP:
$entry = Model_Article::find(4);
$entry->title = 'My first edit';
$entry->author = 'Total n00b';
$entry->save();

A: I suggest you use PEAR's DB_DataObject which does exactly this kind of mapping, including fetching related objects.


text:
Q: How to make 'git log --oneline' show which commit messages are multiline I find myself doing git log --oneline quite often to get a quick glance at changes I am about to push to or merge from the remote. Is it possible to append some identifier (such as "[...]") to mark that commit message as a multiline one, so I can know that there is more information there?
Basically, what I want is this:
e1140de Some commit message
d1f58d1 Some multine commit message [...]
736f778 Some other commit message

A: With the help of Adam's answer, I came up with an alternative to my requirement:
git log --format="%h %s%n%b"

This is just like --oneline, except it puts a linebreak and the message body just after the message subject. It looks much better with some coloring:
git log --format="%C(yellow)%h%Creset %Cgreen%s%Creset%n%b"

A: You can do this with some scripting. There is a message body token for the format in git log (%b).
But nothing can do that in one command: You have to see whether the message body is empty or not.

A: I got used to manually append "(s.b.)" for this which stands for "see below".
You may use a prepare-commit-msg hook to append it automatically if a commit msg is multiline.


text:
Q: How to open a modal in bootstrap if this is loaded via ajax? I am calling a div where the modal is via Ajax. Once the div and its modal has been loaded, the button won't open the modal. The code below is the modal structure, it is just a plain modal from bootstrap, and this has been loaded via ajax:

 <button type="button" class="btn btn-primary" data-toggle="modal" data-target="myModalZ">Large modal</button>

Filter our work

                Content.....

If it is the case that I need to reload bootstrap.js where the modal jQuery is as the content is now loaded via ajax, is there a sort of init modal call I can do after my own ajax callback?

A: You can use the jQuery to open the modal:
$(document).ready(function(){
    $('button[data-target="myModalZ"]').click(function(){
        $('#myModalZ').modal('show');
    });
});

More Documentation is here.
EDITED:
$(document).ready(function(){
    $('button[data-target="myModalZ"]').click(function(){
        if($('#myModalZ').length){
           $('#myModalZ').modal('show');
        } else {
           alert('Your message');
        }
    });
});

A: First append received content inside body somewhere. Then trigger modal manually.
$.ajax(
    {
        url: "http://www.example.com/someAPI",
        success: function(result){
            // Append content somewhere

            // Init button click event once your content is ready
            $('button[data-target="myModalZ"]').click(function(){
                $('#myModalZ').modal('show');
            });

    }
});

Please check out full documentation here.


text:
Q: Sending UTF-8 encoded emails with Python3 gives UnicodeEncodeError I am expecting the following code to send an UTF-8 encoded mail.
import email.parser
import smtplib

msg_str = """From: A <a@example.org>
To: B <b@example.org>
Content-Type: text/plain; charset="UTF-8"

Testing UTF-8: – ä."""

msg = email.parser.Parser().parsestr(msg_str)
smtplib.SMTP('localhost').send_message(msg)

However, I am getting this error.
UnicodeEncodeError: 'ascii' codec can't encode character '\u2013' in position 15: ordinal not in range(128)

What is failing here is the flatten call to email.generator.BytesGenerator in pythons smtplib. Shouldn't the email parser fail in the first place if the msg object can't be converted to bytes?


text:
Q: Chaining STS assume role across 3 aws accounts There is an AWS account A, which has a resource X managed by policy Pax. It adds the second AWS account B to a role which attaches the policy Pax, let's call this role Rax. Now within the AWS account B, I create another policy for assuming role Rax, let's call it Pbrax and added it to a role RPbrax where the Principal is an AWS account C.
When I try to access the resource X via the account C, I get access denied. I cannot touch anything in AWS account A, but in B and C.

A: Role permissions are not cumulative.
This means the history of the role chaining doesn't help you - the principal in account C needs to have its own access to the resources in account X if needs to access them.


text:
Q: How to display values of a dictionary? I'm trying to create a dictionary of weigths per layer for my ANN implementation.
The issue is that although I create the dictionary with strings as keys and tensors as values I don't know how to display them when I call the init_weight method
def init_weights(topology):
#topology: dimensions of the network

for i in range(1,len(topology)):
parameters['W' + str(i)] = tf.Variable(tf.random_normal([topology[i-1],topology[i]]))

The output of the method shows the following:
{'W1': <tf.Variable 'Variable_1:0' shape=(2, 5) dtype=float32_ref>,
 'W2': <tf.Variable 'Variable_3:0' shape=(5, 5) dtype=float32_ref>,
 'W3': <tf.Variable 'Variable_5:0' shape=(5, 5) dtype=float32_ref>,
 'W4': <tf.Variable 'Variable_7:0' shape=(5, 10) dtype=float32_ref>}

How can print the weights matrices?

A: Tensorflow is a statically typed framework (guess this is changing in 2.0). Meaning, you first build a static graph and the graph has values only when run using Tf.Session(). Now to answer your question. There are two ways to get what you want.

*

*Add tf.enable_eager_execution() at the start of your script. This creates a dynamic graph (similar to Pytorch). Your same code without any extra addition will give you what you want.

*Wrap everything into a tf.Session() and run it. You will get the weight matrices


text:
Q: Error in Opengl opencl interoperation I get the following 4 errors after compiling.
error C2065: 'CL_GL_CONTEXT_KHR' : undeclared identifier
error C2065: 'CL_WGL_HDC_KHR' : undeclared identifier
IntelliSense: identifier "CL_GL_CONTEXT_KHR" is undefined
IntelliSense: identifier "CL_WGL_HDC_KHR" is undefined

I use following headers:
#include <stdio.h>
//#include <iostream>
#include <Windows.h>
#include <GL/glew.h>
#ifdef MAC
    #include <OpenCL/cl_gl.h>
    #include <OpenGL/OpenGL.h>
    #include <GLUT/freeglut.h>
    #define GL_SHARING_EXTENSION "cl_APPLE_gl_sharing"
#else
    #include <CL/cl.h>
    #include <CL/cl_gl.h>
    #include <GL/glut.h>


text:
Q: В каком приложении писать код для сайта? Подскажите, пожалуйста, что лучше использовать? До этого сколько читал, многие склонялись и указывал использовать софт SimpleText. Сейчас вот узнал, что есть такая вещь Microsoft WebMatrix, с вида выглядит очень прилично, но информации в Интернете в плане отзывов по ней почти нет. Ещё пару раз встречал, что упоминают продукт от Adobe, adobe dreamweaver. Что можете о ней сказать? И чем всё таки в принципе лучше пользоваться при написание сайта?
A: Начни с Notepad++.
Если хочешь именно IDE, то попробуй Eclipse или NetBeans.
A: Посмотрите на Sublime.
Если под Mac — другой отличный вариант Coda.
A: Geany
A: Обратите внимание на Atom editor, похож на notepad++, легкий и бесплатный!


text:
Q: docker desktop Preferences settings page is not loading and state is docker desktop is starting from forever Main issue is docker desktop is not starting in mac &
The status bar is showing docker desktop is starting but this process is not ending
I tried system reboot multiple times, Reinstallation of different docker desktop versions but didn't help.
I found answers which mentioned to change the Preferences -> Settings and allocation of different memory and core to docker desktop here but settings page is also in endless loading state

Internet speed ~10MBps| mac OS 10.14 Mojave | 16GB RAM|. Please help fixing it

A: I've been trying so many things to make it work and the only thing that worked for me in Windows was running this in cmd
"C:\Program Files\Docker\Docker\DockerCli.exe" -SwitchDaemon
I took this on Docker cannot start on Windows

A: Try this: Github Link it works for me!
I found a magical solution, first open the docker preferences settings, and then click the docker icon in the status bar to select restart. At this time, you will be surprised to find that the settings UI is no longer in the loading state, then select Kubernetes in this short time, cancel the enable Kubernetes option, finally click the application below and restart. docker returned to normal. All this should be caused by Kubernetes not starting normally.
Docker version 2.2.0.5
macOS High Sieera 10.13.6

A: On my side I had a similar issue on my Windows machine.
It was probably caused by a forced shutdown after sleep mode (perhaps no more battery).
I tried many things like restarting the Services but it was not working when I started to watch the folder .docker in my home directory.
I did this:

*

*I first stopped my Docker Desktop process

*then I deleted the file named .token_seed.lock in ${USER_HOME}/.docker/

*Start the Docker Desktop from the shortcut

and after that my Docker was running without any issue and my stored images were correctly displayed (and starting / stopping properly).

A: When Docker preference setting page is not working

Click on Docker desktop icon >> Preferences ( This page is not loading) >> Click on the Troubleshoot icon ( top right corner with a bug image placeholder)  >> Reset to factory defaults

A: Docker demon isn't responding all your need is

*

*Quit docker desktop.

*force quit all docker processes in activity monitor (this should force stop the demon).

*start docker desktop again.

A: I was having the same issue and what it solved it was to force Docker using Linux language. You can use this command for that:
'C:\Program Files\Docker\Docker\DockerCLI.exe' -SwitchLinuxEngine

A: 1 - If you haven't already, follow Microsoft's Steps 4-6
https://learn.microsoft.com/en-us/windows/wsl/install-manual#step-4---download-the-linux-kernel-update-package
After setting up your distro
2 - Inside Docker Click on the Bug Icon (next to the settings top)
3 - Do Factory reset for Docker
4 - Stop Docker from Task Manager
5 - Run this command
'C:\Program Files\Docker\Docker\DockerCLI.exe' -SwitchLinuxEngine

6 - Now Launch Docker and it will work! hopefully.
If it doesn't (in step 3 I also deleted Containers, WSL settings, Hyper V) from Docker Settings (Be careful deleting your own Containers is dangerous)

A: I've just solved this problem.
I'm using docker on Ubuntu vmware.
I think, the cause is just docker engine is not started.
The solution is below:

This function is for virtual machine in the virtual machine.
Oh yes, so now we can run the docker engine successfully.
Of course, the "forever loading" problem has been solved.

A: I have encountered the exact same problem right after I added a key-value pair into the Docker daemon configuration file through the Docker Desktop -> Preferences -> Docker Engine tab. The change broke my Docker engine and I couldn't undo my changes through UI since the UI was broken and showing the loading animation.
I solved the problem by manually removing the changes I made. The daemon configuration file is located in ~/.docker/daemon.json.


text:
Q: Screenshot.png Not displaying on admin I have installed a premium theme and changed the screenshot.png and uploaded it via ftp, upon looking at the admin panel it still display the old screenshot.png and the link it was linking was
http:// www. mysite .com/wp-content/themes/mytheme/screenshot.png
and if I directly go to the link
mysite.com/wp-content/themes/mytheme/screenshot.png
it shows my new screenshot but not showing on my admin panel, why does the admin panel detects the screenshot with www and if I look on my hosting file manager my theme has the new screenshot. I've tried to delete and reinstall wordpress from scratch including the theme but still doing the same thing. any thoughts?
Thanks!

A: It's probably cached. Try CTRL+F5 or clear browser cache and see if that helps.
A quicker solution is to add a query arg to the end of the url, like ?refresh=1 which would make your browser think it is a different URL, even if the query arg doesn't do anything. This won't fix the original issue until your cache clears, still, but it will tell you that it is working (at least for other people who haven't seen the old version yet).


text:
Q: How to stop Alert box reloading in same session I've used the code below - from https://www.w3schools.com/howto/howto_js_alert.asp - to create an alert box that goes away when the user clicks on the "x" button inside the box. But the box appears again whenever a user loads another page.
I'd like users to only see this box once; ie, it doesn't reappear again after they have clicked it.
New to this site and javascript - would be grateful for suggestions on what should be added to the script below so the box doesn't reappear for a user once they've clicked it.

×
Click this link


text:
Q: Add nth-child odd and even in a div for multiple lines I have, let's say, 10 lines of text in a post, and I want to include them in a that will add different style (like font size or color) to line one and line two, and then repeat it automatically no matter how many lines are. so line one will have the same style as line 3, 5, 7, 9 and line two will have the same style as line 4, 6, 8, 10 and so on, if the list would be bigger...
From what I see I could use something like
 p:nth-child(odd)
 {
     background:#ff0000;
 }

 p:nth-child(even)
 {
     background:#0000ff;
 }

but the problem is I do not want to add a <p> to every line, I want to add a <div class="something"> before the first line and close it after the line 10 </div>
How to make this work?
thank you


text:
Q: Influencing Colonial Nation wars In my game, Castilian Mexico (my independent colonial state) is currently fighting British Mexico (Great Britain's colonial state). It's a war started by the other side; but Britain and me are at peace, which means I can share provinces with the troops of British Mexico without fighting.
I don't want to start a war with Britain at this point. Is there any other way to support Castilian Mexico other than declaring war on Britain - money, ...? (Or to influence Isla Juana, another one of my colonial independent states comprising almost the entire Caribbean and their next-door neighbor which currently just stands by idly, to make them help their Castilian Mexican brethren)
Any ideas appreciated!

A: You can also consider issuing an embargo, which for some colonial nations could cut into their income.
A bit more of a cheesy and costly tactic is to ask for military access with the enemy nation, then park a gigantic army on top of their biggest army, causing massive attrition.
If you do enforce peace, keep in mind that Britain will automatically be called into a war with any non-colonial nation that is at war with their colonial nations. Thus, enforcing peace puts you at war with the entire empire, unless the demand for peace is accepted (and peace is immediately concluded). The demand for peace is rarely accepted, especially if the enemy nation is doing well, but if they are terrified of you and the war has dragged on for a long time and isn't going particularly well, they might accept the demand.
Either way, if you do subsidize and give gifts to your colonial nation (or any nation) the money will be spent on raising troops unless they have run out of manpower and aren't too far over their forcelimit. The AI will start building buildings once they can't build armies, so they don't tend to accumulate a warchest or hire mercenaries. It might be a good idea to preemptively subsidize your colonial nations that might get attacked so that they will have good infrastructure and better standing armies, which will make them fight better and also deter attacks to begin with.

A: The only thing I can think of to enable you to influence the war without actually declaring war and hence drawing in the British is to provide War subsidies to Castilian Mexico.
There's no guarantee that your money would be wisely spent but it could sway things if it's evenly balanced.
You could also try to enforce peace on British Mexico. It may work, but if they refuse you'll be dragged into the war on the side of the defender.
Or finally you could try to support rebels in British Mexico or If you've researched espionage ideas 6 you could try to sow discontent to try and cause a rebellion uprising.


text:
Q: Object initialization in Python I've created a simple class with object that has init value x0. When I change another value x, my x0 is also changing.
I thought that x0 should remain unchanged. Could you please explain why is this happening?
file main.py:
import numpy as np
from simpleclass import test

def main():

    params = dict()
    params['position'] = np.array([1.0, 2.0])

    object = test(params)

    print(object.x0)
    print(object.x)

    object.run(2)

    print(object.x0)
    print(object.x)

if __name__ == "__main__":
    main()

file simpleclass.py:
class test():

    def __init__(self, params):
        self.x0 = params['position']
        self.x = self.x0

    def run(self, num):
        self.x += self.x*num

result:
[ 1.  2.]
[ 1.  2.]
[ 3.  6.]
[ 3.  6.]

A: problem is with
class test():
    def __init__(self, params):
        self.x0 = params['position']
        self.x = self.x0

    def run(self, num):
        self.x += self.x*num

self.x = self.x0 here self.x and self.x0 are pointing same object. you can make copy of self.x0.
import copy

class test():
    def __init__(self, params):
        self.x0 = params['position']
        self.x = copy.deepcopy(self.x0)

    def run(self, num):
        self.x += self.x*num

A: surya singh is right, just print the memory address, you will get the same numbers
class test():
    def __init__(self, params):
        self.x0 = params['position']
        self.x = self.x0
        print id(self.x)
        print id(self.x0)

A: You are only passing a reference
By self.x = self.x0, you are only passing a reference. With self.x += self.x*num, the reference is unchanged too. So after those two operations, x and x0 still points to the same array.
It would be different if you used an immutable object, such as tuple
params['position'] = (1, 2)

With tuple, += does something different than what you want, but you see, x and x0 points to different object.
(1, 2)
(1, 2)
(1, 2)
(1, 2, 1, 2, 1, 2)

Use a copy
You want to create a copy of your array, numpy has a built-in method for that
self.x = self.x0.copy()

Result:
[ 1.  2.]
[ 1.  2.]
[ 1.  2.]
[ 3.  6.]


text:
Q: ssh successful but not scp? why? I am trying to automate the file transfer between server and the local machine, which I was able to do it on laptop running windows 7 as well as Ubuntu. Now trying to implement it on the local desktop machine running windows server 2003, by installing cygwin. I am able to transfer files via
scp

the errror message got using the following command is as below.
 $ ssh -vvv test username@example.se:~/?
OpenSSH_6.0p1, OpenSSL 1.0.1c 10 May 2012
debug2: ssh_connect: needpriv 0
debug1: Connecting to test [11.22.33.44] port 22.
debug1: connect to address 11.22.33.44 port 22: Connection timed out
ssh: connect to host test port 22: Connection timed out

some help would be appreciated. I do not understand, why i am unable to since server settings must be ok as I was able to transfer files using scp from my laptop. what can be the reason. some help needed immediately if possible. thanks.

A: This error shows you couldn't connect to the server. That can have many reasons:

*

*a firewall blocking incoming connections to your server

*a firewall blocking outgoing connections from your computer

*ssh daemon on the server configured to listen on a non-standard port

*stopped ssh daemon

Since you can transfer files from your other computer I'd say you probably have a firewall blocking the connection. By the way... I supposed this host "test" is just a hypothetical example you used. Note it's IP address is not a valid local address (11.22.33.44), so if this message is real you should try using the server's IP address in place of "test".


text:
Q: What method to use to figure out if user is connected to facebook I am using django-social-auth for facebook login. I am able to login user using "/facebook/login". But, I need to check if user is logged in using facebook on some other page. Is there a method in the module to check if user is logged in using facebook?
thanks

A: You can check if the user has any facebook account as such:
for usersocialauth in request.user.usersocialauth_set.all():
    print usersocialauth.provider

You might as well get the list of providers for the user:
request.user.usersocialauth_set.values_list('provider')

Beware: a cosmic backward compatibility break was introduced in commit 7f967702. Read answer comment for detail.

A: Updated for latest Django / python-social-auth
This example checks if facebook is linked to the account.  Replace facebook with a valid backend name.
'facebook' in user.social_auth.all().values_list("provider", flat=True)


text:
Q: Fill a Bootstrap Responsive table vertically I would like to use a bootstrap solution to be able to dynamically generate columns, that contains elements, and have an overflow of this column as a horizontal scroll.
My project should display a product list ordered by their brand. So a column is a brand and in the column are many products.
I saw that the Bootstrap responsive table might be a solution but I can't make it fit my needs. This table organize the data by row when I need to organize them by column.
Here is an image of how it should be :

The code below is generated using JS. I'm building my products and I'm pushing them in a "col-3" that is my brand.
Works well as long as I have 4 brands maximum. If I add a 5th one, this last column is pushed under one of the existing one. That is exactly what I'm trying to change. I want this 5th column to be at the same 'level' of the others and to have a horizontal scroll on my brand container.

               Brand A

Product 1

1.5

Product 2

1.5

            ...

               Brand B

Product 3

2.5

la pièce

Product 4

2

la pièce

A: You can do this with bootstrap's grid system.

.product-image {
  height: 75px;
  width: 75px;
}
<!DOCTYPE html>

    <link data-require="bootstrap@*" data-semver="4.0.5" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" />

    <link rel="stylesheet" href="style.css" />

https://plnkr.co/edit/sybd6FW749SFHr3DAqQ4?p=preview

A: Searching deeper on the internet I found a solution I could adapt to fit mine : TW Bootstrap: How to overflow columns
Thanks for your time.


text:
Q: How to retrieve percentage type value from excel sheet using poi I am trying to read cell values excel sheet using Apache POI. One of my sheet contains percentage type as the cell type. When I read that cell using POI using cell.getNumbericValue(), its returning me the double value. If cell contains 11.24%, it is returning me 0.1124.
My problem is, I want to read the % symbol also from the cell i.e., I want to read the exact data as it is in cell as 11.24%. So, I tried it using the cell.toString(), even then it is returning me the same value as above.
Can anyone please suggest me, how to get rid of this problem.
Thanks in advance
Nandu

A: Try this:
String typeCell =cell.getCellStyle().getDataFormatString();

It gives:

*

*"General" value for non formated cells,

*"0%" for percentage formats

*dd/mm/yy for date , depends of locale

I manage to parse all types in cells (Numbers, Percentage, Date, Text, Currency) I just have to check what value for which cell type it will give me back.
Because I also have to much trouble with HSSFCell.CELL_TYPE_STRING or HSSFCell.CELL_TYPE_NUMERIC.

A: 11.24% is 0.1124, which is why that's what gets stored in the file, and that's what you get when you ask for the numeric value
POI provides a utility for formatting numeric strings based on the format rules applied to the cell, which is DataFormatter. If you use that to format the cell, you'll get back a string with the contents of the cell largely as seen in Excel.

A: You can detect if a cell is formatted as a percentage by testing the cell data format string like this:
if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
    if (cell.getCellStyle().getDataFormatString().contains("%")) {
        // Detect Percent Values
        Double value = cell.getNumericCellValue() * 100;
        System.out.println("Percent value found = " + value.toString() +"%");
    } else {
        Double value = cell.getNumericCellValue();
        System.out.println("Non percent value found = " + value.toString());
    }
}

This should enable you to distinguish between percentage formatted values and ordinary numeric values.

A: The answer of @WeeShetland should be the accepted answer.
Instead of cell.getCellStyle().getDataFormatString().contains("%") you can use
// class level
private static final int PERCENTAGE_FORMAT = BuiltinFormats.getBuiltinFormat("0%");

...

// in some method
if (cell.getCellStyle().getDataFormat() == PERCENTAGE_FORMAT) {
    ...


text:
Q: Proof of Runge's phenomenon for a concrete case Let $f(x)=\frac{1}{1+25x^2}$ and range is $[-1,1]$. Given $n+1$ equidistant points $x_0 = -1,x_1,...,x_n = 1$ and their values $f(x_0),f(x_1),..,f(x_n)$, perform polynomial interpolation by the $n+1$ points and get the polynomial $p_n(x)$. The question is

Show there exists some $x\in[-1,1]$ such that error $p_n(x)-f(x)$ does not converge to $0$ as $n\to\infty$.

I think it is possible that we need to show $\mathop {\lim }\limits_{x \to \infty } ({\max _{ - 1 \leqslant x \leqslant 1}}|f(x) - {p_n}(x)|) = \infty $, but I am not sure how to do this. I don't know how to express the error of newton's interpolation in a decent way. Thank you!


text:
Q: Issues in R package after CRAN asked to replace \dontrun{} by \donttest{} I submitted a package to CRAN and they asked me to replace \dontrun{} by \donttest{} in the Rd-files and resubmit. I was using \dontrun{} to wrap some examples that are supposed to throw error messages.
After replacing \dontrun{} by \donttest{} I conducted some tests and R CMD check still succeeds but it happens that now both devtools::check() and R CMD check --as-cran fail due to the examples wrapped in \donttest{}:
checking examples with --run-donttest ... ERROR

After some browsing I learned that R 4.0.0 has changed R CMD check --as-cran to run \donttest examples. According to the NEWS of R-devel:

"R CMD check --as-cran now runs \donttest examples (which are run by example()) instead of instructing the tester to do so. This can be temporarily circumvented during development by setting environment variable R_CHECK_DONTTEST_EXAMPLES to a false value."

Since I intend to resubmit the package to CRAN, setting _R_CHECK_DONTTEST_EXAMPLES_ to false locally  will not help me.
I also found this recent discussion in a devtools issue where Hadley Wickham states that:

"Generally, now if you don't want to run tests on CRAN \dontrun{} is more likely to work, but using \dontrun{} may cause initial submission to fail."

So now I don't know how to proceed because if I resubmit the package with the required changes I already know it will throw an error in R CMD check --as-cran, and hence it will probably fail CRAN's automatic pretests.
EDIT:
As suggested here I tried if(interactive()){} instead of \dontrun{}. This solution succeeds in R CMD check --as-cran and devtools::check() but I don't think it is the most appropriate way to address this problem since it does not work well with example() (throws an error and does not show the remaining examples). \dontrun{} works better with example() as it prints all the examples but comments out the ones wrapped with \dontrun{}.

A: I don't think the package examples are the right place for "examples that are supposed to throw error messages".
Your problem would be easily solved when you move these 'examples' to testthat unit tests.
There is
expect_error()
expect_warning()

to see if your package throws a warning/error as expected.
If you really want to inform users about what they should avoid to input, maybe you can just add it as a comment to the examples or into the other documentation (details, param)
What you see quite regularly in other package examples is the following:
## Example for working
function(x, abc = "5)

## This would give an error because
# function(x, abc = "falsch")

## Working example 2
function(x)
x <- x+y

A: If you know that something will throw an error, you can wrap it in try().
## example of failing code
try(stop("Here is an error"))


text:
Q: Swap two items in List Is there a LINQ way to swap the position of two items inside a List<T>?

A: Maybe someone will think of a clever way to do this, but you shouldn't. Swapping two items in a list is inherently side-effect laden but LINQ operations should be side-effect free. Thus, just use a simple extension method:
static class IListExtensions {
    public static void Swap<T>(
        this IList<T> list,
        int firstIndex,
        int secondIndex
    ) {
        Contract.Requires(list != null);
        Contract.Requires(firstIndex >= 0 && firstIndex < list.Count);
        Contract.Requires(secondIndex >= 0 && secondIndex < list.Count);
        if (firstIndex == secondIndex) {
            return;
        }
        T temp = list[firstIndex];
        list[firstIndex] = list[secondIndex];
        list[secondIndex] = temp;
    }
}

A: List<T> has a Reverse() method, however it only reverses the order of two (or more) consecutive items.
your_list.Reverse(index, 2);

Where the second parameter 2 indicates we are reversing the order of 2 items, starting with the item at the given index.
Source: https://msdn.microsoft.com/en-us/library/hf2ay11y(v=vs.110).aspx

A: Check the answer from Marc from C#: Good/best implementation of Swap method.
public static void Swap<T>(IList<T> list, int indexA, int indexB)
{
    T tmp = list[indexA];
    list[indexA] = list[indexB];
    list[indexB] = tmp;
}

which can be linq-i-fied like
public static IList<T> Swap<T>(this IList<T> list, int indexA, int indexB)
{
    T tmp = list[indexA];
    list[indexA] = list[indexB];
    list[indexB] = tmp;
    return list;
}

var lst = new List<int>() { 8, 3, 2, 4 };
lst = lst.Swap(1, 2);

A: Starting with C# 7 you can do
public static IList<T> Swap<T>(IList<T> list, int indexA, int indexB)
{
    (list[indexA], list[indexB]) = (list[indexB], list[indexA]);
    return list;
}

A: There is no existing Swap-method, so you have to create one yourself. Of course you can linqify it, but that has to be done with one (unwritten?) rules in mind: LINQ-operations do not change the input parameters!
In the other "linqify" answers, the (input) list is modified and returned, but this action brakes that rule. If would be weird if you have a list with unsorted items, do a LINQ "OrderBy"-operation and than discover that the input list is also sorted (just like the result). This is not allowed to happen!
So... how do we do this?
My first thought was just to restore the collection after it was finished iterating. But this is a dirty solution, so do not use it:
static public IEnumerable<T> Swap1<T>(this IList<T> source, int index1, int index2)
{
    // Parameter checking is skipped in this example.

    // Swap the items.
    T temp = source[index1];
    source[index1] = source[index2];
    source[index2] = temp;

    // Return the items in the new order.
    foreach (T item in source)
        yield return item;

    // Restore the collection.
    source[index2] = source[index1];
    source[index1] = temp;
}

This solution is dirty because it does modify the input list, even if it restores it to the original state. This could cause several problems:

*

*The list could be readonly which will throw an exception.

*If the list is shared by multiple threads, the list will change for the other threads during the duration of this function.

*If an exception occurs during the iteration, the list will not be restored. (This could be resolved to write an try-finally inside the Swap-function, and put the restore-code inside the finally-block).

There is a better (and shorter) solution: just make a copy of the original list. (This also makes it possible to use an IEnumerable as a parameter, instead of an IList):
static public IEnumerable<T> Swap2<T>(this IList<T> source, int index1, int index2)
{
    // Parameter checking is skipped in this example.

    // If nothing needs to be swapped, just return the original collection.
    if (index1 == index2)
        return source;

    // Make a copy.
    List<T> copy = source.ToList();

    // Swap the items.
    T temp = copy[index1];
    copy[index1] = copy[index2];
    copy[index2] = temp;

    // Return the copy with the swapped items.
    return copy;
}

One disadvantage of this solution is that it copies the entire list which will consume memory and that makes the solution rather slow.
You might consider the following solution:
static public IEnumerable<T> Swap3<T>(this IList<T> source, int index1, int index2)
{
    // Parameter checking is skipped in this example.
    // It is assumed that index1 < index2. Otherwise a check should be build in and both indexes should be swapped.

    using (IEnumerator<T> e = source.GetEnumerator())
    {
        // Iterate to the first index.
        for (int i = 0; i < index1; i++)
            yield return source[i];

        // Return the item at the second index.
        yield return source[index2];

        if (index1 != index2)
        {
            // Return the items between the first and second index.
            for (int i = index1 + 1; i < index2; i++)
                yield return source[i];

            // Return the item at the first index.
            yield return source[index1];
        }

        // Return the remaining items.
        for (int i = index2 + 1; i < source.Count; i++)
            yield return source[i];
    }
}

And if you want to input parameter to be IEnumerable:
static public IEnumerable<T> Swap4<T>(this IEnumerable<T> source, int index1, int index2)
{
    // Parameter checking is skipped in this example.
    // It is assumed that index1 < index2. Otherwise a check should be build in and both indexes should be swapped.

    using(IEnumerator<T> e = source.GetEnumerator())
    {
        // Iterate to the first index.
        for(int i = 0; i < index1; i++)
        {
            if (!e.MoveNext())
                yield break;
            yield return e.Current;
        }

        if (index1 != index2)
        {
            // Remember the item at the first position.
            if (!e.MoveNext())
                yield break;
            T rememberedItem = e.Current;

            // Store the items between the first and second index in a temporary list.
            List<T> subset = new List<T>(index2 - index1 - 1);
            for (int i = index1 + 1; i < index2; i++)
            {
                if (!e.MoveNext())
                    break;
                subset.Add(e.Current);
            }

            // Return the item at the second index.
            if (e.MoveNext())
                yield return e.Current;

            // Return the items in the subset.
            foreach (T item in subset)
                yield return item;

            // Return the first (remembered) item.
            yield return rememberedItem;
        }

        // Return the remaining items in the list.
        while (e.MoveNext())
            yield return e.Current;
    }
}

Swap4 also makes a copy of (a subset of) the source. So worst case scenario, it is as slow and memory consuming as function Swap2.

A: If order matters, you should keep a property on the "T" objects in your list that denotes sequence.  In order to swap them, just swap the value of that property, and then use that in the .Sort(comparison with sequence property)


text:
Q: How to utilize code flow for OneDrive API? How to allow my C# apps (non-forms, non-web based) application authenticate & interact with OneDrive? (That is to say, completely programmatically.)
So far:
-Application registered, have client id & secret.
-Enabled both web & phone.
-Personal, not Business.
-Client token flow appears to be for interactive, so using code.
-Tried the OneDrive SDK, but it just kept saying it couldn't authenticate (not why).
-Now hand-rolling requests.
As web client code:
    async Task<string> GetStringFromURLAsync(string theURL)
    {
        string urlContents = "";
        System.Net.Http.HttpClient c = null;
        try
        {
            c = new System.Net.Http.HttpClient();
            c.Timeout = new System.TimeSpan(0, 0, 30); // 30 seconds
            Task<string> asyncResp = c.GetStringAsync(theURL);
            urlContents = await asyncResp;
            Console.WriteLine("success...");
        }
        [catch...]
        return urlContents;
    }

Called by:
    Task<string> tGetContent = GetStringFromURLAsync(ai.fullTokenRequestURI);
    string httpResponseBody = tGetContent.Result;

(ai is a struct holding client id, url, etc.)
If it is not possible to roll your own and get the correct responses, then which SDK should I be using?
This fares no better:
    this.oneDriveClient = OneDriveClient.GetMicrosoftAccountClient(
                       authInfo.cient_id,
                       authInfo.redirect_url,
                       authInfo.scopes);
    await this.oneDriveClient.AuthenticateAsync();

The OD API simply complains:
    OneDrive reported the following error:
    Code: AuthenticationFailure
    Message: Failed to retrieve a valid authentication token for the user.


text:
Q: NoSuchMethodException with a Radio Button I'm attempting to write a form, and at one point there are 2 radio buttons asking for the gender of the person. I want to require that at least one button is pressed, or they receive a toast. They appear in the activity_main as such:
<RadioGroup
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <RadioButton
            android:id="@+id/radioButton1"
            android:layout_width="wrap_content"
            android:layout_height="53dp"
            android:layout_weight="1.00"
            android:onClick="onRadioButtonClicked"
            android:text="@string/female" />

        <RadioButton
            android:id="@+id/radioButton2"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="1.00"
            android:onClick="onRadioButtonClicked"
            android:text="@string/male" />
</RadioGroup>

And the relevant code in the MainActivity:
    RadioButton rb1, rb2;
    rb1 = (RadioButton) findViewById(R.id.radioButton1);
    rb2 = (RadioButton) findViewById(R.id.radioButton2);
    if(!rb1.isChecked() && !rb2.isChecked()){
        Toast.makeText(this, "Please select a gender.", Toast.LENGTH_SHORT).show();
        return;
    }

It may be worth noting that I've tried doing the if statement with only one &, and my app still crashes upon clicking a radio button.
Here is the LogCat:
09-11 01:21:26.599: E/AndroidRuntime(821): FATAL EXCEPTION: main
09-11 01:21:26.599: E/AndroidRuntime(821): java.lang.IllegalStateException: Could not find a method onRadioButtonClicked(View) in the activity class com.example.myapplication.MainActivity for onClick handler on view class android.widget.RadioButton with id 'radioButton1'
09-11 01:21:26.599: E/AndroidRuntime(821):  at android.view.View$1.onClick(View.java:3620)
09-11 01:21:26.599: E/AndroidRuntime(821):  at android.view.View.performClick(View.java:4240)
09-11 01:21:26.599: E/AndroidRuntime(821):  at android.widget.CompoundButton.performClick(CompoundButton.java:100)
09-11 01:21:26.599: E/AndroidRuntime(821):  at android.view.View$PerformClick.run(View.java:17721)
09-11 01:21:26.599: E/AndroidRuntime(821):  at android.os.Handler.handleCallback(Handler.java:730)
09-11 01:21:26.599: E/AndroidRuntime(821):  at android.os.Handler.dispatchMessage(Handler.java:92)
09-11 01:21:26.599: E/AndroidRuntime(821):  at android.os.Looper.loop(Looper.java:137)
09-11 01:21:26.599: E/AndroidRuntime(821):  at android.app.ActivityThread.main(ActivityThread.java:5103)
09-11 01:21:26.599: E/AndroidRuntime(821):  at java.lang.reflect.Method.invokeNative(Native Method)
09-11 01:21:26.599: E/AndroidRuntime(821):  at java.lang.reflect.Method.invoke(Method.java:525)
09-11 01:21:26.599: E/AndroidRuntime(821):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
09-11 01:21:26.599: E/AndroidRuntime(821):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
09-11 01:21:26.599: E/AndroidRuntime(821):  at dalvik.system.NativeStart.main(Native Method)
09-11 01:21:26.599: E/AndroidRuntime(821): Caused by: java.lang.NoSuchMethodException: onRadioButtonClicked [class android.view.View]
09-11 01:21:26.599: E/AndroidRuntime(821):  at java.lang.Class.getConstructorOrMethod(Class.java:423)
09-11 01:21:26.599: E/AndroidRuntime(821):  at java.lang.Class.getMethod(Class.java:787)
09-11 01:21:26.599: E/AndroidRuntime(821):  at android.view.View$1.onClick(View.java:3613)
09-11 01:21:26.599: E/AndroidRuntime(821):  ... 12 more

Thanks.

A: Create a method onRadioButtonClicked because you have set onClick in xml. So you must have a method with that name in Activity which can handle the click.
Method
public void onRadioButtonClicked(View v){
    // Your code on click
}

A: Try Below code:
public class MainActivity extends Activity {

  private RadioGroup radioSexGroup;
  private RadioButton radioSexButton;
  private Button btnDisplay;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    addListenerOnButton();

  }

  public void addListenerOnButton() {

    radioSexGroup = (RadioGroup) findViewById(R.id.radioSex);
    btnDisplay = (Button) findViewById(R.id.btnDisplay);

    btnDisplay.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

                // get selected radio button from radioGroup
            int selectedId = radioSexGroup.getCheckedRadioButtonId();

                        if(selected==-1)
                             Toast.makeText(MyAndroidAppActivity.this,
                "Please Select at least one Gender", Toast.LENGTH_SHORT).show();
            // find the radiobutton by returned id
                radioSexButton = (RadioButton) findViewById(selectedId);

            Toast.makeText(MyAndroidAppActivity.this,
                radioSexButton.getText(), Toast.LENGTH_SHORT).show();

        }

    });

  }
}

A: did you define
public void onRadioButtonClicked(View v)

as your line
android:onClick="onRadioButtonClicked"

implies?

A: Define properties onClick in xml file onRadioButtonClicked and access for this method on java file,
public void onRadioButtonClicked(View view) {
    switch (view.getId()) {
    case R.id.YOUR_ID_RADIO_BUTTON:
                    // write here some one code
        break;

    default:
        break;
    }
}


text:
Q: MSSQL C# query Only add row if value is unique I have a simple c# application that writes to a database using the following.
IF EXISTS (SELECT * FROM Table WHERE deviceName='deviceNAMEDATA')
    UPDATE HeartBeat
        SET DeviceName = 'DEVICENAMEDATA',
            LastConnect = 'DATETIMEDATA'
ELSE
    INSERT INTO HeartBeat
        VALUES('DeviceNAMEDATA', 'DATETIMEDATA')

DEVICENAMEDATA and DATETIMEDATA are replaced using a string builder to the name of the device and the time.
I left it running for an hour and everything seemed to be working i was not getting any duplicate records however after leaving it running for 24 hours the database has about 20 duplicate records.
Is there a better way of ensuring that two rows with the same device name are never created ?

A: The problem is your update statement - You are updating both columns instead of using the DeviceName column in the Where clause. It should look like this:
UPDATE HeartBeat
SET LastConnect = 'DATETIMEDATA'
WHERE DeviceName = 'DEVICENAMEDATA'

That being said, you should probably use the DeviceName as the primary key for your table, which will make it impossible for it to have multiple values.
Also, while on the subject of "upsert", you should read Dan Guzman's blog post about how to avoid race condition in "upsert" in SQL Server.
One more thing - you should always specify the columns list in an insert statement.
Here is how I would write this:
SET NOCOUNT, XACT_ABORT ON

BEGIN TRY
BEGIN TRANSACTION

    IF EXISTS
    (
    SELECT *
    FROM Table
    WITH (UPDLOCK, HOLDLOCK)
    WHERE deviceName='deviceNAMEDATA'
    )

        UPDATE HeartBeat
        SET LastConnect = 'DATETIMEDATA'
        WHERE DeviceName = 'DEVICENAMEDATA'
    ELSE
        INSERT INTO HeartBeat (DeviceName, LastConnect)
        VALUES('DeviceNAMEDATA', 'DATETIMEDATA')

COMMIT TRANSACTION
END TRY
BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION
END CATCH

A:
Is there a better way of ensuring that two rows with the same device name are never created ?

Yes, have the database ensure the data integrity using a  a unique constraint/index:
alter table t add constraint unq_t_deviceName unique (deviceName);

You will need to adapt your code to catch errors on the insert.  If this is T-SQL code, you can use a try/catch block.


text:
Q: Converting a template class to a header and cpp file Im trying to convert the following header file into a seperate header and .cpp file.
    template <class T>
class Rolodex {
  public:
    /**
     * Creates a new empty Rolodex
     */
    Rolodex()
    {
        sentinel_ = new Item;
        sentinel_->value_ = T();
        sentinel_->next_  = sentinel_;
        sentinel_->prev_  = sentinel_;
        current_ = sentinel_;
    }

    ~Rolodex()
    {
        while (current_ != sentinel_) {
            delete_current();
        }
        delete sentinel_;
    }

    /**
     * Returns true if the Rolodex is positioned at the beginning.
     */
    bool is_before_first()
    {
        return current_ == sentinel_;
    }

    /**
     * Returns true if the Rolodex is positioned at the end.
     */
    bool is_after_last()
    {
        return current_ == sentinel_;
    }

    /**
     * Rotates the Rolodex one step forwards.
     */
    void rotate_forward()
    {
        current_ = current_->next_;
    }

    /**
     * Rotates the Rolodex one step backwards.
     */
    void rotate_backward()
    {
        current_ = current_->prev_;
    }

    /**
     * Returns the value of the current card.
     */
    const T &current_value()
    {
        return current_->value_;
    }

    /**
     * Inserts a new item after the current position and
     * positions the Rolodex at the newly inserted item.
     */
    void insert_after_current(const T &value)
    {
        Item *coming = new Item;
        coming->value_ = value;
        coming->next_  = current_->next_;
        coming->prev_  = current_;

        current_->next_->prev_ = coming;
        current_->next_ = coming;

        current_ = coming;
    }

    /**
     * Inserts a new item before the current position and
     * positions the Rolodex at the newly inserted item.
     */
    void insert_before_current(const T &value)
    {
        Item *coming = new Item;
        coming->value_ = value;
        coming->prev_  = current_->prev_;
        coming->next_  = current_;

        current_->prev_->next_ = coming;
        current_->prev_ = coming;

        current_ = coming;
    }

    /**
     * Deletes current item and positions the Rolodex
     * at the _following_ item
     */
    void delete_current()
    {
        Item *going = current_;
        current_->prev_->next_ = current_->next_;
        current_->next_->prev_ = current_->prev_;

        if (going->next_ == sentinel_)
            current_ = going->prev_;
        else
            current_ = going->next_;

        delete going;
    }

  private:
    struct Item {
        T value_;
        Item *next_;
        Item *prev_;
    };

    Item *sentinel_;
    Item *current_;
};

#endif /* ROLODEX_H_ */

However when i split them apart, if i don't include
template <class T>

in the header file i get an error trying to declare
T value;

but if i do i get multiple errors in the .cpp file saying Rolodex is not a file class or enumeration. Is there a different type I can use to declare my value; and if so how do i go about modifying the code to fit this. Any help is greatly appreciated im super lost
EDIT: Thank you all for your help, my understanding of the C++ classes was lacking and after some research on the similar threads you provided I fixed my issue.

A: If you don't know how the templates work, I would suggest reading the topic first.
You can define the template class members in a separate .cpp file, but you will also have to instantiate a class for all of the types you will be using. You can do such declaring a simple dummy object in the .h or .cpp file.
// tmpl.h

template <typename T>
struct S {
  S();
  T _a_field;
}

// tmpl.cpp

template <typename T>
S<T>::S() {}

S<int> dummy;

However, this is not a suggested approach. I personally would suggest defining all in a single tmpl.h file or in another file and include it into tmpl.h

A: when using templates  the complete implementation needs to be in the header. You cannot use .cpp files for the method definitions, but if you would still like to separate interface and implementation. You can use .hpp for the class definition, .inl file for the method definitions. At the end of the .hpp file, you have to include the .inl file containing that implementation. You can learn more  here, why template codes cannot be moved to
.cpp file  https://youtu.be/6wdCqNlnMjo


text:
Q: Javascript Closure Problem I know this kind of question gets asked alot, but I still haven't been able to find a way to make this work correctly.
The code:
function doStuff () {
     for (var i = 0; i< elementsList.length; i++) {
        elementsList[i].previousSibling.lastChild.addEventListener("click", function(){
                   toggle(elementsList[i])}, false);

        }
    } // ends function

    function toggle (element) {
        alert (element);
    }

The problem is in passing variables to the toggle function. It works with the this keyword (but that sends a reference to the clicked item, which in this case is useless), but not with elementsList[i] which alerts as undefined in Firefox.
As I understood it, using anonymous functions to call a function is enough to deal with closure problems, so what have I missed?

A: Try:
function startOfFunction() {
    for (var i = 0; i< elementsList.length; i++) {
        elementsList[i].previousSibling.lastChild.addEventListener(
            "click",
            (function(el){return function(){toggle(el);};})(elementsList[i]),
            false
        );

    }
} // ends function

function toggle (element) {
    alert (element);
}

A: The Problem is, that you want to use the var i! i is available in the onClick Event, (since closure and stuff). Since you have a loop, i is counted up. Now, if you click on any of the elements, i will always be elementsList.length (since all event functions access the same i )!
using the solution of Matt will work.

A: As an explanation: the anonymous function you use in the for loop references the variable "i" to get the element to toggle. As anonymous functions use the "live" value of the variable, when somebody clicks the element, "i" will always be elementsList.length+1.
The code example from Matt solves this by sticking the i into another function in which it is "fixated". This always holds true:
If you iterate over elements attaching events, do not use simple anonymous functions as they screw up, but rather create a new function for each element. The more readable version of Matts answer would be:
function iterate () {
    for (var i = 0; i < list.length; i++) {
        // In here, i changes, so list[i] changes all the time, too. Pass it on!
        list[i].addEventListener(createEventFunction(list[i]);
    }
 }

 function createEventFunction (item) {
     // In here, item is fixed as it is passed as a function parameter.
     return function (event) {
         alert(item);
     };
 }

A: Try:
function doStuff () {
    for (var i = 0; i< elementsList.length; i++) {
        (function(x) {
            elementsList[x].previousSibling.lastChild.addEventListener("click", function(){
               toggle(elementsList[x])}, false);
        })(i);

    }
} // ends function

I think it might be an issue with passing elementsList[i] around, so the above code has a closure which should help.


text:
Q: TableView won't send setEditing message to cells So far I have a UITableView, it works properly and all.
My problem is when going into "editing" mode, apparently the cells are not changing at all, and the red sign (delete control) only shows up when I drag the cell out of the tableview (meaning the iphone reloads the cell again, and it is here when it detects that the cell was "flagged" as editing).
The problem is right when I select "edit" button, red controls should show up but they don't.
I did implement the tableview's delegate method for returning a editing type control ( either an insert ot deletion) and no luck.

A: Of course you can use a UIViewController.
in the setEditing:animate Method, simply call
[super setEditing:editing animated:animate];
[self.myTableView setEditing:editing animated:animate];

and you will get those nice little icons ;)

A: Your Controller is probably a subclass of UIViewController not UITableViewController.  As far as I have found thus far is you only get the "free" icons when subclassing a UITableViewController, which is not cool because you cannot mix visual elements on UITableViewController, you only have a tableView.


text:
Q: How do I stop the css transition that happens when the page loads [React] I am trying to make a transition when showing the side navigation and it works fine when opening and closing. The problem is when the page first loads the sidebar is shown withdrawning. Here is the code:

    ☰
    <Transition in={this.state.navStanje} timeout={ 500 }>
    { state =>
    <div className={`navigacija navigacija-${state}`}>
        <Typography variant="h7">×</Typography>

            <Typography style={ profileName }>Ime Prezime</Typography>

        <Typography variant="h4" style={{ color: '#FFEB3B', marginTop: '3%' }}>Neki naslov</Typography>
        About

        Services

        Clients

        Contact

    }
    </Transition>

And here is the CSS I am using:
.navigacija {
  position: fixed;
  top: 8%;
  left: 0;
  height: 100%;
  padding-top: 1%;
  background: #2B3944;
  width: 20%;
  display: block;
  overflow-x: hidden;
  z-index: 2;
  transition: all 0.5s linear;
}

.navigacija.navigacija-entering {
  transform: translateX(0%);
}

.navigacija.navigacija-exited {
  transform: translateX(-100%);
}

How can I prevent the withdrawing of the sidebar when the page loads?

A: Set the initial CSS transform property to transform: translateX(-100%); that way it will initially be hidden


text:
Q: Unsigned and signed integers in C
Possible Duplicate:
Unsigned long with negative value
Assigning negative numbers to an unsigned int?

#include<stdio.h>

int main()
{
    struct a
    {
        unsigned int i:3;
        int c:3;
    }s;
    s.i=5;
    s.c=5;

    printf("s.i=%d\n",s.i);
    printf("s.c=%u\n",s.c);
    unsigned int x = -1;
    printf(" x = %d", x);
    return 0;
}

This outputs:
s.i=5
s.c=4294967293
x=-1

I am not clear about the output of "x" and "s.c"(s.c can store number of 3 bits only but in the output it is giving very large value)."x" is declared as unsigned so the bits stored in x are 1111111....... and the output of x should be a large value instead of -1. 1st printf() statement is giving the result as expected
I am using devc++ compiler.

A: The output depends on the signedness of the format character, not the signedness of the declaration. Think about it: printf can't know whether x was declared int or unsigned int, since no type information is passed in C. So it prints based on how you told it to print. %d is signed, so you get a signed value. With s.c, it's an int so it's signed, but you printed it with %u so it is treated as unsigned.
As for s.i, it is unsigned, so 5 can fit in its 3 bits, so it is passed to printf as 5 without sign extending it, so %d (or %u) prints it as 5.

A: It seems there are two things going on that need to be understood:

*

*printf() conversion specifiers

*Integral conversions

And two more things that help make sense of your output:

*

*Argument promotion for variadic function arguments

*Two's complement representation

First, printf() is a variadic function. It doesn't know what the types of its arguments are (other than the format string), so you have to use conversion specifiers to tell it how to interpret the arguments.  These arguments are subject to the "default argument promotions" such that your 3-bit bit fields are being promoted to ints.
You are using conversions specifiers (%d, %u, and %d) that do not match the signedness of your data, so you will get undefined behavior that depends on how your data is actually represented in memory.
Second, the C11 standard states:

6.3.1.3 Signed and unsigned integers

*

*When a value with integer type is converted to another integer type other than _Bool, if the value can be represented by the new type, it is unchanged.

*Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the new type until the value is in the range of the new type.

*Otherwise, the new type is signed and the value cannot be represented in it; either the result is implementation-defined or an implementation-defined signal is raised.

(As far as I can tell, the details relevant here have been true at least since C89.)
This tells us a couple things about your code:

*

*When you assign -1 to an unsigned int, UINT_MAX + 1 is added to it, giving UINT_MAX, or 4294967295 for 32-bit integers.

*When you try to assign 5 to a 3-bit signed bit field, the result is implementation-defined.
So you've got both undefined and implementation-defined behavior, but we can still try to make sense of your output, just for fun.  I'm assuming 32-bit integers and two's complement representation.
Your system represents the 4294967295 stored in x as 11111111 11111111 11111111 11111111. When you told printf() that the argument you were passing it was signed, those same bits are interpreted as -1, which is the output you got.
For s.c, the implementation-defined behaviour you seem to have gotten is straightforward:
the three bits 101representing 5 got stored as-is.  That means that with the correct conversion specifier, printf() should show s.c as -3.
Here are the values you've assigned:
s.i = 101
s.c = 101
  x = 11111111 11111111 11111111 11111111

The 3-bit values are promoted to 32-bit by left-padding with 0 for the unsigned value and repeating the sign for the signed value:
s.i = 00000000 00000000 00000000 00000101
s.c = 11111111 11111111 11111111 11111101
  x = 11111111 11111111 11111111 11111111

Which, when interpreted as signed, unsigned, and signed integers gives:
s.i=5
s.c=4294967293
x=-1

The x=-1 suggests to me that you are in fact using a two's complement representation (which was a pretty safe bet, anyway), and the output for s.c suggests that your ints are 32 bits wide.


text:
Q: How to check if the checkbox is checked or not in php? i have an if statement as follows
        if($_POST['remember']=="on")
i want to know if this is the correct syntax for checking if the checkbox is checked or unchecked?

A: This code will help you
<input type="checkbox" name="checkbx" <?php if(isset($_POST['remember'])=="on")  echo "checked";?> />

OR
<?php if(isset($_POST['remember'])=="on") {?>
 <input type="checkbox" name="checkbx" checked="checked"  />
<?php }else {?>
    <input type="checkbox" name="checkbx"  />
<?php }?>

A: simple check of isset
if(isset($_POST['remember']) && $_POST['remember']=="on")
{
   // checkbox remember is checked
}
else
{
   // checkbox remember is not checked
}

A: Use
if (isset($_POST['remember'])) {
     // checked
} else {
   not checked
}

A: <input type="checkbox" name="remember" value="YES" />

$remember= ($_POST['remember'] == 'YES')?'YES':'NO';


text:
Q: How do I make .gitlab-ci.yml execute different ansible playbooks in different folders/subfolders? I just started learning about NetDevOps.
All the examples containing demos of GitLAb + Ansible show how to execute "deploy.yml" from Ansible from the .gitlab-ci.yml.
However, when I see a general network equipment based Ansible tutorial the author executes different Ansible cookbook .yml files, for example sites.yml from the root, deploy.yml from another subfolder, interfaces.yml from another subfolder.
Can someone give me an example of how I would execute the different Ansible playbook .yml files on demand?
I.e. - When it detects changes in .yml in a folder, run that .yml file under that folder?

A: lets say you have an ansible repo and a .gitlab-ci.yml in the root of it.
.gitlab-ci.yml
ansible/cookbook1
ansible/cookbook2

For each cookbook you could create a Gitlab job
execute_cookbook1:
 script:
  - ...ANSIBLE COMMANDS...
 ...
 only:
     changes:
       - ansible/cookbook1/**/*.yml

execute_cookbook2:
 script:
  - ...ANSIBLE COMMANDS...
 ...
 only:
     changes:
       - ansible/cookbook2/**/*.yml

This way when you push your code to ansible repo, Gitlab will detect which cookbook changed. And run the according job

A: You can use in your GitLab job complex rules like if, changes, and exists, in the same rule.
The rule evaluates to true only when all included keywords evaluate to true.

For example:
docker build:
 script: docker build -t my-image:$CI_COMMIT_REF_SLUG .
 rules:
   - if: '$VAR == "string value"'
     changes:  # Include the job and set to when:manual if any of the follow paths match a modified file.
       - Dockerfile
       - docker/scripts/*
     when: manual
     allow_failure: true

In your case, keep when: manual and changes: *.yml in order to trigger the job manually, if yml Ansible playbook are changed.


text:
Q: File permissions changing on save ( using root ) Using a fresh installation of CENTOS 6.2, when I connect to the server ( SFTP mount with nautilus ) and edit files, no matter what permission the file had before, it is reset to 700, read+write+execute only for the owner.
When SSHing directly into the machine and editing files on the command line - no permissions are changed.
The files I am editing are website scripts sitting in my Apache folders.
Why is this behavior happening? Any suggestions are welcome.

A: Your FTP client might be "downloading and reuploading" your files when you edit them. Change your umask if you want different permissions, or use SSH and a proper editor if you want to keep the permissions...


text:
Q: Pyinstaller executable opens and immediately closes I am trying to create an executable from a python project with pyinstaller. However, when I run the executable, it just opens and closes immediately.
I don't get one error and two warnings when running pyinstaller from the command line. There are no error messages when running the executable.
(But I don't think that the two warnings should be problematic as I've created other executables with those same warnings and they still worked fine!!)
When I run
pyinstaller --debug=all main.py

I get
12070 WARNING: Hidden import "pkg_resources.py2_warn" not found!
12070 WARNING: Hidden import "pkg_resources.markers" not found!
...
Traceback (most recent call last):
  File "[path]/venv/bin/pyinstaller", line 10, in <module>
    sys.exit(run())
  File "[path]/venv/lib/python3.9/site-packages/PyInstaller/__main__.py", line 126, in run
    run_build(pyi_config, spec_file, **vars(args))
  File "[path]/venv/lib/python3.9/site-packages/PyInstaller/__main__.py", line 65, in run_build
    PyInstaller.building.build_main.main(pyi_config, spec_file, **kwargs)
  File "[path]/venv/lib/python3.9/site-packages/PyInstaller/building/build_main.py", line 815, in main
    build(specfile, kw.get('distpath'), kw.get('workpath'), kw.get('clean_build'))
  File "[path]/venv/lib/python3.9/site-packages/PyInstaller/building/build_main.py", line 762, in build
    exec(code, spec_namespace)
  File "[path]/main.spec", line 37, in <module>
    coll = COLLECT(exe,
  File "[path]/venv/lib/python3.9/site-packages/PyInstaller/building/api.py", line 855, in __init__
    self.__postinit__()
  File "[path]/venv/lib/python3.9/site-packages/PyInstaller/building/datastruct.py", line 159, in __postinit__
    self.assemble()
  File "[path]/venv/lib/python3.9/site-packages/PyInstaller/building/api.py", line 883, in assemble
    os.makedirs(todir)
  File "/usr/local/Cellar/python@3.9/3.9.1_4/Frameworks/Python.framework/Versions/3.9/lib/python3.9/os.py", line 225, in makedirs
    mkdir(name, mode)
NotADirectoryError: [Errno 20] Not a directory: '[path]/dist/main/main/GUI'

When I now run
pyinstaller --hidden-import pkg_resources.py2_warn --hidden-import pkg_resources.markers --debug=all main.py

I get
11705 ERROR: Hidden import 'pkg_resources.py2_warn' not found
11705 ERROR: Hidden import 'pkg_resources.markers' not found
...
Traceback (most recent call last):
  File "[path]/venv/bin/pyinstaller", line 10, in <module>
    sys.exit(run())
  File "[path]/venv/lib/python3.9/site-packages/PyInstaller/__main__.py", line 126, in run
    run_build(pyi_config, spec_file, **vars(args))
  File "[path]/venv/lib/python3.9/site-packages/PyInstaller/__main__.py", line 65, in run_build
    PyInstaller.building.build_main.main(pyi_config, spec_file, **kwargs)
  File "[path]/venv/lib/python3.9/site-packages/PyInstaller/building/build_main.py", line 815, in main
    build(specfile, kw.get('distpath'), kw.get('workpath'), kw.get('clean_build'))
  File "[path]/venv/lib/python3.9/site-packages/PyInstaller/building/build_main.py", line 762, in build
    exec(code, spec_namespace)
  File "[path]/main.spec", line 37, in <module>
    coll = COLLECT(exe,
  File "[path]/venv/lib/python3.9/site-packages/PyInstaller/building/api.py", line 855, in __init__
    self.__postinit__()
  File "[path]/venv/lib/python3.9/site-packages/PyInstaller/building/datastruct.py", line 159, in __postinit__
    self.assemble()
  File "[path]/venv/lib/python3.9/site-packages/PyInstaller/building/api.py", line 883, in assemble
    os.makedirs(todir)
  File "/usr/local/Cellar/python@3.9/3.9.1_4/Frameworks/Python.framework/Versions/3.9/lib/python3.9/os.py", line 225, in makedirs
    mkdir(name, mode)
NotADirectoryError: [Errno 20] Not a directory: '[path]/dist/main/main/GUI'

I've been stuck at this problem for days and at this point I really don't know what to do!

My system specs:

*

*MacOS 11.5.2

*Python 3.9

*pyinstaller 4.5.1 (Python package)

*setuptools 57.5.0 (Python package)

*PyQt5 5.15.4 (Python package)

*pyqtgraph 0.12.2 (Python package)

I am running everything in a virtual environment.
My project structure is:
Project
|- dist
|- build
|- main.spec
|
|- main.py
|- main
|  |- GUI
|     |- MainWindow.py
|     |- ui.py
|  |- Sim
|     |- Setter.py
|     |- Integrator.py

A: The executable works now after I changed the name of the directory main from main to MainPackage.
I think the error was that my entry-point main.py had the same name as the directory main (which contains the other code that is called). So pyinstaller confused the directory with the entry-point file.
Also, I didn't have to include the two hidden imports for the executable to work (as suspected). The command to build the executable is simply:
pyinstaller main.py


text:
Q: How to flag for migration to serverfault? When I flag a post I can't seem to flag it to migrate to serverfault.com.
Strange I can flag it to
     belongs on meta.stackoverflow.com
     belongs on superuser.com
     belongs on tex.stackexchange.com
     belongs on dba.stackexchange.com
     belongs on sharepoint.stackexchange.com

These are the only options I get ?
Any reason for that. How do you migrate to ServerFault?

A: Flag for moderation attention and ask for migration to Server Fault, the off topic list only includes Meta and the four most common migration targets. Keep in mind that questions that are on topic on Stack Overflow will not be migrated, even if they are on topic on an other site, and that sub par questions will not be migrated in general.
Lastly; migration for questions older than 60 days is disabled (even for moderators).


text:
Q: Can the word "ignorant" be used as a noun? Googling would suggest that it can, but believing everything you read on the Internet is a risky business. I have the Concise Oxford English Dictionary eighth edition 1990 and a Chambers Twentieth Century Dictionary from 1977 and neither of them list the word ignorant as a noun. Sadly I do not have access to the full OED as my local library has just closed.
I saw the word used by a native Hindi speaker, and I think it is being used as a synonym of ignoramus. It may well be that this is accepted usage in Indian English.
A quick footnote:
WS2 makes the excellent point that ignorant can be used as noun in phrases like:

He is the kind of politician who relies on the ignorant for support

So that answers my question in the affirmative. However the way I saw the word being used was more like:

You are an ignorant

I would be interested to know if this is proper use of English, or possibly a proper use of Indian English

A: Ignorant is  an adjective, Etymonline cites its usage as a noun also. I think it is an archaic usage. Note that the Spanish (ignorante) and the Italian (ignorante) are both adjectives and nouns, so the Google results might be from inaccurate translations:

*

*late 14c., "lacking wisdom or knowledge; unaware," from Old French ignorant (14c.), from Latin ignorantem (nominative ignorans) "not knowing, ignorant," present participle of ignorare "not to know, to be unacquainted; mistake, misunderstand; take no notice of, pay no attention to," from assimilated form of in- "not, opposite of" (see in- (1)) + Old Latin gnarus "aware, acquainted with" .

*Form influenced by related Latin ignotus "unknown, strange, unrecognized, unfamiliar." Colloquial sense of "ill-mannered, uncouth, knowing nothing of good manners" attested by 1886. As a noun, "ignorant person," from mid-15c.

A: To get a sense of historical use of ignorant as a noun, I ran a Google Books search for the plural form ignorants—and found a fair number of matches, stretching back to the 1600s. Here are some examples from various points along the timeline.
From John Seldon, The Historie of Tithes: That Is, the Practice of Payment of Them, the Positiue Laws Made for Them, the Opinions Toching the Right of Them (1618):

Therefore I suppose (if he haue not studied the Laws, or otherwise know it) he will rather take some minuts pains then blame me for not turning it. and howsoeuer to diuers peeuish Ignorants, out of their daintie stomachs, and a pretence of nothing but the more polished literature, it may here seem barbarous and distastefull; ... If to so great a man [Father Gregorie] that curious language could seeme no pleasanter when he studied it, it is the lesse wonder that the Law French (which doth as truly and fully deliuer the matter in our Lawes, as the Latin in the Imperialls ; though indeed farre from polite expression) should bee so contemptible among the many petie Ignorants which vsually despise what euer their lazie course of studies hath not furnisht them withall, ...

From Edward, Lord Bishop of Cork & Rosse, A Practical and Plain Discourse of the Form of Godliness, Visible in the Present Age, and of the Power of Godliness (1683):

Now there is no doubt but both and all thefe, our Church ignorants, and our Outlying-ignorants, and that whether through supine negligence and sloth, or through resolute design and obstinacy, all of them, I say, Deny the Power of Godlineß, whatsoever they may have or retain of the Form : For they stop the very first passage by which Godlineß can come to their hearts, or ever have any power over them ; namely they suffer it not to enter into their Understandings.

From Abraham Cowley, "Bathing in the River," in The Mistress: Or, Several Copies of Love-Verses (1720):

Why to Mute Fish should'st thou thy self discover,/ And not to me thy no less silent Lover?/ As some from Men their buried Gold commit/ To Ghosts that have no use of it!/ Half their rich Treasures so/ Maids bury; and for ought we know/ (Poor Ignorants) they're Mermaids all below.

From "Debate in the Lords on the State of the Civil List" (March 14, 1770), in The Universal Magazine of Knowledge and Pleasure (1770) [combined snippets]:

The Earl of Chatham spoke in support of the motion. ... In every other respect, the minute and particular expences of the Civil List are as open to Parliamentary examination and inquiry, in regard to the application and abuse, as any other grant of the people to any other purpose; and Ministers are equally or more culpable for incurring any unprovided expence, and for running in arrear this service, as for any other. The preambles of all the Civil-list acts prove this, and none but children, novices, or ignorants, will ever act without proper regard to it; and, therefore, I can never consent to increase fraudulently the Civil establishment under pretence of making up deficiencies; ...

From J. Ewing Ritchie, "The French Revolution of February," in The Metropolitan Magazine (April 1848):

And so wretched was the instruction given [in France], that we find a large proportion of the criminals amongst the educated, and not the uneducated classes. In the most ignorant of the French departments, Correze, with eight hundred and four ignorants in one thousand young men of twenty-one years of age, there was but one criminal in ten thousand three hundred and sixty inhabitants. In the department of Creuse, where the ignorants were six hundred and twenty-one to one thousand, there was but one criminal in twenty-one thousand inhabitants; whilst in the Seine Inferieure, with three hundred and forty-six ignorants, and Seine et Marne with two hundred and twenty-eight, the proportion was four thousand four hundred and ninety-six inhabitants for one criminal, in the first, and in the second, six thousand one hundred and ninety-four. The general average of departmental criminal statistics gave one convict for every six thousand three hundred and seventy-nine inhabitants, and four hundred and eighty-four ignorants in one thousand men; while in the forty-three least criminal departments, the ignorants ere five hundred and eighteen in one thousand, and one convict in eleven thousand eight hundred and twenty-nine inhabitants.

From Seymour Supercern, Truth Will Out: An Emergence from Chaos and Subterfuge Into Light and Reality (1912):

Hypocrisy! mean, sneaking weasel, means self-deteriment,/ But Bigotry means self-annihilation, as 't has meant,/ In times gone by when nations slaughtered, slew, like fiends run loose,/ Harangued and tortured, murdered, butchered at the slightest ruse,/ As 't has meant when ignorants, those would-be pious pests,/ Fall down with faces in the bogs, callous to all behests,/ To rise them up from foul and festering filth, where all is night,/ Cimmerian as a Stygian realm; ah, pity 'pon the bigot's plight!/ As it now means, as it has meant, still grovelling in the bog,/ Till grown to it, like marshy mosses to a swamp-lain log./ Though mitigated nowaday if not eradicate,/ It still holds sway 'mongst unenlightened and 'twill not abate,/  Until the ignorants will be enlightened in such wise,/ As to make them see through things alone, a self-wrought willful rise.

From American Scientist (1942) [snippet view]:

Here is how they begin:

The stochastic theory of rumours, with interacting subpopulations of ignorants,  spreaders and stiflers, began with the seminal paper of Daley and Kendall.

...
Spreaders communicate the rumor to ignorants, turning them into spreaders; when two spreaders meet, both become stiflers; a spreader who meets a stifler also becomes a stifler. The process begins with a single spreader in a sea of ignorants.

From Intrapreneurial Excellence (1985) [combined snippets]:

The Innovation Ignorants. Made up of some of America's best known companies, this group of firms still does not appreciate the close correlation between longer-term growth in return on equity, sales, and earnings and the skills required in the management of innovation. Typically nothing will change the behavior of the innovation ignorants until one of two things happens. Either they get into serious trouble in their markets and are forced to say, "We've got to learn to manage change," or they experience a change in leadership that leads to a new set of organizational values.

From Arnulf Depperman, "Using the Other for Oneself: Conversational Practices of Representing Out-Group Members Among Adolescents," in Selves and Identities in Narrative and Discourse (2007):

Just before the transcript starts, one part of the youngsters (the "savants") played a trick on the others ("the ignorants") by requesting them to hand them objects (a bottle, a toy cow, etc.) that the savants had glued to the walls and to the desk of the caravan. The ignorants' failure to lift the objects pleased the savants, while the ignorants reacted with irritation (see Mark's insult in line 01).

Conclusions
From these results it appears that ignorant[s] was in general use in the 1600s and on through the early decades of the 1800s, with the meaning "ignorant person [or people]." Noah Webster, A Compendious Dictionary of the English Language (1806) offers this entry for the word as a noun referring to a type of human being:

Ignorant, n. one who is untaught or unskilled.

In more-recent decades, the term ignorant[s] has popped up in the fields of psychology, business, and social science—in each case with a fairly narrow and specialized meaning.
The upshot of all this is that, although a great many native English speakers would view calling someone "an ignorant" as nonstandard English, the word used as a noun and applied to people has a past and a present in the language—and may very well have a future, too.

A: In theory any adjective can be employed as a noun—in fact, until the middle of the 18th century western grammatical theory put adjectives in the same category as nouns, distinguishing only between 'adjective' and 'substantive' uses of the noun. And in many modern European languages adjectives are employed as nouns very freely: in German, for instance, the only difference between an adjective and a noun is that the noun is capitalized—der arme Mann and der Arme both represent E 'the poor man'. French (le pauvre) doesn't even make that distinction.
However, English does differ from other languages in restricting nominal use to adjectives which represent readily recognized categories. The poor, the rich, the ignorant are acceptable collective nouns, designating all poor/rich/ignorant people, but we do not ordinarily use the rich to designate a specific rich person. That sort of use occurs only in discourses where the adjective has previously been established as categorial. For instance:

Do you want one of the red t-shirts or a black one?
  I'll have a red.

CGEL treats this sort of use as an instance of the adjective fusing with its implied head, just as determinatives like which and some fuse with their implied heads to constitute pronouns.

A: If I were to come across someone using the word "ignorant" as a noun in speech, I would assume that they were not native English speakers. If I am helping someone learn how to more properly use English, then I would tell them that this usage was incorrect.
 Edit - You mentioned that this Indian man used the word as a synonym for ignoramus. When I imagine the scenario, I hear him speaking in the second person: "No, you know nothing. You ignorant." Or, "She said that the New Testament had five Gospels, she is an ignorant." In either of these cases, usage as a noun is not common. In the case of the ignorant you do not have a noun in the common sense because "Politicians rely on the support of the ignorant" implies a noun that isn't there but is understood in context: "Politicians rely on the support of the ignorant constituents."
If I and my girlfriend are sorting red and blue beads, during the course of the conversation I might say "I'll sort the red, you sort the blue." When an adjective is used in this way it is only technically a noun and has no bearing on your question.

A:
He is the kind of politician who relies on the ignorant for support.

I always understood "ignorant" here to be an adjective with an implied noun: people, men, voters, etc.
So:

He is the kind of politician who relies on the ignorant voters for support.

A: It should be both. The word has a latin origin, and in Latin languages, it is used to describe an scenario where the ignorance is present or an individual, situation, being (animated or not) or just to address the person who makes exercise of the Ignorance...the ignorant produces ignorance. In my native Spanish language you can say: El es muy ignorante/ Él es el ignorante. He is very ignorant/He is the ignorant. The history is already giving us an antecedent with those text some of you quoted, not Commonly used doesn't mean it should be wrong. I like to use the sentence frolicking gaily and some people ask whether that's English or not. Equivalent to "Retozando alegremente" something you will probably never hear in your life.
I'm no authority, but rather a languages enjoyer.


text:
Q: How to bind port 80 for my tomcat 7 on centos 7 log:
Dec 05, 2015 2:22:10 PM org.apache.catalina.core.StandardService initInternal
SEVERE: Failed to initialize connector [Connector[HTTP/1.1-80]]
org.apache.catalina.LifecycleException: Failed to initialize component [Connector[HTTP/1.1-80]]
        at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:106)
        at org.apache.catalina.core.StandardService.initInternal(StandardService.java:559)
        at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:102)
        at org.apache.catalina.core.StandardServer.initInternal(StandardServer.java:813)
        at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:102)
        at org.apache.catalina.startup.Catalina.load(Catalina.java:638)
        at org.apache.catalina.startup.Catalina.load(Catalina.java:663)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:497)
        at org.apache.catalina.startup.Bootstrap.load(Bootstrap.java:280)
        at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:454)
Caused by: org.apache.catalina.LifecycleException: Protocol handler initialization failed
        at org.apache.catalina.connector.Connector.initInternal(Connector.java:980)
        at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:102)
        ... 12 more
Caused by: java.net.BindException: Permission denied <null>:80
        at org.apache.tomcat.util.net.JIoEndpoint.bind(JIoEndpoint.java:411)
        at org.apache.tomcat.util.net.AbstractEndpoint.init(AbstractEndpoint.java:640)
        at org.apache.coyote.AbstractProtocol.init(AbstractProtocol.java:434)
        at org.apache.coyote.http11.AbstractHttp11JsseProtocol.init(AbstractHttp11JsseProtocol.java:119)
        at org.apache.catalina.connector.Connector.initInternal(Connector.java:978)
        ... 13 more
Caused by: java.net.BindException: Permission denied
        at java.net.PlainSocketImpl.socketBind(Native Method)
        at java.net.AbstractPlainSocketImpl.bind(AbstractPlainSocketImpl.java:387)
        at java.net.ServerSocket.bind(ServerSocket.java:375)
        at java.net.ServerSocket.<init>(ServerSocket.java:237)
        at java.net.ServerSocket.<init>(ServerSocket.java:181)
        at org.apache.tomcat.util.net.DefaultServerSocketFactory.createSocket(DefaultServerSocketFactory.java:49)
        at org.apache.tomcat.util.net.JIoEndpoint.bind(JIoEndpoint.java:398)
        ... 17 more

And I followed the instruction here to install tomcat.
It seams that I should grant permissions to my tomcat but how?  And when I googled this problem, many says that I should modify this file /etc/defaults/tomcat7 But, I do not have this file on my centOS 7.
Thanks for your help.

A: I found a solution by forwarding:
firewall-cmd --zone=public --add-forward-port=port=80:proto=tcp:toport=8080 --permanent
and
firewall-cmd --reload