text:
Q: how to pass the Integrity error django and DRF without stoping execution raising the error I am byulding an API using django and DRF my code is this
models.py
class Company(models.Model):
    """Company object."""
    name_company = models.CharField(max_length=255)
    symbol = models.CharField(max_length=10, unique=True)
    cik = models.CharField(max_length=150, blank=True)
    sector = models.CharField(max_length=150, blank=True)
    industry_category = models.CharField(max_length=150, blank=True)
    company_url = models.TextField(blank=True)
    description = models.TextField(blank=True)

    def __str__(self):
        return self.name_company

views.py
class CompanyViewSet(viewsets.ModelViewSet):
    """View for manage company APIs."""
    serializer_class = serializers.CompanyDetailSerializer
    queryset = Company.objects.all()
    authentication_classes = [TokenAuthentication]
    permission_classes = [IsAuthenticated]

    def get_serializer_class(self):
        """Return the serializer class for request."""
        if self.action == 'list':
            return serializers.CompanySerializer

        return self.serializer_class

    def perform_create(self, serializer):
        """Create a new Company."""
        try:
            serializer.save()
        except IntegrityError:
            print('Symbol exists already.')
            pass

serializers.py
class CompanySerializer(serializers.ModelSerializer):
    """Serializer for Company."""

    class Meta:
        model = Company
        fields = [
            'id', 'name_company', 'symbol', 'cik', 'sector',
            'industry_category', 'company_url',
        ]
        read_only_fields = ['id']

    def create(self, validated_data):
        try:
            instance, created = Company.objects.get_or_create(**validated_data)
            if created:
                return instance
        except IntegrityError:
            pass

class CompanyDetailSerializer(CompanySerializer):
    """Serializer for Company details."""

    class Meta(CompanySerializer.Meta):
        fields = CompanySerializer.Meta.fields + ['description']

And right now i am doing unit tests using in this file.
test_company.py
def create_company(**params):
    """Create and return a sample company."""
    defaults = {
        'name_company': 'Apple',
        'symbol': 'AAPL',
        'cik': '0000320193',
        'sector': 'Technology',
        'industry_category': 'Consumer Electronics',
        'company_url': 'https://www.apple.com/',
        'description':'',
    }
    defaults.update(params)

    company = Company.objects.create(**defaults)
    return company

def test_retrieve_companies(self):
        """Test retrieving a list of Companies."""
        create_company()
        create_company()
        create_company(
            name_company='Tesla',
            symbol='TSLA',
        )

        res = self.client.get(COMPANIES_URL)

        companies = Company.objects.all().order_by('id')
        serializer = CompanySerializer(companies, many=True)
        self.assertEqual(res.status_code, status.HTTP_200_OK)
        self.assertEqual(res.data, serializer.data)

I am getting IntegrityError, what i want is that the run time continue without stopping execution raising the error that is why i am testing it inserting APPLE twice.

I am trying to catch the error with this code in the views.py but does not catch it.

def perform_create(self, serializer):
"""Create a new Company."""
try:
serializer.save()
except IntegrityError:
print('Symbol exists already.')
pass
my error is this:

django.db.utils.IntegrityError: duplicate key value violates unique constraint "core_company_symbol_50a489f1_uniq"
DETAIL:  Key (symbol)=(AAPL) already exists.

Thank you in advance.


text:
Q: Troubles Writing A Proper jQuery Plugin I'm in the process of rewriting a jQuery plugin to be used in an RSS reader I'm building during an internship. This plugin uses Google's Feed API to pull a JSON-formatted RSS feed and return it to the developer, allowing them fine-tuned control over how that feed is displayed on the webpage. I have been following the official jQuery Plugin Authoring page as a reference.
On the reference page, code examples say that you need to add your plugin to jQuery's prototype: $.fn. Here's what I've done:
(function($) {
    "use strict";

    $.fn.rssObj = function(newUrl) {
        var RSSFeed = function(newUrl) {
            /*
             * An object to encapsulate a Google Feed API request.
             */

            this.feedUrl = newUrl;
        };

        RSSFeed.prototype.load = function() {
            var feed = new google.feeds.Feed(this.feedUrl);
            feed.load(function(result) {
                console.log(result);
            });
        };

        return new RSSFeed(newUrl);
    };

})(jQuery);

When I attempt to use this plugin by executing $.rssObj("http://rss.test.com"), my browser gives me this error:
$.rssObj() is not a function

What am I doing wrong?

A: You add to $.fn if you want your function to be available on jQuery instances (e.g., the objects you get back from $("your selector here") and such). If you want your function available from the $ object directly, you add it directly to it.
Here's an example showing each:

// Creating the plugin
(function($) {

  // This will be on *instances*
  $.fn.green = function() {
    // `this` is the jQuery instance we were called on
    return this.css("color", "green");
  };

  // This will be on the $/jQuery object itself
  $.blue = function(selector) {
    // You don't use `this` here (you could if you want,
    // it will be === $/jQuery, but there's no reason to)
    $(selector).css("color", "blue");
    return this;
  };

})(jQuery);

// Usage
jQuery(function($) {

  // Make all divs green with a border
  $("div").green().css("border", "1px solid green");

  // Make all paragraphs blue
  $.blue("p");

});

I'm a div

I'm a paragraph

A: See where I've done exactly what the author was wanting to do here! I simply used this template I've been using for years:
(function($) {
    if (!$.myExample) { // check your plugin namespace does not already exist
        $.extend({  //  this will allow you to add your plugin to the jQuery lib
            myExample: function(elm, command, args) {
                //  keep in mind, right here you might want to do a class or data check to determine which direction this call is going
                //  for example, upon init the plugin on an element you may add the plugin name as a class,
                //      this way, when it's recalled, you can see it alrady has that class and might be calling a command,
                //          thus make an if statemnt to push the process through
                return elm.each(function(index){
                    // do work to each element as its passed through
                    // be sure to use something like
                    //    return elm.each(function(e) { dor work });
                    // as your final statement in order to maintain "chainability"
                });
            }
        });
        $.fn.extend({   //  this gives the chainability functionality seen with $ funcs like: $("#eleID").css("color", "red") <--returns original element object
            myExample: function(command) {
                return $.myExample($(this), command, Array.prototype.slice.call(arguments, 1));
            }
        });
        $.myExample.props = {   //  Here you can establish specific properties to your plugin, prehaps even make them "Over-writable"
            key1: "value",
            key2: "value"
        };
        $.myExample.methods = { //  Here you can establish specific methods/functions for your plguin to carry out and maintain your namespace as well
            key1: function(param) {
                /*  do work */
            },
            key2: function(param) {
                /*  do work */
            }
        };
        //  This next part is not seen in many plugins but useful depending on what you're creating
        $.myExample.init = function(param) {    //  If you have an initialize method to apply, namespace it in here and calll on initializing your plugin
            var key = "value",
                key2 = {
                    subKey: "value"
                };
                /*
                /  run any number of initializing functions here
                /  I prefer to make my param a value that can be a
                /   string with a possible object
                /   the string for holding a base configuration
                /   the object for any change in properties or base values for that config
                */
        };
        $.myExample.defaults = {    //  establish base properties here that can be over-written via .props, but their values should never truly change
            key1: "value",
            key2: {
                prop1: {
                    subKey1: "value",
                    subKey2: "value"
                },
                prop2: {
                    subKey1: "value"
                }
            },
            key3: function(param) {

            }
        };
    }
})(jQuery);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Excel: Formula to place a random number in an array This one has got me seriously stumped, so I thought I'd share it with you guys and see what I get :)
General Problem
I have the following data in a spreadsheet
As you can see I have two identical sets of headings 'Cat, Dog, Man...' (the precise names do not matter)
These two sets are classed under either the 'From' column or the 'To' row.
The bulk of the table is an array of numbers between 0 and 1, or empty cells.
Essentially what I want to do is find where a given Rand() number ranks along each row. I then return the item from the 'To' row corresponding to where the random number would be placed.
i.e. Reading along the 1st Cat row, a random number (between 1 and 0 too) is ranked. If it's,say, between 0 and 0.3658... I return Cat, 0.7193... and 1 gives me Van
So ideally I return the value from the To set of headings which is vertically above the upper bound within which the Rand() number lies.

Attempted Solution
To achieve this ranking I've been using the Match(value,array,0) function (0 as my numbers are in ascending order).
A simplified version of my formula is therefore:
=Index(To_Headings,MATCH(RAND(),From_Row,0))
where To_Headings is the array E3:I3 and From_Row is an array I generate using a further formula, resulting in D#:I# (# being a row number which is related to the From headings, so must be an integer between 4 and 8)
However if you are particularly observant, you can see this is where my solution falls short
As I say,ideally I want to find the upper bound of where RAND() lies, as this is always in the same column as my desired output To heading. MATCH() with a parameter of 0 returns the lower bound of where RAND() lies. Typically this is the column 1 to the left of the desired column.
e.g. Reading along the Cat row again - for a random number of 0.5, bounds within which it lies are 0.3658... and 0.7193... .The upper bound is directly below Dog, my desired output. The lower is 1 column to the left of the desired 1, so in my formula I simply shift back to the right when reading off using Index

HOWEVER the blank cells render this useless. For a random number between 0.719... and 1, the lower bound is now two columns to the left of the upper bound. In other instances it can be 3 or 4, in fact any number. This is because the blank cells push the upper bound further right.

Right, bearing all that in mind, can anyone tell me how to rank the RAND() number so it gives me the upper bound? Of course I've tried Match with -1 as the parameter, however because that requires descending order the problem flips too!
I'm thinking I could try counting if there are any blanks to the right of the lower bound, and offsetting my INDEX by that many instead of just 1, but I can see that will add a lot of lines to my code, and I really need to keep it streamlined, as it will be running in about 10000 cells!!

A: You can use this array formula.
Since your data is arranged in ascending order, this will find the first cell in which the random number is less than or equal to the number in the dataset:
=INDEX($E$3:$I$3,MATCH(TRUE,$J$2<=E4:I4,0))

Being an array formula it must be confirmed with Ctrl-Shift-Enter instead of Enter when exiting edit mode.  If done correctly then Excel will put {} around the formula.

A: I've found another very simple answer through experiment with the Match function.
All you have to do is fill those blanks with the number on the left. Since Match doesn't look for the first instance of a number greater than the random number, but instead the last, by filling in the blanks all the adjustment is done for you.
So the example picture now becomes the following:

So for example, reading along the Cat row again, 0.719... is repeated. For a random input of 0.8, instead of stopping at the Dog column as before (since 0.8<1, therefore 0.719... is the biggest number smaller than the random input), the formula now stops 1 column to the left of the Upper bound every time.
Now I admit @ScottCraner gave a perfect answer to my problem as stated, however an Array formula is stuck to only one size (without VBA) whereas cell formulae can automatically fill a new range, so for my application I cannot use that answer. So I thought I'd add on this solution as a cell formula approach.


text:
Q: Duplicate records from element in a list using Python I have been working on a functionality to get the synonyms from a data set or sample using the following snippet and want to print Concepts and related Synonyms but the actual output is printing it twice making it difficult to understand.
Code :
for rt in self.raw_tokens:
            concept = None
            if rt.startswith('<'):
                # if it's a concept (entity):
                if 'value' in ElementTree.fromstring(rt).attrib:
                    string_token = ElementTree.fromstring(rt).text
                    concept = ElementTree.fromstring(rt).tag
                # if it's a synonym, just use the text and strip the tag from the sample:
                else:
                    string_token = ElementTree.fromstring(rt).text
                    #print('Token: [' + rt + ']')
                    print("Concepts & Synonyms are present in the sample :<%s> = %s" %(ElementTree.fromstring(rt).tag,string_token))
                    #print('CONCEPT: ' + concept)
            else:
                    string_token = rt
            toks.append((concept, string_token))

Expected output :
Concepts & Synonyms are present in the sample :<<I_LOVE>I like</I_LOVE>> = I like
Concepts & Synonyms are present in the sample :<<I_WANTS>NEED</I_WANTS>> = NEED
Concepts & Synonyms are present in the sample :<<NEW_YORK>NEW YORK</NEW_YORK>> = NEW YORK
Concepts & Synonyms are present in the sample :<<I_WANTS>wish</I_WANTS>> = wish
Concepts & Synonyms are present in the sample :<<NEW_YORK>BIG APPLE</NEW_YORK>> = BIG APPLE

Current :

Concepts & Synonyms are present in the sample :<<I_LOVE>I like</I_LOVE>> = I like
Concepts & Synonyms are present in the sample :<<I_WANTS>NEED</I_WANTS>> = NEED
Concepts & Synonyms are present in the sample :<<NEW_YORK>NEW YORK</NEW_YORK>> = NEW YORK
Concepts & Synonyms are present in the sample :<<I_WANTS>wish</I_WANTS>> = wish
Concepts & Synonyms are present in the sample :<<NEW_YORK>BIG APPLE</NEW_YORK>> = BIG APPLE
Concepts & Synonyms are present in the sample :<<I_LOVE>I like</I_LOVE>> = I like
Concepts & Synonyms are present in the sample :<<I_WANTS>NEED</I_WANTS>> = NEED
Concepts & Synonyms are present in the sample :<<NEW_YORK>NEW YORK</NEW_YORK>> = NEW YORK
Concepts & Synonyms are present in the sample :<<I_WANTS>wish</I_WANTS>> = wish
Concepts & Synonyms are present in the sample :<<NEW_YORK>BIG APPLE</NEW_YORK>> = BIG APPLE

Any suggestions how to make it print unique sample ?

A: This is what I meant by using a Set:
toks = set()
for rt in self.raw_tokens:
            concept = None
            if rt.startswith('<'):
                # if it's a concept (entity):
                if 'value' in ElementTree.fromstring(rt).attrib:
                    string_token = ElementTree.fromstring(rt).text
                    concept = ElementTree.fromstring(rt).tag
                # if it's a synonym, just use the text and strip the tag from the sample:
                else:
                    string_token = ElementTree.fromstring(rt).text
            else:
                    string_token = rt
            if not (concept, string_token) in toks:
                print("Concepts & Synonyms are present in the sample :<%s> = %s" %(concept,string_token))
                toks.add((concept, string_token))


text: Q: How to have checkstyle fail on blank lines between annotations and what they're annotating? I recently received a PR that had a couple field-based annotations separated with blank lines, leaving the annotations looking like they had nowhere to go. I've checked the existing checkstyle rules and searched Google but can't really find anything (and my regex skills are non-existent). So, anyone know how to make sure the annotations are not separated with blank lines?!


text:
Q: Running PHP code on certain Drupal nodes My Drupal 6 installation has the php filter disabled so I can't use <?php ... ?> in the node itself.
I have a case where I need to run a little bit of PHP code on a small number of pages. Is there a way in Drupal 6 to create a module that will match a URL pattern and then before showing the page execute a function?
Specifically, on a few pages I need to process some data and then send an HTTP header. I know that I can create a custom .tpl file for these pages but putting application logic like this in a .tpl file feels like a hack.

A: If you want to do this specifically for node pages then you'd be better off implementing hook_nodeapi(). This would mean you don't have to perform a match based on the URL and you can add your header in the most 'structured' manner possible:
function MYMODULE_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  if ($op == 'view') {
    drupal_set_header('some header');
  }
}

If you need to do it for non-node pages then you'll want to implement hook_init() instead:
function MYMODULE_init() {
  if ($_GET['q'] == 'node/1') { // or whatever path
    drupal_set_header('some header');
  }
}

Both of the hooks are invoked well before the headers are sent to the client so either way will work.


text:
Q: How to implement a switcher/viewstack component with slot? I'm trying to implement a 'switcher' or 'viewstack' component in Aurelia, this would be useful for wizards, paged content, and stepping through a list of tasks. This would show a single child component at a time from a number of possible children. I'd like the usage markup to resemble:
<my-switcher>
    <one-component></one-component>
    <two-component></two-component>
    <three-component></three-component>
</my-switcher>

Now, the obvious alternatives here are:

*

*<compose view-model.bind="currentStep"> and point the currentStep variable to each component at a time.
(+ves: components are only instantiated when accessed, -ves: needing to know the path for each component, all children need to be valid view-models)

*Add an if.bind='active' within the definition of each component in the slot, and just set this active member from the my-switcher class. (+ves: easier to follow, -ves: components need to be specifically written for use here).

*Retrieve the children via @children (if this now works reliably?) and add the Element as a child DOM element manually, then call ViewCompiler.enhance. (-ves: can't seem to get get @children to work, larger amount of custom code)

Each of these feels a bit contrived a solution. Does anyone have any idea about whether there a cleaner approach that could/should be used instead?

A: Combine options 2 and 3 while avoiding the negatives (not sure why you can't get @children to work).
consumer.html
<my-switcher>
    <my-switcher-item>
        <one-component></one-component>
    </my-switcher-item>
    <my-switcher-item>
        <two-component></two-component>
    </my-switcher-item>
    <my-switcher-item>
        <three-component></three-component>
    </my-switcher-item>
</my-switcher>

my-switcher-item.js
export class MySwitcherItem {
    constructor() {
        this.isActive = false;
    }
}

my-switcher-item.html
<template show.bind="isActive">
    <slot></slot>
</template>

my-switcher.js
import {children} from 'aurelia-framework';

export class MySwitcher {
    @children('my-switcher-item') items = [];

    // Here you have access to this.items[index].isActive.

    // You can set this value to true or false from this class
    // and make sure only one item's isActive is true.

    // You could add next() and previous() methods to move between
    // the items, etc.
}


text:
Q: Is there a way to make this bruteforce password cracker faster? So I'm pretty new to c++, and this is the second program I've ever written in it.  The first program was a complete mess but it worked, this program I decided to just put all in one file.  My problem is, it just runs incredibly slowly.  I'm pretty sure it's because of just how many characters it has to iterate through, but the requirements are that it can crack a password of a specific length with any special characters like these.  Other than the number of characters it has to go through I'm not sure what, if anything, is making it run so slowly.  I'm wondering if it's something I've done that is improper and making it take so long.  Is this just about how fast a password cracker like this can run?
// Password Cracker.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include <string>
#include <thread>
#include <atomic>
#include <vector>
#include <cmath>
#include <sstream>

std::string convertToString(char*, int);
void passwordBruteForcer(std::string, long long, long long);

std::atomic<bool> isPasswordFound = false;
std::string foundString;

int main()
{
    // Given some count of the amount of symbols that can exist in the password
    // We will calulcate how many possible passwords there are then divide work evenly between threads
    // In this case the possible symbols are all ascii codes from 32 to 126
    int numOfSymbols = 95;

    // Declarations;
    int numberOfThreads = 8;
    std::string password;
    std::vector<std::thread> vecOfThreads;

    // Loop waits for correct user input (problem required that password length be 5, change this if you want)
    while (true)
    {
        // Prompting user input
        std::cout << "Please enter a password of length 5 \n";
        std::cout << "password: ";
        std::getline(std::cin, password);
        if (password.length() == 5)
        {
            break;
        }
        else
        {
            std::cout << "Invalid password \n";
        }
    }

    long long amountOfPossiblePasswords = pow(numOfSymbols, password.length());

    // Creates threads running brute force cracker
    for (int threadNumber = 1; threadNumber <= numberOfThreads; threadNumber++)
    {
        long long startingNumber = (amountOfPossiblePasswords * (threadNumber - 1)) / numberOfThreads;
        long long endNumber = (amountOfPossiblePasswords * threadNumber) / numberOfThreads;
        long long remainder = amountOfPossiblePasswords % numberOfThreads;

        if (threadNumber == numberOfThreads)
        {
            vecOfThreads.push_back(std::thread(passwordBruteForcer, password, startingNumber, endNumber + remainder));
        }
        else
        {
            vecOfThreads.push_back(std::thread(passwordBruteForcer, password, startingNumber, endNumber));
        }
    }

    // Wait to join thread
    for (std::thread & th : vecOfThreads)
    {
        if (th.joinable())
            th.join();
    }

    // Prints the password the algorithm found
    if (isPasswordFound)
    {
        std::cout << foundString;
    }
    return 0;
}

// Will go through all "printable" ASCII characters
void passwordBruteForcer(std::string passStr, long long startingNumber, long long endNumber)
{
    int firstChar = 32;
    int lastChar = 126;
    int length = passStr.length();
    int numOfChar = 95;
    int numOfTries = pow(numOfChar, length);

    char* guess = new char[length];

    // Converts decimal to base num of chars then puts that char into array
    // For ex. 0 will be first char, and a 1 will be the next char, the number that represents the amount of possible passwords
    // will set this to be all lastChar

    long long numToBeConvert = startingNumber;

    for (int i = (length - 1); i >= 0; i--)
    {
        guess[i] = firstChar + (numToBeConvert % numOfChar);
        numToBeConvert /= numOfChar;
    }

    // This creates a string based on initialized guess then tests it
    std::string comparisonPasswordString = convertToString(guess, length);

    if (comparisonPasswordString == passStr)
    {
        isPasswordFound = true;
        foundString = comparisonPasswordString;

        delete[] guess;
        return;
    }

    // This loop goes from startingNumber to endNumber testing all passwords
    for(long long i = startingNumber; i < endNumber; i++)
    {
        if (isPasswordFound == true)
        {
            break;
        }

        long long numForGuess = i;
        for (int j = (length - 1); j >= 0; j--)
        {
            guess[j] = firstChar + (numForGuess % numOfChar);
            numForGuess /= numOfChar;
        }
        comparisonPasswordString = convertToString(guess, length);

        if (comparisonPasswordString == passStr)
        {
            isPasswordFound = true;
            foundString = comparisonPasswordString;
            break;
        }
    }

    delete[] guess;
}

std::string convertToString(char* charArr, int length)
{
    std::string convString;
    for (int i = 0; i < length; i++)
    {
        convString.push_back(charArr[i]);
    }
    return convString;
}


text:
Q: how do i clear the error icons in c# tabpage? Ive been researching and trying for the past 5 hours to clear the error icons from the required fields (city, state, country, longitude, and latitude) that appear to the right side of each textbox if the user does not enter stuff in them.
its all good and well except the fact once the create button displays the entry created message, and I click ok, the fields reset and all, but all 5 error icons appear next to them.
how can I get the tab page to kind of reload after the message ok is clicked so that these error icons would stop appearing after the message confirmation?
only when I close and reload the whole form the icons aren't there. I don't wanna keep redoing that for them to not appear initially!
here is part of the code that is associated with what I'm trying to accomplish:
private void createEntryButton_Click(object sender, EventArgs e)
{
    /*//if required boxes are left empty, reveal error
    if (String.IsNullOrEmpty(createCityTextBox.Text) && String.IsNullOrEmpty(createStateTextBox.Text) && String.IsNullOrEmpty(createCountryTextBox.Text) && String.IsNullOrEmpty(createLongitudeTextBox.Text) && String.IsNullOrEmpty(createLatitudeTextBox.Text))
    {
        cityError.SetError(createCityTextBox, "City field is empty!");
        stateError.SetError(createStateTextBox, "State field is empty!");
        countryError.SetError(createCountryTextBox, "Country field is empty!");
        longitudeError.SetError(createLongitudeTextBox, "Longitude field is empty!");
        latitudeError.SetError(createLatitudeTextBox, "Latitude field is empty!");
    }
    */

    if (!String.IsNullOrEmpty(createCityTextBox.Text) && !String.IsNullOrEmpty(createStateTextBox.Text) && !String.IsNullOrEmpty(createCountryTextBox.Text) && !String.IsNullOrEmpty(createLongitudeTextBox.Text) && !String.IsNullOrEmpty(createLatitudeTextBox.Text))
    {
        //cityError.Clear();
        //stateError.Clear();
        //countryError.Clear();
        //longitudeError.Clear();
        //latitudeError.Clear();

        MessageBox.Show("New entry created!");

        //resetting the fields
        foreach (Control item in createEntryTab.Controls)
        {
            if (item is TextBox)
            {
                item.Text = "";
            }

        }//end foreach
        }
        if (String.IsNullOrEmpty(createCityTextBox.Text))
        {
            cityError.SetError(createCityTextBox, "City field is empty!");
        }
        else
        {
            cityError.Clear();
        }
        if (String.IsNullOrEmpty(createStateTextBox.Text))
        {
            stateError.SetError(createStateTextBox, "State field is empty!");
        }
        else
        {
            stateError.Clear();
        }
        if (String.IsNullOrEmpty(createCountryTextBox.Text))
        {
            countryError.SetError(createCountryTextBox, "Country field is empty!");
        }
        else
        {
            countryError.Clear();
        }
        if (String.IsNullOrEmpty(createLongitudeTextBox.Text))
        {
            longitudeError.SetError(createLongitudeTextBox, "Longitude field is empty!");
        }
        else
        {
            longitudeError.Clear();
        }
        if (String.IsNullOrEmpty(createLatitudeTextBox.Text))
        {
            latitudeError.SetError(createLatitudeTextBox, "Latitude field is empty!");
        }
        else
        {
            latitudeError.Clear();
        }
    }


text:
Q: How to Go to a parent timeline properly in Flash actionscript 2? I am using a tutorial for a Flash aplication, with several galleries. The issue is, when I click on a thumbnail photo, I don't know how to go up to the corresponding timeline to show that photo.
My code is (scene 2 is the corresponding timeline):
on(release)
{
   gotoAndPlay("Scene 3", 1);
}

The button does not work, it does when I write _root (as the tutorial said originally) but it takes to the very root timeline and I don't need that.
on(release)
{
   _root.gotoAndStop(3);
}

How can I do?

A: The stage containing your MovieClip (thumbnail photo) is its parent. So you can write:
_parent.gotoAndStop(3);

Your MovieClip is contained by another MovieClip itself contained by the stage, you'll write:
_parent._parent.gotoAndStop(3);

It's a better practice to use the keyword _parent than to use _root here. Generally: forget _root that is a bad coding practice. If you use loadMovie, variables used with _root are undefined in the loaded Movie! Target directly with _parent. Moreover it will be more clear for you and for the people who read your code.
So if you want to go to a parent properly, use _parent.
For nested MovieClips, to know if you are accessing the correct timeline, you can use the trace function (the Main Timeline is _level0):
trace(_parent);
trace(_parent._parent);
trace(_parent._parent._parent);


text:
Q: Problem in Making the X in a div To be used to make the div disappear pls I need help
I have been trying to develop a div which contain a message and a x. When the x is clicked, the div supposed to disappear. But that isn't happening.
This is the source code:

document.querySelector(".closeMsg").addEventListener("click", function () {
  var removeReplyBx = document.getElementById("contactReplyBx");
  removeReplyBx.style.display = "none";
});
#contactReplyBx{
  display: block;
  z-index: 999999999;
  background: #009e66;
  padding: auto;
  min-height: 4vh;
  line-height: 4vh;
}

.replyMsg{
  display: inline-block;
  vertical-align: middle;
  font-size: 1.2em;
  letter-spacing: 0.2em;
  padding-left: 20vw;
  padding-right: 25vw;
  padding-top: auto;
  padding-bottom: auto;
}
.closeMsg{
  vertical-align: middle;
  display: inline-block;
  background: #009e66;
  padding-left: 0.3em;
  padding-right: 0.3em;
  font-size: 1.5em;
  font-weight: 500;
}

  Thank you! Your message has been sent.
  <button class="closeMsg">x</button>

I have searched for answer on the internet but haven't seen any that solves the problem
The div is green located at the upper part of the image


text:
Q: Why deleted copy constructor doesn't let to use other constructor with polymorphic type? I wonder why this program doesn't compile (the same behavior on msvc, gcc and clang):
#include <iostream>

using namespace std;

struct Action
{
    virtual void action()
    {
        cout << "Action::action()\n";
    }
};

struct ActionDecorator : Action
{
    ActionDecorator(const ActionDecorator&) = delete;
    ActionDecorator(Action & action) : origAction(action)
    {
    }

    void action() override
    {
        decoration();
        origAction.action();
    }

private:
    void decoration()
    {
        cout << "ActionDecorator::decoration()\n";
    }

    Action & origAction;
};

int main()
{
    Action action;
    ActionDecorator actionDecorator(action);
    ActionDecorator actionDecorator2(actionDecorator);
    actionDecorator2.action();
}

According to my expectation, deleted copy constructor should let construct ActionDecorator by other ActionDecorator instance, as it is polymorphic type of Action. Instead I have to explicit cast ActionDecorator instance to Action& as compiler complains about attempting to reference a deleted copy constructor. Is there some standard rule which explains such behavior?

A: Deleting a a function doesn't remove it from overload resolution. The function is merely defined as deleted. The purpose is to make the program ill-formed when overload resolution chooses that function.
Since the copy c'tor is a better match than the special base class c'tor you provided, overload resolution will always pick it if you don't cast.
How to best handle it is debatable. You could theoretically have the copy c'tor do a similar sort of wrapping. I'm torn about having a copy c'tor that doesn't copy, however. Your millage may very.
Another option, which I'm personally much more comfortable with, is to not provide public constructors as is. Instead, have clients create decorators via a regular named function. Something like this:
ActionDecorator decorate(Action& action) {
  return {action};
}

Now the class can truly remain non-copyable, and clients will never need to cast it themselves. If they pass an ActionDecorator to decorate, it will bind to an Action reference prior to constructing the instance. So it won't even consider the copy c'tor.
The class will have to be movable, for this to work prior to C++17, however.


text:
Q: How to automate captcha using webdriver on azure ? How can I automate a captcha on azure using webdriver ? Are there any 3rd party tools available ?

A: No, it is not possible to automate captcha using selenium web driver. There are few tools like Tesseract OCR which helps to retrieve the text from the image.But still, it will not be able to recognize the font used for captcha in azure site.


text:
Q: Html in visual studio code, Image and font color are not shown on the website    *That's the file index.html*

 <!DOCTYPE html>

          <meta charset="utf-8">
            <link href="styles\styles.css" rel="stylesheet" type="text\css">
          <title>24/7-Clanshop.de</title>

24/7-Clanshop

The official shop for your 24/7 streetstyle!

Hoodies

Jogginghosen

Socken

Accessoires

Look up to the Channel

*That's the file styles.css*

p, li, h1 {
  color:#ff0000;
  width: 500px;
  border: 1px solid black;
}

When i run this programm, neither the picture nor the font color can be displayed. Is it due to my browsersettings or am I overlooking something completely different?


text:
Q: При адаптивности объекты прилипают к краям При уменьшении разрешения объекты прилипают к краям экрана. Чтобы этого избежать:

*

*для каждой секции при уменьшении задать padding?

*как-то иначе можно?

A: Выберите главную обертку, обычно это тег main или

 ну или body и ему задайте:
@media (max-width: 540px) {
  padding: 0 15px;
}


text:
Q: weird behavior of jQuery Steps plugin I am using jQuery Steps plugin (LINK HERE). Problem is in one IF statements that returns wizzard to first step (not on step that is currently indexed). All IF statements are working correctly expect this one. That if statemnt is checking if phone number is in correct format:
Here is code:
onFinishing: function (event, currentIndex) {
                            var filter = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
                            if (!filter.test($("#email").val())) {
                            $("#emailError").text("e-mail is wrong");
                            return false;
                            }
                            if (!filter.test($("#email2").val())) {
                            $("#email2Error").text("e-mail is wrong");
                            return false;
                            }
                            var newnum = parseInt($("#numppl").val());
                            if(Math.floor(newnum) != newnum && !$.isNumeric(newnum)){
                            $("#numpplError").text("Number error");
                            return false;
                            }
                            if (!($("#numppl").val() >= 1 && $("#numppl").val()<=10)){
                            $("#numpplError").text("Number error");
                            return false;
                            }
                             if ($("#email").val()!=($("#email2").val())){
                             $("#email2Error").text("address don't match");
                             return false;
                             }
                            /*IF Statment bellow is bugged */
                            if ($("#phone").length) {
                             if(!$("#phone").match(/^[+]?([\d]{0,3})?[\(\.\-\s]?([\d]{3})[\)\.\-\s]*([\d]{3})[\.\-\s]?([\d]{4})$/)){
                              $("#phoneError").text("Wrong format");
                                return false;
                             }
                             }
                             return true;
                             },

A: Make correction in IF Statement in which you commented as bug :
       pval = $("#phone").val(); //Store the value of "Phone"
       if (pval.length) {   //Check for non empty
                         if(!pval.match(/^[+]?([\d]{0,3})?[\(\.\-\s]?([\d]{3})[\)\.\-\s]*([\d]{3})[\.\-\s]?([\d]{4})$/))  { // Check format.
                               $("#phoneError").text("Wrong format");
                               return false;
                               }
                         }

A: $("#phone").length isn't same as the length of phone number
inspite of $("#phone").length use ($("#phone").val()).length
similarly inspite of $("#phone").match(regular Expression) use
($("#phone").val()).match(regular Expression)


text:
Q: Unable to install Nginx Proxy Manager using Portainer on Synology I followed this guide to install Nginx Proxy Manager (NPM). When I try to create a stack, I get this error:

failed to deploy a stack: npm-db Pulling npm-app Pulling npm-app Error
npm-db Error Error response from daemon: Get
"https://registry-1.docker.io/v2/": net/http: request canceled while
waiting for connection (Client.Timeout exceeded while awaiting
headers)

I understand that the solution might be in this post but how can I fix it in my case?

A: version: '3'
services:
  app:
    container_name: proxy
    image: jc21/nginx-proxy-manager:latest
    restart: unless-stopped
    ports:
      - '80:80'
      - '81:81'
      - '443:443'
    volumes:
      - data:/data
      - letsencrypt:/etc/letsencrypt

volumes:
  data: {}
  letsencrypt: {}


text:
Q: Using Python Descriptors in Inherited Classes Given the simple example below, a few strange observations are made:

*

*The Parameter.__set__ function is never called

*At the line self.color = Parameter() the inspector shows color as being of type Parameter

*At the conclusion of the program, f.color is of type str, not even aware of once being a Parameter

Why is the descriptor __set__ method not called when color is being assigned to? I'd expect it to be called for both the 'red' and 'blue' assignments.
class Parameter(object):
    def __init__(self, value=None):
        self.value = value

    def __set__(self, instance, value):
        print('in __set__')
        self.value = value

    def __get__(self, instance, owner):
        return self.value

    def __delete__(self, instance):
        pass

class Fruit(object):
    def __init__(self):
        self.color = Parameter()

class Apple(Fruit):
    def __init__(self):
        super().__init__()
        self.color = 'red'

f = Apple()
f.color = 'blue'
print(f.color)

A: Turns out the answer had nothing to do with inheritance but rather with how descriptors work using the instance dictionary. I found a great article (https://realpython.com/python-descriptors/) that goes over the details of descriptors and showed how to properly design the pattern I was shooting for.
note: this only works with Python 3.6+ due to using the __set_name__() method.
class Parameter(object):

    def __set_name__(self, owner, name):
        self.name = name

    def __set__(self, instance, value) -> None:
        print('in __set__')
        instance.__dict__[self.name] = value

    def __get__(self, instance, obj_type=None) -> object:
        return instance.__dict__.get(self.name) or 0

class Fruit(object):
    color = Parameter()

class Apple(Fruit):
    def __init__(self):
        super().__init__()
        self.color = 'red'

f = Apple()
f2 = Apple()

print(f.color)
f.color = 'blue'
print(f.color)
print(f2.color)

Output
in __set__
in __set__
red
in __set__
blue
red


text:
Q: memory structure of two dimensional array i'm learning c++ and i am not good at english so you may not understand what i wrote...
#include <iostream>
using namespace std;
int main()
{
   int v[2][2] = {0,};
   cout << v << endl;
   cout << endl;
   cout << v[0] << endl;
   cout << endl;
   cout << &v[0][0] << endl;
   cout << sizeof(&v) << " " << sizeof(&v[0]) << " " << sizeof(&v[0][0]) << endl;
   return 0;
}

and the result is..
0x61ff00
0x61ff00
0x61ff00
4 4 4
the name of array(above code, v) is a pointer to the address of the memory block that contains the value of the first element of array v. and &v[0][0], v[0] is all same.(because v = &v[0])
my question is,
v is a pointer to the address of the first element of array v and its size is 4 byte.
&v is the address of the first element of array v and its size is 4 byte.
&v[0] is the address of first row of the array v and its size is 4 byte.
&v[0][0] is the address of the first row, first column element of array v and its size is 4 byte.
the address of v, v[0], v[0][0] is all same.
then, what is the memory structure of two-dimensional array? the same address has 3 different values.
thanks for reading and I'm sorry that the writing is not smooth.

A: While v and v[0] and v[0][0] all have the same address they do have different types. For example v is an array while v[0][0] is an integer. Their addresses result in pointers to different types.
This is no different than
struct A {
    int x;
};

A a;

// &a is the same as &a.x

The language guarantees that in arrays and simple structs the first element is at offset 0 so they have the same address.
In your code you do this:
   cout << sizeof(&v) << " " << sizeof(&v[0]) << " " << sizeof(&v[0][0]) << endl;

What you are printing here are the sizes of pointers to the array or elements in the array. On your system pointers have a size of 4 so that is what you get.
Now lets turn this example into modern C++ code:
#include <iostream>
#include <array>

using namespace std;

int main()
{
   array<array<int, 2>, 2> v = {{{0}}};
   cout << &v << endl;
   cout << &v[0] << endl;
   cout << &v[0][0] << endl;
   cout << "Size of addresses: " << sizeof(&v) << " " << sizeof(&v[0]) << " " << sizeof(&v[0][0]) << endl;
   cout << "Size of values   : " << sizeof(v) << " " << sizeof(v[0]) << " " << sizeof(v[0][0]) << endl;
   return 0;
}

Output:
Program returned: 0
0x7ffe86e116c0
0x7ffe86e116c0
0x7ffe86e116c0
Size of addresses: 8 8 8
Size of values   : 16 8 4

On godbolt.org the size of a pointer is 8 so that is what you get for all 3 addresses. But the size of the array, subarray and single element show what you expect it to be.


text:
Q: Asp.net MVC 2: Can Ajax.ActionLink pass a parameter without it going into the url? I have the following in partial view
<%= Ajax.ActionLink("Plunder Again", "Resources", new { controller = "Resource", parent =  Model.ToJson() }, new AjaxOptions { UpdateTargetId = Model.ResourceType })%>
going to the controller method:
    public ViewResult Resources(/*ModelResource parent*/)
    {
        Debug.Assert(Request.Params["parent"]!=null);
        var jss=new System.Web.Script.Serialization.JavaScriptSerializer();
        var parent=jss.Deserialize<ModelResource>(Request.Params["parent"]);
        return View(parent.PlunderAmount);
    }

but it throws an exception because the json doesn't properly pass via url, it can't find the 'Type' parameter.
I tried simply having the ModelResource as a parameter to the Action but it came in as null
This action will also be returning a partial view if that matters in any way.

A: ActionLink is used to create an anchor to a URL -- the URL must be valid!  In general, you don't pass a whole object to an Action because the route values have to be bound back into the model and passed to the action.  You might pass an ID of object though so the Action can get the object using that key.

A: If you want to send Model to controller instead of Ajax.ActionLink use Ajax.BeginForm


text:
Q: jquery get users location using promises and reverse geocoding

  //Get Users Current Location
  $("#collection-search-geolocation").click(function (event) {
          event.preventDefault();
    var zipcode = '';

    getCurrentLocation().then(function(results) {
     console.log('done');
     zipcode = extractZipcode(results);
     callCollectionMap(zipcode);
    });

          return false;
  });

  function extractZipcode(results) {
   var searchAddressComponents = results[0].address_components;
   var zipcode = searchAddressComponents.find(function(el) {
    return el.types[0] == "postal_code";
   }).short_name;
  }

  function getCurrentLocation() {
   navigator.geolocation.getCurrentPosition(function (position){
    var geocoder = new google.maps.Geocoder();
    var latLng   = new google.maps.LatLng(
     position.coords.latitude, position.coords.longitude);
    var deferred = $.Deferred();

     geocoder.geocode(
      {'latLng': latLng}
     , function(results, status){
      if (status == google.maps.GeocoderStatus.OK) {
       console.log(results);
       deferred.resolve(results);
      } else {
       deferred.reject(status);
       console.log("Geocode was not successful for the following reason: " + status);
      }
     });

     return deferred.promise();
   });
  }

Click Here

I am trying to get a user's location on click. On click, I want to grab the user's location then call a method after geocode is done executing successfully. Here is my code, but geocode is asynchronous hence why I need to use promises.
My issue is that results is returning null in the click function because geocode.geocoder hasn't finished, but I thought that is what .done() is supposed to wait until it finishes? I tried .then() as well and same result. I get the error cannot read property .done() of undefined.

A: You're creating the deferred inside the getCurrentPosition callback - returning it there does not mean it is being returned by getCurrentLocation - you need to create the deferred outside th getCurrentPosition call, return deferred.promise() as the last line of that function, but keep the resolve/reject where it is
so, something like
function getCurrentLocation() {
    var deferred = $.Deferred();
    navigator.geolocation.getCurrentPosition(function(position) {
        var geocoder = new google.maps.Geocoder();
        var latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);

        geocoder.geocode({
            'latLng': latLng
        }, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                console.log(results);
                deferred.resolve(results);
            } else {
                deferred.reject(status);
                console.log("Geocode was not successful for the following reason: " + status);
            }
        });
    });
    return deferred.promise();
}

Personally, I'd avoid jQuery Deferred as it is not a true Promise/A+ implementation (maybe in 3.x it is, but ..) and you have tagged the question with es6-promise
function getCurrentLocation() {
    return new Promise(function(resolve, reject) {
        navigator.geolocation.getCurrentPosition(function(position) {
            var geocoder = new google.maps.Geocoder();
            var latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);

            geocoder.geocode({
                'latLng': latLng
            }, function(results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                    console.log(results);
                    resolve(results);
                } else {
                    reject(status);
                    console.log("Geocode was not successful for the following reason: " + status);
                }
            });
        });
    });
}


text:
Q: Bootstrap 3 : Accordion Chevron Icon pointing up or down sorry for my english.
First, what is wrong in the script? The chevron doesn't change.
I'm not a web master. I'm a beginner. Thanks a lot.
This is my template :

Tableau de bord

Information

Log out

Archives

2015

2014

and this is the script :

A: I replaced the two lines addClass/removeClass by a toggleClass which do the same, and it seems to work : http://jsfiddle.net/FLZpk/1/
$('.clickable').on('click', function (e) {
  var $this = $(this);
  if (!$this.hasClass('panel-collapsed')) {
    $this.parents('.panel').find('.panel-title').slideUp();
    $this.addClass('panel-collapse');
  } else {
    $this.parents('.panel').find('.panel').slideDown();
    $this.removeClass('.panel-title');
  }
  $this.find('i').toggleClass('glyphicon-chevron-up glyphicon-chevron-down');
})

jQuery toggleClass doc : https://api.jquery.com/toggleClass/


text:
Q: Excel Pivot Tables - Calculated Field of a Calculated Field I'm using Excel 2010.
I have a data set of widgets made by person by period. I created a calculated field that shows each person's widgets made as a percentage of the total for each period.
I would like to now show the change in that "percent of total" from period to period. That is to say, I want to see how each person's percentage of the total widgets made has change from the previous period. It's a calculation on a calculation and perhaps it's just wishful thinking that Excel supports this, but it would be great if it did.
Can anyone confirm if this is possible and if so, how would I approach it? I've been looking into creating a custom Calculated Field, but I don't see how to do percent to total or difference from in those (perhaps because it would be redundant?)


text:
Q: Kibana Customized Visualization with ES and Angular Doesn't Work First, I try to make a custom visualization in Kibana with learning here.
Then, I want my custom visualization to display like the clock how many hits my elasticsearch index has dynamically .
So, I changed some codes in above tutorial but they don't work.
Chrome Devtools tells says Error: The elasticsearch npm module is not designed for use in the browser. Please use elasticsearch-browser
I know I had better use elasticsearch-browser perhaps.
However, I want to understand what is wrong or why.
public/myclock.js
define(function(require) {
    require('plugins/<my-plugin>/mycss.css');
    var module = require('ui/modules').get('<my-plugin>');
    module.controller('MyController', function($scope, $timeout) {
        var setTime = function() {
            $scope.time = Date.now();
            $timeout(setTime, 1000);
        };
        setTime();
        var es = function(){
            var elasticsearch = require('elasticsearch');
            var client = new elasticsearch.Client({
              host: 'localhost:9200',
              log: 'trace'
            });
            client.search({
              index: 'myindex',

            }).then(function (resp) {
                $scope.tot = resp.hits.total;
            }, function (err) {
                console.trace(err.message);
            });
        };
        es();

    });

    function MyProvider(Private) {
        ...
    }

    require('ui/registry/vis_types').register(MyProvider);

    return MyProvider;
});

public/clock.html
<div class="clockVis" ng-controller="MyController">
     {{ time | date:vis.params.format }}
     {{tot}}
</div>

Thank you for reading.

A: Looks like the controller in angularjs treats the elasticsearch javascript client as if it was accessing from the browser.
To elude this, one choice will be by building Server API in index.js and then make kibana access to elasticsearch by executing http request.
Example
index.js
// Server API (init func) will call search api of javascript
export default function (kibana) {
  return new kibana.Plugin({
    require: ['elasticsearch'],

    uiExports: {
      visTypes: ['plugins/sample/plugin']
    },

    init( server, options ) {
      // API for executing search query to elasticsearch
      server.route({
        path: '/api/es/search/{index}/{body}',
        method: 'GET',
        handler(req, reply) {
          // Below is the handler which talks to elasticsearch
          server.plugins.elasticsearch.callWithRequest(req, 'search', {
            index: req.params.index,
            body:  req.params.body
          }).then(function (error, response) {
            reply(response);
          });
        }
      });
    }
  });
}

controller.js
In the controller, you will need to call GET request for above example.
$http.get( url ).then(function(response) {
  $scope.data = response.data;
}, function (response){
  $scope.err  = "request failed";
});

In my case, I used url instead of absolute or relative path since path of dashboard app was deep.
http://[serverip]:5601/iza/app/kibana#/dashboard/[Dashboard Name]

                                                   *

                                             Your here

http://[serverip]:5601/iza/[api path]

                           *
                       api path will start here

I used this reference as an example.


text:
Q: Web2py ...Connecting to the correct controller I have 2 tables : business and article.
And I have 3 controllers : Home, Articles, Businesses.
In Home page controller the following code returns a list of Businesses and Articles:
     def index():
       lists= db().select(db.article.ALL,limitby=(0, 5),orderby=~db.article.id)
       listings=db().select(db.business.ALL)
       return dict(lists=lists,listings=listings)

with a loop in the home view file.
So I want to link articles to the Articles controller and Businesses to the Business controller from the home page...I have used the following code:
    def show():
      myid == request.vars.id
      redirect(URL(c='businesses',f='show?id=%s'% myid))

So even articles list will link to Business controller now using the function show in Business controller, but I want use if and elif according to the respective listing.

A: Instead of a redirect, why not just link directly to the show() function in each controller, and set up the URLs as follows:
{{for article in lists:}}
{{=article.title}}
{{pass}}

and similarly for the business links.
In article.py:
def show():
    article = db(db.article.id == request.args(0)).select().first()
    return dict(article=article)

Another option is using just a single show() function in your main controller to handle both articles and businesses. In that case, links would look like this:
Article: URL('home', 'show', args=['article', article.id])
Business: URL('home', 'show', args=['business', business.id])
and in home.py:
def show():
    item = db(db[request.args(0)].id == request.args(1)).select().first()
    return dict(item=item)

The show.html view could then include logic to display an article and a business differently (depending on the value of request.args(0)), or the show() function could explicitly set alternative article.html and business.html views as follows:
    response.view = 'home/%s.html' % request.args(0)

Side Note: The URLs will look nicer if you make the record id an arg instead of a var (i.e., /show/1 instead of /show?id=1). Also, if you do need to specify vars in the URL() function, do not explicitly append them to the function name as a query string (i.e., don't do URL(..., f='show?id=%s' % myid)) -- instead, use the vars argument (i.e., URL(..., f='show', vars=dict(id=myid))).


text:
Q: Structure formData in an array I have an extensive form and I'm trying to organize this so that it remains practicable for the plan that I intend to have with it.
An example showing what my form looks like:
<input type="text" name="data[0][name]">
<input type="email" name="data[0][email]">
<input type="tel" name="data[0][phone]">

<input type="text" name="data[1][name]">
<input type="email" name="data[1][email]">
<input type="tel" name="data[1][phone]">

I want this to return as:
 - data
    - data[0]
       - data[name]
       - data[email]
       - data[phone]
    - data[1]
       - data[name]
       - data[email]
       - data[phone]

But with new FormData(form); and then Object.fromEntries(formData) I'm just getting it on separate lines (as one large array).
Can someone help me with an easy way of converting these in a dynamic way because in my actual setup I have dozens of fields. So manually is not a desired option for me.
Thanks!

A: I do not think there is a standard way to do this. You can try to find existing solution that turns FormData into JSON (https://www.google.com/search?q=formdata+to+json+npm), you can refer to solutions from How to convert FormData (HTML5 object) to JSON, or you can find inspiration e.g. in https://github.com/therealparmesh/object-to-formdata and write reverse operation. The complexity of your solution will depend on the complexity of your data and required performance for the solution.

A: To convert a (single layer) NodeList of form elements into a nested object, using the form element name components, you can loop over the data form elements:
const dataform_obj = {} // instantiate empty object

// specify regular expression to capture name components
// for example: data[0][email]
const dataform_re = /^([^\[]+)(\[\d+\])(\[[^\]]+\])$/;

// convert form elements into array then loop
[...document.querySelector('#dataform').elements].forEach(function (elem) {

    // capture name components
    const match = elem.name.match(dataform_re);
    // match[1] is first name, match[2] is index, match[3] is last name
    // for example, ["data", "0", "email"]

  // instantiate sub-objects if do not exist
  if ( !dataform_obj[match[1]] ) {
    dataform_obj[match[1]] = {};
  }
  if ( !dataform_obj[match[1]][match[1] + match[2]] ) {
    dataform_obj[match[1]][match[1] + match[2]] = {};
  }

  // assign element value to object
  dataform_obj[match[1]][match[1] + match[2]][match[1] + match[3]] = elem.value;
})

Above, a javascript regular expression is used to capture the various components of the form element name. Those components are then used to build the object hierarchy.
console.log(dataform_obj);

...produces:
data: {
  data[0]: {
    data[email]: "",
    data[name]: "",
    data[phone]: ""
  },
  data[1]: {
    data[email]: "",
    data[name]: "",
    data[phone]: ""
  }

Online example: https://jsfiddle.net/n4m32wzh/

Perhaps, this is the format you're actually looking for:
data: {
  0: {
    email: "",
    name: "",
    phone: ""
  },
  1: {
    email: "",
    name: "",
    phone: ""
  }
}

Do that like this:
const dataform_obj = {};
const dataform_re = /^([^\[]+)\[(\d+)\]\[([^\]]+)\]$/;

[...document.querySelector('#dataform').elements].forEach(function (elem) {

  const match = elem.name.match(dataform_re)

  if ( !dataform_obj[match[1]] ) {
    dataform_obj[match[1]] = {}; // <-- this level can alternatively be an array using [] instead of {} since the component is a number
  }
  if ( !dataform_obj[match[1]][match[2]] ) {
    dataform_obj[match[1]][match[2]] = {};
  }

  dataform_obj[match[1]][match[2]][match[3]] = elem.value;
});
console.log(dataform_obj["data"])

Online example: https://jsfiddle.net/gnav6qb4/2/

If you already have a FormData Object, you can loop this way:
const dataform = new FormData(document.querySelector('#dataform'));
[...dataform.entries()].forEach(function (elem) {
  // elem is an array: [element name, element value]
  //...


text:
Q: Automatic connection of text points in tikz-qtree I have to draw pictures like the following a lot:

I want to use tikz-qtree, since I have a lot of trees and this package simplifies things considerably. Right now I use the following code, since it is not possible to have nodes in nodes and tikz-qtree makes the tree elements nodes. So I use the grid code from How can I show coordinates by grid in TikZ automatically? and draw lines from absolute positions to other absolute positions. This is time consuming, it never looks right, and I have to redo it when the font size changes. Is there a better way to do this?
\documentclass{minimal}

\usepackage{tikz-qtree}
\tikzset{every roof node/.append style={inner sep=0.1pt,text height=2ex,text depth=0.3ex}}

\newcommand{\sliste}[1]{%
\mbox{%
$\left\langle\mbox{\scshape #1}\right\rangle$}%
}

\begin{document}

\begin{tikzpicture}
\tikzset{level 1+/.style={level distance=3\baselineskip}}
\tikzset{frontier/.style={distance from root=12\baselineskip}}
%\draw (-3,-5) to[grid with coordinates] (4,0);
\Tree[.S
        [.{V \sliste{ S$\!/\!/$V }}
          [.V liest$_k$ ] ]
        [.{S$\!/\!/$V}
           [.NP Jens ]
           [.{V$'$$\!/\!/$V}
             [.NP \edge[roof]; {das Buch} ]
             [.{V$\!/\!/$V} \_$_k$ ] ] ] ]
\draw[semithick,<->,color=green] (3.1,-3.9) ..controls +(south east:.5) and +(south west:.5)..(2.7,-3.9);
\draw[semithick,<->,color=green] (3.5,-3.7) ..controls +(east:.5) and +(east:.5)..(2.8,-2.5);
\draw[semithick,<->,color=green] (2.8,-2.3) ..controls +(east:.5) and +(east:.5)..(1.7,-1.1);
\draw[semithick,<->,color=green] (1.5,-0.9) ..controls +(north:.5) and +(north:.5)..(-0.8,-0.9);
\draw[semithick,<->,color=green] (-0.7,-1.1) ..controls +(south east:.2) and +(north east:.5)..(-1.0,-2.4);
\end{tikzpicture}

\end{document}

Edit:
I followed the suggestion and used tikzmark and \subnode:
\documentclass{minimal}

\usepackage{tikz-grid}

\usepackage{tikz-qtree}
\tikzset{every roof node/.append style={inner sep=0.1pt,text height=2ex,text depth=0.3ex}}

\usetikzlibrary{tikzmark}

\newcommand{\sliste}[1]{%
\mbox{%
$\left\langle\mbox{\scshape #1}\right\rangle$}%
}

\begin{document}

\begin{tikzpicture}
\tikzset{level 1+/.style={level distance=3\baselineskip}}
\tikzset{frontier/.style={distance from root=12\baselineskip}}
\Tree[.S
        [.{V \sliste{ S$/\!/$\subnode{vcomp}{V} }}
          [.{\subnode{vliest}{V}} liest$_k$ ] ]
        [.{S$/\!/$\subnode{vs}{V}}
           [.NP Jens ]
           [.{V$'$$\!/\!/$\subnode{vbar}{V}}
             [.NP \edge[roof]; {das Buch} ]
             [.{\subnode{vzero}{V}$\!/\!/$\subnode{vdsl}{V}} \_$_k$ ] ] ] ]
\draw[semithick,<->,color=green] (vcomp.east) ..controls +(south east:.2) and +(north east:.5)..(vliest.east);
\end{tikzpicture}

\end{document}

The result is funny: It works if I use pdflatex and have no AUX file. As soon as there is an AUX file, the code produces two pages or the arrows are distributed over the page. Hm.
Edit 2:
I followed Allen Mun's suggestion and worked further on similar examples:
\documentclass{minimal}

\usepackage{tikz-grid}

\usepackage{tikz-qtree}
\tikzset{every roof node/.append style={inner sep=0.1pt,text height=2ex,text depth=0.3ex}}

\usetikzlibrary{tikzmark}

\newcommand{\sliste}[1]{%
\mbox{%
$\left\langle\mbox{\scshape #1}\right\rangle$}%
}

\newcommand{\trace}{\raisebox{0.2ex}{\_}\rule{0cm}{0.7em}}

\begin{document}

\begin{tikzpicture}[
level 1+/.style={level distance=3\baselineskip},
frontier/.style={distance from root=15\baselineskip},
connect/.style={semithick,<->,color=green}]
\Tree[.S
        [.\node (NP) {NP}; \edge[roof]; {das Buch} ]
        [.\node (S/NP) {S/NP};
          [.{V \sliste{ S/$\!$/V }}
            [.V liest$_k$ ] ]
           [.\node (S//V/NP) {S$/\!/$V/NP};
             [.\node (NP/NP) {NP/NP}; \trace{} ]
             [.{V$'$$\!/\!/$V}
               [.NP Jens ]
               [.{V$\!/\!/$V} \_$_k$ ] ] ] ] ] ]
\draw[connect] (NP/NP) [bend right] to (S//V/NP.south east);
\draw[connect] (S//V/NP.north east) [bend right] to (S/NP.east);
\draw[connect] (S/NP.north east) [bend right] to (NP);
\end{tikzpicture}

\end{document}

The intention of this figure is to show that the NP information is shared. So here it would be great to be able to connect to the NP nodes directly.

A: There's no need to be so complicated. Any tikz-qtree node label can be an explicit TikZ \node command, so you can name your nodes without too much extra work.  I've also used a simpler syntax for the arrows, so that you don't need to specify controls (and which I think makes the arrows a little nicer too.)  There's no need for subnodes even for the smaller arrows, since they can be shortened with the shorten key (as in the V//V arrow in the example.)
As Qrrbrbirlbel notes, using the forest package makes this slightly easier, since it allows you to simply specify a label for any node without using an explicit \node command, but otherwise the basic procedure is the same.
\documentclass{article}

\usepackage{tikz-qtree}
\tikzset{every roof node/.append style={inner sep=0.1pt,text height=2ex,text depth=0.3ex}}

\newcommand{\sliste}[1]{%
\mbox{%
$\left\langle\mbox{\scshape #1}\right\rangle$}%
}

\begin{document}

\begin{tikzpicture}[
level 1+/.style={level distance=3\baselineskip},
frontier/.style={distance from root=12\baselineskip},
connect/.style={semithick,<->,color=green}]
\Tree[.S
        [.\node (V1) {V \sliste{ S$\!/\!/$V }};
          [.\node(V){V}; liest$_k$ ] ]
        [.\node (S/V) {S$\!/\!/$V};
           [.NP Jens ]
           [.\node(V'V) {V$'$$\!/\!/$V};
             [.NP \edge[roof]; {das Buch} ]
             [.\node(V/V) {V$\!/\!/$V}; \_$_k$ ] ] ] ]
\draw[connect,shorten >=.5em,shorten <=.5em] (V/V.south east) [bend left] to (V/V.south west) ;
\draw[connect] (V/V.north east) [bend right] to (V'V.east);
\draw[connect] (V'V.north east) [bend right] to (S/V.east);
\draw[connect,shorten <=.5em] (S/V.north east) to [bend right] (V1) ;
\draw[connect] (V1) to [bend left] (V);
\end{tikzpicture}

\end{document}

A: Even with forest which can do a lot of things automatically, a certain amount of manual tweaking is needed. There is just no way for it to know what the content of the node means. However, forest does allow you to integrate the loops into the tree which may be attractive in some cases.
For example:
\documentclass[tikz,border=5pt]{standalone}
\usetikzlibrary{tikzmark, arrows.meta, bending}
\usepackage{forest}

\begin{document}

  \tikzset{
    connect/.style={{Stealth[bend]}-{Stealth[bend]}, draw=green, shorten <=-3pt, shorten >=-3pt}
  }
  \newlength\txtht
  \settoheight\txtht{B}
  \begin{forest}
    for tree={
      parent anchor=south,
      child anchor=north,
      if n children=0{tier=t, text height=\txtht}{},
    },
    [S
      [NP, tikz={\draw [connect] (.north east) [bend left] to ([xshift=-10pt]np1.north east);}
        [das Buch, triangle]
      ]
      [S/NP, name=np1, tikz={\draw [connect] (.east) [bend left] to ([xshift=-10pt]np2.north east);}
        [V (S//V), tikz={\draw [connect] ([xshift=-10pt].south east) [bend left] to (v1.north east);}
          [V, name=v1
            [liest$_k$]
          ]
        ]
        [S//V/NP, name=np2
          [NP/NP, tikz={\draw [connect] (.east) [bend right] to ([xshift=-10pt]np2.south east);}
            [-]
          ]
          [V$'$//V, tikz={\draw [connect] (.east) [bend left] to ([xshift=-5pt]v2.north east);}
            [NP
              [Jens]
            ]
            [V//V, name=v2, tikz={\draw [connect] ([xshift=5pt].south west) [out=-105, in=-75] to ([xshift=-5pt].south east);}
              [${}_{-k}$]
            ]
          ]
        ]
      ]
    ]
  \end{forest}

\end{document}


text:
Q: Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.UserControl', AncestorLevel='1'' I am trying to set up context menus within a treeview based on an hierarchicaldatatemplate in MVVM.
The root is a parent viewmodel that has nested viewmodels inside in a observable collection and so on. The root  is based in my main viewmodel
Example:

*

*Parent

*

*Child

*

*Grand Child 1

*Grand Child 2

*Child 2

*

*Grand Child 1

*Child 3

What I try to do is to set up a context menu on a Grand Child called "Delete". The Problem I have is how do I set up the command within the context menu when it is located in the viewmodel of the child? Because all Grand childs are stored within a observablecollection in the child viewmodel.
I tried several solution published here but nothing worked for me.
What I tried until now:

*

*using the Tag property  and Placementtarget

But I am getting the Error:
Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='SimTableApplication.View.Controls.VirtualControllerView', AncestorLevel='1''. BindingExpression:(no path); DataItem=null; target element is 'StackPanel' (Name=''); target property is 'Tag' (type 'Object')
Here is my xaml code of the treeview:
 <TreeView Name="Tree" ItemsSource="{Binding Projects}" Background="#cccccc" BorderThickness="0" >
                    <i:Interaction.Behaviors>
                        <behav:TreeViewSelectedItemBehavior SelectedItem="{Binding SelectedTreeViewItem}"/>
                    </i:Interaction.Behaviors>
                    <TreeView.Resources>
                        <Style TargetType="TreeViewItem">
                            <Setter Property="IsExpanded" Value="True"/>
                            <Setter Property="Foreground" Value="White"/>
                            <Setter Property="FontWeight" Value="Bold"/>
                            <Setter Property="Background" Value="Transparent"/>
                            <EventSetter Event="MouseRightButtonDown" Handler="TreeViewItem_MouseRightButtonDown"/>
                        </Style>
                    </TreeView.Resources>
                    <TreeView.ItemTemplate>
                        <HierarchicalDataTemplate ItemsSource="{Binding VirtualPLCs}">
                            <StackPanel Orientation="Horizontal">
                                <Image Source="/SimTableApplication;component/Assets/ICO_PE_Project.ico" Height="18" Width="18"/>
                                <TextBlock Text="{Binding ProjModel.ProjectName}" Margin="3"/>
                                <StackPanel.ContextMenu>
                                    <ContextMenu>
                                        <MenuItem Header="Add new Controller" Command="{Binding AddNewControllerCommand}">
                                            <MenuItem.Icon>
                                                <Image Source="/SimTableApplication;component/Assets/ICO_PE_CreateNewItem.ico"/>
                                            </MenuItem.Icon>
                                        </MenuItem>
                                        <Separator />
                                        <MenuItem Header="Properties" Command="{Binding ShowProjectPropertiesCommand}">
                                            <MenuItem.Icon>
                                                <Image Source="/SimTableApplication;component/Assets/ICO_PVS_Properties.png"/>
                                            </MenuItem.Icon>
                                        </MenuItem>
                                    </ContextMenu>
                                </StackPanel.ContextMenu>
                            </StackPanel>
                            <HierarchicalDataTemplate.ItemTemplate>
                                <HierarchicalDataTemplate ItemsSource="{Binding SimTables}">
                                    <StackPanel Orientation="Horizontal">
                                        <Image Source="/SimTableApplication;component/Assets/ICO_PE_Device.ico" Height="18" Width="18"/>
                                        <TextBlock Text="{Binding Name}" Margin="3"/>
                                        <StackPanel.ContextMenu>
                                            <ContextMenu>
                                                <MenuItem Header="Add new SIM table" Command="{Binding AddNewSimTableCommand}">
                                                    <MenuItem.Icon>
                                                        <Image Source="/SimTableApplication;component/Assets/ICO_PE_CreateNewItem.ico"/>
                                                    </MenuItem.Icon>
                                                </MenuItem>
                                                <Separator />
                                                <MenuItem Header="Power On" Command="{Binding PowerOnCommand}">
                                                    <MenuItem.Icon >
                                                        <Image Source="/SimTableApplication;component/Assets/ICO_PLCSIM_Tbon.ico "/>
                                                    </MenuItem.Icon>
                                                </MenuItem>
                                                <MenuItem Header="Power Off" Command="{Binding PowerOffCommand}">
                                                    <MenuItem.Icon >
                                                        <Image Source="/SimTableApplication;component/Assets/ICO_PLCSIM_Tboff.ico "/>
                                                    </MenuItem.Icon>
                                                </MenuItem>
                                                <MenuItem Header="Run" Command="{Binding RunCommand}">
                                                    <MenuItem.Icon >
                                                        <Image Source="/SimTableApplication;component/Assets/StartSimulation.png"/>
                                                    </MenuItem.Icon>
                                                </MenuItem>
                                                <MenuItem Header="Stop" Command="{Binding StopCommand}">
                                                    <MenuItem.Icon >
                                                        <Image Source="/SimTableApplication;component/Assets/StopSimulation.png"/>
                                                    </MenuItem.Icon>
                                                </MenuItem>
                                                <MenuItem Header="MRES" Command="{Binding ResetMemoryCardCommand}">
                                                    <MenuItem.Icon >
                                                        <Image Source="/SimTableApplication;component/Assets/reset-icon.png"/>
                                                    </MenuItem.Icon>
                                                </MenuItem>
                                                <Separator />
                                                <MenuItem Header="Delete">
                                                    <MenuItem.Icon>
                                                        <Image Source="/SimTableApplication;component/Assets/ICO_PE_TbDelete.ico"/>
                                                    </MenuItem.Icon>
                                                </MenuItem>
                                            </ContextMenu>
                                        </StackPanel.ContextMenu>
                                    </StackPanel>
                                    <HierarchicalDataTemplate.ItemTemplate >
                                        <DataTemplate >
                                            <StackPanel Orientation="Horizontal" **Tag="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}}}">**
                                                <Image Source="/SimTableApplication;component/Assets/ICO_PLCS_SimTable.ico" Height="18" Width="18"/>
                                                <TextBlock  Text="{Binding SimTableName}"  Margin="3"/>
                                                <StackPanel.ContextMenu>
                                                    <ContextMenu>
                                                        <MenuItem Header="Delete"  Command="{Binding Path=PlacementTarget.Tag.DataContext.DeleteSimTableCommand,
                                                    RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ContextMenu}}">
                                                            <MenuItem.Icon>
                                                                <Image Source="/SimTableApplication;component/Assets/ICO_PE_TbDelete.ico"/>
                                                            </MenuItem.Icon>
                                                        </MenuItem>
                                                    </ContextMenu>
                                                </StackPanel.ContextMenu>
                                            </StackPanel>
                                        </DataTemplate>
                                    </HierarchicalDataTemplate.ItemTemplate>
                                </HierarchicalDataTemplate>
                            </HierarchicalDataTemplate.ItemTemplate>
                        </HierarchicalDataTemplate>
                    </TreeView.ItemTemplate>

                </TreeView>

Maybe somebody can give me a hint what I am doing wrong.

A: I think your problem is because you're trying to do relativesource binding as well as placementtarget at the same time. I don't think I've ever managed to get that to work as expected.
What I usually do is bind the tag of the placementtarget to wherever I'm going to get commands from and then I can get to that. This could be a problem if you had other commands in that contextmenu, but you don't.
I don't have all your code so I threw something together with just two levels - parent and child. Child is the leaf and parent is equivalent to where your delete command will be.
This works for me:
<Window.DataContext>
    <local:MainWindowViewModel/>
</Window.DataContext>
<Grid>
    <TreeView ItemsSource="{Binding Parents}">
        <TreeView.Resources>
            <HierarchicalDataTemplate DataType="{x:Type local:Parent}" ItemsSource="{Binding Children}">
                    <TextBlock Text="{Binding Name}" />
            </HierarchicalDataTemplate>
            <DataTemplate DataType="{x:Type local:Child}">
                <StackPanel Tag="{Binding DataContext,
                        RelativeSource={RelativeSource AncestorType=TreeViewItem , AncestorLevel=2}
                        }"
                       >
                    <StackPanel.ContextMenu>
                        <ContextMenu DataContext="{Binding Path=PlacementTarget.Tag,
                                     RelativeSource={x:Static RelativeSource.Self}}">
                            <MenuItem Header="Delete"  Command="{Binding DeleteCommand}">
                            </MenuItem>
                        </ContextMenu>
                    </StackPanel.ContextMenu>
                    <TextBlock Text="{Binding ChildName}"/>
                </StackPanel>
            </DataTemplate>
        </TreeView.Resources>
    </TreeView>
</Grid>

The tag is in the visual tree so it can do the relativesource thing OK and then the command is in the Tag of the placement target.
If that's not clear, I can publish the sample.
A keybinding on delete would be simpler, I guess that's no good to you though.


text:
Q: How to check if a radiobutton is checked in a radiogroup in Android? I need to set validation that user must fill / select all details in a page. If any fields are empty wanna show Toast message to fill. Now I need set validation for RadioButton in the RadioGroup. I tried this code but didn't work properly. Suggest me correct way. Thankyou.
// get selected radio button from radioGroup
int selectedId = gender.getCheckedRadioButtonId();
// find the radiobutton by returned id
selectedRadioButton = (RadioButton)findViewById(selectedId);
// do what you want with radioButtonText (save it to database in your case)
radioButtonText = selectedRadioButton.getText().toString();

if(radioButtonText.matches(""))
{
    Toast.makeText(getApplicationContext(), "Please select Gender", Toast.LENGTH_SHORT).show();
    Log.d("QAOD", "Gender is Null");
}
else
{
    Log.d("QAOD", "Gender is Selected");
}

A: Use the isChecked() function for every radioButton you have to check.
RadioButton maleRadioButton, femaleRadioButton;

maleRadioButton = (RadioButton) findViewById(R.id.maleRadioButton);
femaleRadioButton = (RadioButton) findViewById(R.id.femaleRadioButton);

Then use the result for your if/else case consideration.
if (maleRadioButton.isChecked() || femaleRadioButton.isChecked()) {
     Log.d("QAOD", "Gender is Selected");
} else {
    Toast.makeText(getApplicationContext(), "Please select Gender", Toast.LENGTH_SHORT).show();
    Log.d("QAOD", "Gender is Null");
}

A:   rgrp.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup radioGroup, int i) {
            switch(i) {
                case R.id.type_car:
                    num=1;
                    Toast.makeText(getApplicationContext()," Car",Toast.LENGTH_LONG).show();
                    break;
                case R.id.type_bike:
                    num=2;
                    Toast.makeText(getApplicationContext()," Bike",Toast.LENGTH_LONG).show();
                    break;
            }
        }
    });

A: I used the following and it worked for me. I used a boolean validation function where if any Radio Button in a Radio Group is checked, the validation function returns true and a submission is made. if returned false, no submission is made and a toast to "Select Gender" is shown:

*

*MainActivity.java
public class MainActivity extends AppCompatActivity {
    private RadioGroup genderRadioGroup;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //Initialize Radio Group And Submit Button
    genderRadioGroup=findViewById(R.id.gender_radiogroup);
    AppCompatButton submit = findViewById(R.id.btnSubmit);

    //Submit Radio Group using Submit Button
    submit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //Check Gender radio Group For Selected Radio Button
            if(genderRadioGroup.getCheckedRadioButtonId()==-1){//No Radio Button Is Checked
                Toast.makeText(getApplicationContext(), "Please Select Gender", Toast.LENGTH_LONG).show();
            }else{//Radio Button Is Checked
                RadioButton selectedRadioButton = findViewById(genderRadioGroup.getCheckedRadioButtonId());
                gender = selectedRadioButton == null ? "" : selectedRadioButton.getText().toString().trim();
            }
            //Validate
            if (validateInputs()) {
                //code to proceed when Radio button is checked
            }
        }
    }
    //Validation - No process is initialized if no Radio button is checked
    private boolean validateInputs() {
        if (genderRadioGroup.getCheckedRadioButtonId()==-1) {
            return false;
        }
        return true;
    }
}

*In activity_main.xml:
<LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

    <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/gender"/>

    <RadioGroup
            android:id="@+id/gender_radiogroup"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

        <RadioButton
                android:id="@+id/male"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/male"/>

        <RadioButton
                android:id="@+id/female"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/female""/>

    </RadioGroup>

    <android.support.v7.widget.AppCompatButton
        android:id="@+id/btnSubmit"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/submit"/>

</LinearLayout>

If no gender radio button is selected, then the code to proceed will not run.
I hope this helps.

A: Try to use the method isChecked();
Like,

selectedRadioButton.isChecked() -> returns boolean.

Refere here for more details on Radio Button

A: I used the id's of my radiobuttons to compare with the id of the checkedRadioButton that I got using mRadioGroup.getCheckedRadioButtonId()
Here is my code:
mRadioButton1=(RadioButton)findViewById(R.id.first);
mRadioButton2=(RadioButton)findViewById(R.id.second);
mRadioButton3=(RadioButton)findViewById(R.id.third);
mRadioButton4=(RadioButton)findViewById(R.id.fourth);

mNextButton=(Button)findViewById(R.id.next_button);

mNextButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        int selectedId=mRadioGroup.getCheckedRadioButtonId();

        int n=0;
        if(selectedId==R.id.first){n=1;}

        else if(selectedId==R.id.second){n=2;}

        else if(selectedId==R.id.third){n=3;}

        else if(selectedId==R.id.fourth){n=4;}
        //. . . .
    }

A: try to use this
<RadioGroup
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
>
    <RadioButton
        android:id="@+id/standard_delivery"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/Standard_delivery"
        android:checked="true"
        android:layout_marginTop="4dp"
        android:layout_marginLeft="15dp"
        android:textSize="12dp"
        android:onClick="onRadioButtonClicked"
    />

    <RadioButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/Midnight_delivery"
        android:checked="false"
        android:layout_marginRight="15dp"
        android:layout_marginTop="4dp"
        android:textSize="12dp"
        android:onClick="onRadioButtonClicked"
        android:id="@+id/midnight_delivery"
    />
</RadioGroup>

this is java class
public void onRadioButtonClicked(View view) {
        // Is the button now checked?
        boolean checked = ((RadioButton) view).isChecked();

        // Check which radio button was clicked
        switch(view.getId()) {
            case R.id.standard_delivery:
                if (checked)
                    Toast.makeText(DishActivity.this," standard delivery",Toast.LENGTH_LONG).show();
                    break;
            case R.id.midnight_delivery:
                if (checked)
                    Toast.makeText(DishActivity.this," midnight delivery",Toast.LENGTH_LONG).show();
                    break;
        }
    }

A: All you need to do is use getCheckedRadioButtonId() and isChecked() method,
if(gender.getCheckedRadioButtonId()==-1)
{
    Toast.makeText(getApplicationContext(), "Please select Gender", Toast.LENGTH_SHORT).show();
}
else
{
    // get selected radio button from radioGroup
    int selectedId = gender.getCheckedRadioButtonId();
    // find the radiobutton by returned id
    selectedRadioButton = (RadioButton)findViewById(selectedId);
    Toast.makeText(getApplicationContext(), selectedRadioButton.getText().toString()+" is selected", Toast.LENGTH_SHORT).show();
}

https://developer.android.com/guide/topics/ui/controls/radiobutton.html

A: If you want to check on just one RadioButton you can use the isChecked function
if(radioButton.isChecked())
{
  // is checked
}
else
{
  // not checked
}

and if you have a RadioGroup you can use
if (radioGroup.getCheckedRadioButtonId() == -1)
{
  // no radio buttons are checked
}
else
{
  // one of the radio buttons is checked
}

A: My answer is according to the documentation, which works fine.
1) In xml file include android:onClick="onRadioButtonClicked" as shown below:
<RadioGroup
android:id="@+id/rg1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:gravity="center">
<RadioButton
    android:id="@+id/b1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="onCreateOptionsMenu()"
    android:onClick="onRadioButtonClicked"
            />
<RadioButton
    android:id="@+id/b2"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="onCreateMenu()"
    android:onClick="onRadioButtonClicked"
            />
</RadioGroup>

2) In Java file implement onRadioButtonClicked method outside onCreate() method as shown below:
public void onRadioButtonClicked(View view) {
    // Is the button now checked?
    boolean checked = ((RadioButton) view).isChecked();

    // Check which radio button was clicked
    switch(view.getId()) {
        case R.id.b1:
            if (checked)
            {
                Log.e("b1", "b1" );
                break;
            }
        case R.id.b2:
            if (checked)
                break;
    }
}

A: mRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup radioGroup, int i) {
            if (mRadioButtonMale.isChecked()) {
                text = "male";
            } else {
                text = "female";
            }
        }
    });

OR
 mRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup radioGroup, int i) {
            if (mRadioButtonMale.isChecked()) { text = "male"; }
            if(mRadioButtonFemale.isChecked()) { text = "female"; }
        }
    });

A: radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int checkedId) {
                checkedId = radioGroup.getCheckedRadioButtonId();

                switch (checkedId) {
                    case R.id.expert_rb:
                        // do something
                        break;
                    case R.id.no_expert_rb:
                        // do something else
                        break;

                }
            }
        });


text:
Q: Formatting table number? How do I format all table  elements having the class class="contribution" using .toLocaleString(); or a similar method that can add commas and currency formatting? The table will never have more than 200 rows, in case that is relevant for performance. Here is the current table body format:

      2009-01-31
      -100000.00
      0.00
      0.00

      2013-05-15
      0.00
      56000.00
      64000.00

The javascript that I am currently using, which doesnt seem to work, is:
$(document).ready( function() {
    $("td.contribution").toLocaleString('en-US');
})

In case it helps, the webpage does have jquery 3 loaded.

A: Try this (edited to use currency formatting):

$(document).ready( function() {
  $("td.contribution").each(function() { $(this).html(parseFloat($(this).text()).toLocaleString('en-US', {style: 'currency', currency: 'USD'})); })
})

      2009-01-31
      -100000.00
      0.00
      0.00

      2013-05-15
      0.00
      56000.00
      64000.00

This calls a function on each cell which replaces the HTML content with the locale-formatted version of the number in the cell. Your original code did not read or write the text within the cell.

A: Can you try this?
$(document).ready(function () {
            $("td.contribution").each(function () {
                $(this).text($(this).text().toLocaleString('en-US'));
            })
        });


text:
Q: I upgraded from .NET 5 to .NET 6 and now getting SqlNullValueException from a LINQ query I just upgraded a project from .NET 5 to the .NET 6 preview and started using Visual Studio 2022. But I'm getting a SqlNullValueException that I wasn't getting before. And it's not making sense to me.
Here is the LINQ query:
var clients = _dbContext.AppUserAppUsers
            .Where(x => x.AppUserParentId == designerId
                        && x.ChildAppUser.AppUserRole == AppUserRole.Client)
            .Include(x => x.ChildAppUser.Profile)
            .Select(x => x.ChildAppUser)
            .AsNoTracking();

return clients.ToList();

The AppUserAppUsers entity is a many-to-many model for AppUsers. I'm using the
Table-per-hierarchy pattern
So I have AppUserBase abstract class and DesignerModel and ClientModel both extend that class.
public class AppUserAppUser
    {
        public int AppUserParentId { get; set; }

        public int AppUserChildId { get; set; }

        public bool Active { get; set; }

        public AppUserBase ParentAppUser { get; set; }

        public AppUserBase ChildAppUser { get; set; }
    }

Again, all this works beautifully in .NET 5!
The call to ToList() throws this exception:
System.Data.SqlTypes.SqlNullValueException
  HResult=0x80131931
  Message=Data is Null. This method or property cannot be called on Null values.
  Source=Microsoft.Data.SqlClient
  StackTrace:
   at Microsoft.Data.SqlClient.SqlBuffer.ThrowIfNull()
   at Microsoft.Data.SqlClient.SqlBuffer.get_String()
   at Microsoft.Data.SqlClient.SqlDataReader.GetString(Int32 i)
   at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.Enumerator.MoveNext()
   at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
   at Design2WorkroomApi.Repository.AppUserRepository.GetClientsByDesignerId(Int32 designerId) in C:\Users\davew\source\repos\Design2WorkroomApi\Design2WorkroomApi\Repository\AppUserRepository.cs:line 65
   at Design2ClientAPI.Controllers.ClientsController.GetClientsByDesignerId(Int32 designerId) in C:\Users\davew\source\repos\Design2WorkroomApi\Design2WorkroomApi\Controllers\ClientsController.cs:line 56
   at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.SyncActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeActionMethodAsync()
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeNextActionFilterAsync()

If I take out the Include and the Select calls this works fine. But either one and the LINQ statement returns null.
In the .NET 5 version, this same method with the same parameter works just fine. And I have used similar code many times before with no problems.
Obviously, something in .NET 6 has changed to cause this, but I don't know what it is.
Here are my Entity Framework Core packages. I had the same issue before I upgraded these packages.
 <PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="6.0.0-rc.2.21480.10" />
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="6.0.0-rc.2.21480.5" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="6.0.0-rc.2.21480.5" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="6.0.0-rc.2.21480.5">

A: Remove the .Include(),  it is not needed in this particular case and it can cause the error which you are getting.
The new query should simply look something like:
var clients = _dbContext.AppUserAppUsers
            .Where(x => x.AppUserParentId == designerId
                        && x.ChildAppUser.AppUserRole == AppUserRole.Client)
            .Select(x => x.ChildAppUser)
            .AsNoTracking();


text:
Q: I have project created by laravel 8 ,and i use JWT for my API ,now i can't install pusher because of JWT version Someone can help me to fix this conflict
Your requirements could not be resolved to an installable set of packages.
Problem 1
- tymon/jwt-auth is locked to version 1.0.2 and an update of this package was not requested.
- tymon/jwt-auth 1.0.2 requires php ^5.5.9|^7.0 -> your php version (8.0.1) does not satisfy that requirement.
Installation failed, reverting ./composer.json and ./composer.lock to their original content.

A: If using Larvel Version 8 use composer require -w tymon/jwt-auth --ignore-platform-reqs.

A: Just run
composer update
Or
composer require tymon/jwt-auth

A: it's work for me
composer require {{**Your package name**}} --ignore-platform-reqs