text:
Q: Perl search for files and rename them while copying to different directory I'm trying following code to search for .txt files and rename them while copying it to different directory.
#!/bin/perl
use File::Basename;
@txtfiles = <*/*.txt>;
foreach my $file(@textfiles){
    $dir = dirname($file);
    $file = basename($file);
    $file =~ s/(\d+)/$dir/; //renaming number with $dir
`mkdir -p summary` unless -d summary;
`cp $file summary`;
}

Above code gives error saying no such file to copy however print statement at each line shows correctly (renamed file names)

A: NOOOOO!
Don't use system commands -- especially since there are Perl commands that you can use.
`mkdir -p summary` unless -d summary;
`cp $file summary`;

Use the Perl commands!
use File::Copy;       # Standard Perl Module. USE IT!
...
mkdir 'summary' unless -d 'summary';   # No need for `-p`
copy $file, 'summary';

Here's a revised script:
#! /usr/bin/env perl

use strict;
use warnings;
use feature qw(say);

# use File::Basename;  -- No need for this in this version
use File::Copy;

# What files do you want to find?
# Do you want to find the immediate files or the
# files in the subdirectories?

my @text_files = glob('*.txt');  # Immediate files only

mkdir 'summary' if not -d 'summary';   # Make this dir before the loop
for my $file ( @text_files ) {
    next unless -f $file;              # Make sure this is a file you want to copy!
    #
    # No need for 'dirname' and 'basename' with '*.txt' glob
    #
    if ( not copy $file, 'summary' ) { # Check the outcome of this command.
        warn qq(Could not copy file "$file" to "summary".);
    }
}

Let us know if you need to copy files in subdirectories rather than just in the immediate directory. Maybe you can use make_tree found in File::Path, or the Perl version of find from File::Find. These are standard Perl modules that all Perl installations have.

Addendum

I don't want current directory. The files are resides inside one directory i.e. foo/text_v0001.txt, foo/text_v0002.txt, foo_au/text_v0003.txt, foo_au/text_v0004.txt continues.... I want to replace the numbers with directory name e.g. foo/text_v0001.txt should renamed to text_foo.txt and foo/text_v0002.txt should renamed to text_foo.txt (since in same folder we can't have same name files, we can add part2 and the end of second file i.e. text_fooPart2.txt).

That last part is a doozy, and it's a new requirement too. I need to verify that a file doesn't already exist with the same name, and if it does, I need to make sure that I find the next available name.
If I find that a file already exist, I'll loop incrementing a duplicate file counter until I find a file name that doesn't already exist.
#! /usr/bin/env perl

use strict;
use warnings;
use feature qw(say);

use File::Basename;
use File::Copy;
use File::Glob;                        # Improved Glob matching.

use constant {
    DIRECTORY           => 'summary',
};

# What files do you want to find?
# Do you want to find the immediate files or the
# files in the subdirectories?

#
# Let's do a more sophisticated pattern making sure we're catching
# the files we want.
#
my @text_files = glob('*/*.txt');      # Subdirectories only
mkdir DIRECTORY if not -d DIRECTORY;   # Make this dir before the loop

for my $file ( @text_files ) {
    my $dir_name  = dirname $file;
    my $file_name = basename $file;
    say "DEBUG: On '$file'.";
    #
    # Let's make sure that the file name matches the expected
    # pattern. If the substitution doesn't succeed, we assume
    # this file shouldn't be copied, and skip it.
    #
    # I'm serching for a file that has the suffix '_vxxxx.txt' where
    # 'xxxx' is some number. I remove the number and the letter `v`,
    # and add in the directory name.
    #
    if ( not $file_name =~ s/_v(\d+)\.txt$/_$dir_name.txt/ ) {
        warn qq("$dir_name/$file_name" has not been copied.");
        next;
    }
    #
    # If the name matches, make sure it's a file
    #
    if ( not -f $file ) {
        warn qq("$file" is not a file and wasn't copied.");
        next
    }
    #
    # Now make sure file name is unique
    #
    if ( -f DIRECTORY . "/$file_name" ) {         # File name already exists
        say qq(DEBUG: Duplicate File '$file_name' detected!);
        my $dup_file_counter = 2;
        ( my $file_no_suffix = $file_name ) =~ s/\.txt$//;
        #
        # Find a non-matching name
        #
        for (;;) {
            my $new_file_name = $file_no_suffix . "_part_$dup_file_counter.txt";
            say "DEBUG: New file name '$new_file_name'";
            say qq(DEBUG: if ( not -e @{[DIRECTORY]} . "/$new_file_name" ) { );
            if ( not -e DIRECTORY . "/$new_file_name" ) {
                $file_name = $new_file_name;
                last;
            }
            else {
                $dup_file_counter += 1;
            }
        }
    }

    if ( not copy $file, DIRECTORY . "/$file_name" ) { # Check the outcome of this command.
        warn qq(Could not copy file "$file" to directory ") . DIRECTORY . qq(".);
    }
}

A: in the loop you are using @textfiles instead of @txtfiles. Use strict
#!/usr/local/bin/perl
use File::Basename;
use strict;
use warnings;

my @txtfiles = glob("*.txt");
foreach my $file(@txtfiles){
     my $dir = dirname($file);
     $file = basename($file);
     $file =~ s/(\d+)/$dir/; # renaming number with $dir
     `mkdir -p summary` unless -d "summary";
     `cp $file summary`;
}


text:
Q: Posting to java servlet with jEditable Is there anyone familiar with jEditable? As mentioned in the site http://www.appelsiini.net/projects/jeditable it is possible to post to a java servlet. I am unable to post and capture the value in the servlet. Also, the inline edit box does not register a change.
Script
 $('.edit').editable('update.do');

HTML

edit here

Java Servlet
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    try {
        String name=  request.getParameter("id");
        String value=  request.getParameter("value");
        System.out.println("Name is " + name);
        System.out.println("Value is " + value);
        //Nothing is printed out, no change is registered in the inline edit box

    } finally {
        out.close();
    }
}

A: Solved! The solution was to use doPOST in the servlet.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Facebook API: (SDK Version 3) Authenticate and Post to Page I've just downloaded the Facebook SDK Version 3 and there are some significant changes. My goal is to get everything working so a user can be authenticated, then when they add a new page (different screen) they can post to that page. Please take a look at my code and let me know how it can be fixed! Currently, the access_token and secret aren't being retrieved, among other things
authenticate.php:
http://pastebin.com/y0Rdmmbs
add_page.php: http://pastebin.com/17ExQzCB
If you have better code to use, rather than the code shown in those files, that's totally fine with me. At this point I just want it to work! Thanks in advance!

A: I won't write your code for you, but I will point you in the right direction.
Facebook developer documentation is by no means a well maintained resource, but their sections on Authentication and the PHP SDK are perfectly fine for your needs. On the authentication page, they even have an example of how to use the PHP SDK to authenticate.

*

*https://developers.facebook.com/docs/authentication/

*https://developers.facebook.com/docs/reference/php/


text:
Q: Getting 404 errors when trying to use Fontawesome fonts locally in express.js framework When I try to use fontawesome locally I am always getting 404 error when the browser tries to load the fonts. I'm pretty sure I have set the path correctly.
I have set the static paths in app.js as follows.
app.use(express.static(__dirname + '/Content'));
app.use(express.static(__dirname + '/webfonts'));

A: You are referencing webfonts at the /webfonts endpoint, but when you do not provide a path as the first parameter, it will be hosted at root. So, either reference the webfonts without the /webfonts prefix, or try giving them an endpoint as the first parameter:
app.use('/Content', express.static(__dirname + '/Content'));
app.use('/webfonts', express.static(__dirname + '/webfonts'));

See Express Docs - app.use


text:
Q: How to remove consecutive duplicate records from datatable? ID  Name
1   A
2   B
3   A
5   A
6   A
7   B
10  B

From these records I want only below records, Is it possible?
ID  Name
1   A
2   B
3   C
4   A
7   B
9   C
10  B

A: It looks like you're asking about removing contiguous (when considered ordered) values.
If we assume that the ID values should be treated as continuously increasing without gaps, it can be done pretty easily - just do a left join back to yourself and demand that the previous row has a different value, or the previous row doesn't exist (to include the first row):
select cur.ID, cur.[Name]
from @data cur
left outer join @data prev on prev.[ID] = cur.[ID] - 1
where prev.ID is null or prev.[Name] <> cur.[Name]
order by cur.ID

It is trickier if we don't assume the ID values need to be contiguous; here I'm using the ROW_NUMBER() function to simulate it:
select cur.ID, cur.[Name]
from (select ID, [Name], Row = ROW_NUMBER() over (order by ID) from @data) cur
left outer join (select ID, [Name], Row = ROW_NUMBER() over (order by ID) from @data) prev
    on prev.[Row] = cur.[Row] - 1
where prev.ID is null or prev.[Name] <> cur.[Name]
order by cur.ID

There may be much better ways.
In both of these, I'm using:
declare @data table (ID int not null, [Name] char(1) not null);
insert @data (ID, [Name]) values (1,'A'),(2,'B'),(3,'C'),(4,'A'),(5,'A'),
    (6,'A'),(7,'B'),(8,'B'),(9,'C'),(10,'B');

which seems to match your expected output (but not your stated input)


text:
Q: Is this Cambridge Dictionary example of "felicitate" valid? Cambridge dictionary defines "felicitate" as

To praise someone and say that you approve of or are pleased about a
  special or unusual achievement.

Then the  first usage example given is:

Modern developments in collecting language data, including
  taperecordings, have felicitated the growth of corpus analysis and
  increased the objectivity of this work.

Is this example valid?

A: No. Modern developments praising the growth of corpus analysis doesn't make sense. One felicitates someone, not something. This is probably a typo of facilitate:

to make something possible or easier:

In this case, collecting language data in better ways would indeed make (the growth of) corpus analysis more feasible.
The feature you are using collects examples of actual usage from elsewhere, but either human or algorithmic error creeps in from time to time. I suggest flagging it with the comment function next to the entry and moving on.

A: No: in the example, there is a typo; it should really be facilitate. So Cambridge just searches a couple of corpora and displays arbitrary instances of the word in question, without checking them at all. (The Oxford English Dictionary has real examples of its entries, which are actually checked.)


text:
Q: What commands are being sent to an exe? I have an application that calls a console based application when I open a file. I would like to somehow "spy" on this console application so that when it gets called I would like to see what command line parameters are being passed to this console app.
Is this possible?

A: For Windows, Use Process Explorer. Once PE is running, go to the View menu and select the Select Columns item. On that dialog, check the Command Line checkbox and click ok. You should see command line arguments for each process in Process Explorer now.

For most Unix or OS X systems, doing ps auxw will print all processes on the system along with the command line arguments passed to them. Look up the man page for ps on your particular  OS for more information on ps and what options you can pass to it to change its output.

A: Since you say "exe", you're likely on windows. If that is the case Process Monitor would show you exactly what you need and more: http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx


text:
Q: How do I prevent activation of in-app subscriptions when user logs in with a different account? I am developing an Android/iOS application that uses Ionic and In App Purchase 2 to allow users to purchase a monthly or yearly subscription. This subscription is then tied to their account (which they register from the application) using the purchase token, together with the expiration date.
The problem I am facing is that, when user A purchases a subscription with phone A, the Google / Apple account associated with phone A and user A is both associated with the purchase, so when user A logs out, and user B logs in on the app with the same phone, user B has not yet purchased a subscription, so when they try to purchase, In App Purchase 2 sets the status automatically to Approved / Owned, since the Google / Apple account associated with phone A has already purchased the subscription, and this fools the app into thinking that user B has also purchased the subscription, so activating the subscription for user B.
How do I prevent multiple users from logging into the app and re-using the subscription associated with the Google / Apple account? I would be very thankful for any hints or tips regarding this.
This might be a confusing question, and I apologize if that is the case.
I would be grateful for any assistance. Thank you in advance!

A: A classic problem with in-app purchases! For this, what you really need is a server to manage the subscription status for your user IDs, and don't rely on the device receipt after the initial purchase occurs. In the example you provided, when user B logs in and tries to purchase, they'll receive a message from Apple that the subscription is already owned, and you don't do anything, user B doesn't get access.
The real fun begins when user B tries to then do a restore - since you should have some restore functionality in your app. For restores, you should send the receipt to your server still, but you'll want to check if the same receipt is already associated with another user before giving access to user B. If you see that user A already has the same receipt, you can either return an error to user B, or transfer the receipt from user A to user B - giving user B access and revoking access for user A.
The details of building this out would be a much larger post, but hopefully this can point you in the right direction. There are also third-party tools like RevenueCat that are built for this type of thing (Disclaimer: I work there).
More info on building an IAP server: https://www.revenuecat.com/blog/altconf-subscriptions-are-hard

A: can you have it so they purchase tokens that can then be used to activate an account on your end?

A: With Native Play Billing Library 2.2+, you're able to tie the obfuscated app account id by calling setObfuscatedAccountId (and setObfuscatedProfileId if necessary) to the purchase when launching the purchase flow. So your backend and app will both be able to identify if which app account a purchase is binded to. But to leverage this feature, you might need to code by yourself since I didn't see In App Purchase 2 has that functionality.


text:
Q: Transform dictionary to map values to list of keys For example I have a dictionary like this:
my_dict = {
    'name_1': 'method_name_x',
    'name_2': 'method_name_x',
    'name_3': 'method_name_y',
}

(keys and values of the dictionary are simply strings)
I want to transform this dictionary so that all values will be mapped to a list of keys which have these value.
Example result:
my_transformed_dict = {
    'method_name_x': ['name_1', 'name_2'],
    'method_name_y': ['name_3'],
}

I could do this by the following code:
my_transformed_dict = dict.fromkeys(my_dict.values(), [])
for k, v in my_dict.items():
    my_transformed_dict[v].append(k)

But this will end up addind every key to the values somehow.

I also thought of using dict.setdefault(), like this:
my_transformed_dict = dict()
for k, v in my_dict:
    my_transformed_dict.setdefault(v, []).append(k)

This works as indentend, but:
What would be best practice to solve this?
Is there a simpler way to solve this (maybe using a library)? Or just doing the code as a readable one-liner?

A: You can use itertools.groupby, for example:
from itertools import groupby

my_dict = {
    'name_1': 'method_name_x',
    'name_2': 'method_name_x',
    'name_3': 'method_name_y',
}
print({k: list(v) for k, v in groupby(sorted(my_dict, key=lambda k: my_dict[k]), key=lambda k: my_dict[k])})

Output:
{'method_name_x': ['name_1', 'name_2'], 'method_name_y': ['name_3']}


text:
Q: Joomla 3.x Administrator Error : 0 Cannot write to log I wrote a joomla 3.x simple web site on my local machine and it worked fine.  I deployed this to 1&1.com and the front end works fine but the control panel throws an error each time I try to log in saying "0: cannot write to log".
I have tried relative and absolute paths to the log folder in the $log_path parameter of the configuration.php and changed the permissions to the folder and files to all sorts of combinations and still I get the same error?  I have created a new log folder and pointed the  to that and still no joy?
has anyone come across this error using 1&1.com?  I see some suggestions that 1&1.com are really bad with joomla support and I may be best trying another host?  I am in 30 day money back guarantee so that is going to be my next move.
Cheers
Alex

A: First check this link https://joomla.stackexchange.com/questions/4673/error-0-cannot-open-file-for-writing-log-while-updating and if everything is fine and still this doesnt help then proceed to next step
Step:1 get the base path by writing this code to a file and uploading it through ftp
<?php
 $basepath = getcwd();
 echo "Your base Path is: ";
 echo $basepath;
 ?>

When you run that file suppose it is named base.php then go to http://yoursite.com/base.php and get your base path.
Step:2 Create a new log and tmp folder
Now as You have got the base path, create a folder in your main joomla installation and name it newlog with permission 755.
Step:3 Change path in GLobal Configuration
In your global configuration give the base path appending the new folder path. Suppose you get basepath as /var/www/joomla then uou give the log path as
/var/www/joomla/newlog

A: I imagine you might have asked 1&1 already, it may be something they know very well.
Anyway make sure you have the correct configuration paths (absolute!) in the configuration.php and that the folder and its files are writable by the user who runs the website instance.
Also clear /cache and /administrator/cache for good measure, as they may have cached some non-authenticated results.


text:
Q: Simple calculator in c with brackets I tried to make simple calculator in c supporting +, -, * and / operators with brackets. For example ((2.1 - 5.6)*4)+(2.8+2 / 2.2) should be -10.29... I tried like this but it works only with out barckets. I have no idea  how to deal if the user's input includes brackets.
float calc(void)
{
    float x,y, parse;
    char c;

    int test = scanf("%f %c %f", &x,&c,&y);
    if (test == 0){ // if '(' starts equation
        parse = calc();
        }

    else{
        if (c == '-'){
            return x - y;
        }
        else if (c == '/'){
            return x / y;
        }
        else if (c == '+'){
            return x + y;
        }
        else if (c == '*'){
            return x * y;
        }
    }
}

A: Here you have the algorithm:
http://en.wikipedia.org/wiki/Shunting-yard_algorithm
What you are using is called infix notation by the way. What the algorithm seems to do is to transform this into postfix notation (which is much more easy to compute since you just need a stack).

A: You cannot solve an equation that complicated with brackets in this simple way. There are some algorithms that you have to follow. One of them which is used in some calculators is Reversed Polish Notation where you transform the equation into a specific form, then using a stack you start pushing and popping to do the calculation taking into consideration priorities.
Link to Reverse Polish Notation


text:
Q: Saving diacritics to mysql from pdf form I am submitting data from a PDF form to a MySQL database with php. Database, tables, MySQL is set to utf8_unicode_ci and when i submit diacritics from a browser form everything is fine.
Problem appears when i do it from PDF. I found out its pretty impossible to make PDF work with unicode. Is there a workaround for this? I'm having problems with the following chars: ă î ș ț â.


text:
Q: Add node at end or beginning of linked list in C I'm trying to create a server/client program with named pipes in Linux.
Every time a client connects and authenticates, the server stores his data (pid and password) in a linked list.
The problem is that after I store the first client's data, whenever I try to store more data (clients), the program "gives" segmentation fault.
typedef struct client client, *pno;
struct client
{
    pid_t pid;
    char password[TAM_MAX];
    pno next;
};

int verify_struct(pno cliente_t)
{
    if (cliente_t == NULL) //verifica se a lista está vazia
        return 1;
    else
        return 0;
}

    pno AddClient(pno cliente_t, pid_t pid, char password[TAM_MAX])
    {
        pno new, aux;
        new = malloc(sizeof(client)); //aloca espaço

        if(new == NULL) //verifica se alocou o espaço com sucesso
            {
                printf("Memory allocation error!\n");
                return cliente_t;
            }

        new->pid = pid;
        strncpy(new->password, password, TAM_MAX-1);

        if(verify_struct(cliente_t))
            {
                printf("Should be at start\n");
                cliente_t = new;
                printf("Added at start!\n");
            }
        else
            {
                //insert at end
                printf("Adding in the end!\n");
                aux = cliente_t;
                while(aux->next != NULL)
                    aux = aux->next;
                aux->next = new;
                printf("Added sucssefully!\n");
            }
        return cliente_t;
    }

bool isValidUser(pno cliente,  pid_t pid, char password[TAM_MAX])
{
    while(cliente != NULL)
        {
            if(cliente->pid == pid && strncmp(password, cliente->password, 100) == 0)
                {
                    return true;
                }
            cliente = cliente -> proximo;
        }
        return false;
}

    //progam itself :

int main(void)
{
    pno client=NULL;

    /* --code-- */

    while(1)
        {
                if(request.loggedIn == 0)
                    {
                        client=AddClient(client, request.pid, request.password);
                    }
                else
                    {
                        if(!isValidUser(cliente, perg.pid_cliente, perg.password))
                            abort();
                        //process commands
                    }
        }

}

Outputs:
1st Client -> Should be at start!
           -> Added at start!

2nd Client -> Adding in the end!
           -> segmentation fault (core dumped).

A: You need to add this line to AddClient
new->next = NULL;

Otherwise new->next contains uninitialized memory. Later when you check aux->next != NULL (aux is now equal to what new was before), the test does not evaluate to true, because the uninitialized memory does not happen to equal 0. Then you attempt to find another node pointed to by the value in uninitialized memory. It likely contains data which is not actually a legal memory address, hence the segmentation fault.

A: There are two very similar issues:

*

*When adding to the end of the list you need to make sure new->next contains NULL, as @morningstar as already mentioned.

*When adding to the start of the list you need to make sure new->next contains cliente_t (prior to assigning it to new). For example:
printf("Should be at start\n");
new->next = cliente_t;
cliente_t = new;
printf("Added at start!\n");

The code doesn't compile due to this cliente = cliente -> proximo; undefined member... I presume you meant to modify that to -> next. Please make sure you test your testcases in the future.


text:
Q: Django signal user_login_failed not working for Custom User model , Custom Backend I am a beginner in Django and due to my project requirements, I came to conclusion that I have to implement Custom User model, and also due to this I also implemented Custom Backend.
But, now I am unable to use user_login_failed Django Signal, as I am thinking to use it for restrict the user login attempt to 3.
Any help will be a great deal to me
Thanks
Signals.py
from django.contrib.auth.signals import (user_logged_in,
                                        user_logged_out,
                                        user_login_failed)
# from accounts.models import Usermanagement
# from django.conf import settings
from django.contrib.auth import get_user_model
from django.db.models import F
from django.dispatch import receiver

Usermanagement = get_user_model()
# Usermanagement = settings.AUTH_USER_MODEL
print("Sgnals usermanagement: ",Usermanagement)

@receiver(user_logged_in,sender=Usermanagement)
def login_success(sender,request,user, **kwargs):
    print("-------------------------")
    print("Login Success Signal...")
    print("Sender: ", sender)
    print("Request: ", request)
    print("Username: ",user.email)
    print("Password: ",user.password)
    print(f"Kwargs: {kwargs}")

@receiver(user_login_failed,sender=Usermanagement)
def login_failed(sender,credentials,request,**kwargs):
    # User = UserManagement()
    print("-------------------------")
    print("Login failed Signal...")
    print("Sender: ", sender)
    print("Credentials: ", credentials)
    print("Request: ", request)
    # print("Email: ", email)
    print(f"Kwargs: {kwargs}")

# @receiver(user_logged_out,sender=Usermanagement)
# def logout_success()

apps.py
# apps.py

from django.apps import AppConfig

class AccountsConfig(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'accounts'

    def ready(self):
        import accounts.signals

init.py
# __init__.py

default_app_config = "accounts.apps.AccountsConfig"

settings.py

AUTH_USER_MODEL = 'accounts.Usermanagement'

AUTHENTICATION_BACKENDS = [
    'accounts.backends.EmailAuthBackend',
    'django.contrib.auth.backends.ModelBackend',
]

modely.py

class Usermanagement(AbstractBaseUser):

 emailid = models.CharField(db_column='EmailID', unique=True, max_length=45,default=1)
 ------------
 ---------
 -----------

 objects = UsermanagementCustomUserManager()

 USERNAME_FIELD = "emailid"
 EMAIL_FIELD = "emailid"

managers.py

class UsermanagementCustomUserManager(BaseUserManager):
    def create_user(self,emailid,firstname, password=None):
        """
        Creates and saves a User with the given email, date of
        birth and password.
        """
        if not emailid:
            raise ValueError('Users must have an email address')

        user = self.model(
            emailid=self.normalize_email(emailid),
            password=password,

        )

        user.set_password(password)
        user.save(using=self._db)
        return user

backends.py

from django.contrib.auth.backends import BaseBackend
from django.contrib.auth.hashers import make_password,check_password
from django.contrib.auth import get_user_model

Usermanagement = get_user_model()

class EmailAuthBackend(BaseBackend):
    def authenticate(self,request,username=None,password=None):
        # print("Custom authenticate rqst: ",request)
        try:
            print("Trying the email backend!")
            user = Usermanagement.objects.get(emailid=username)
            print("Got the user")
            # print(password)
            # print(user.password)
            # print(check_password(password))
            # print(user.check_password(password))

            if user.password == password or user.check_password(password):
                return user

        except user.DoesNotExist:
            return None

    def get_user(self,user_id):
        try:
            print("Getting the user of the Email Bkacned")
            return Usermanagement.objects.get(pk=user_id)
        except Usermanagement.DoesNotExist:
            return None

views.py

from django.contrib.auth import login,logout ,authenticate
from django.contrib.auth.forms import AuthenticationForm

def loginPage(request):
    # POST
    if request.method == 'POST':
        form = AuthenticationForm(request,data=request.POST)

        if form.is_valid():
            email = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password')
            #Check
            print("EMAIL: ",email)
            print("PASSWORD: ",password)
            # Authentication USER
            user = authenticate(request,username=email,password=password)
            print("Authenticated ",user) # Check
            # check
            print(user)

            if user is not None:
                if user.is_active:
                    login(request,user,backend='accounts.backends.EmailAuthBackend')
                # messages.info(request, f"You are now logged in as {email}.")
                    return redirect("home")
                else:
                    pass

            else: # If User Not found
                # messages.error(request,"User not found")
                # return HttpResponse("User not found, not able to login")
                pass

        else: # Form InValid
            # messages.error(request,"Invalid username or password.")
            # return HttpResponse("Form Invalid")
            context = {
                "form" : form
            }
            return render(request,"loginPage.html",context=context)
    # GET
    else:
        form = AuthenticationForm()
        context = {"form":form}
        return render(request,"loginPage.html",context=context)

my code was working fine until I switched to Custom User model and Custom Authentication backend

A: As mentioned in the documentation the sender for the user_login_failed signal is:

The name of the module used for authentication.

That means sender=Usermanagement is incorrect, the reason for this is that people can have various strategies for authentication (i.e. backends) these might or might not use a user model so until the user is authenticated there's no way Django can know what model class it should use as a sender. Given that the authentication failed Django simply sends the name of the current module as the sender.
You can simply skip the sender argument in your case and it should work fine:
@receiver(user_login_failed)
def login_failed(sender,credentials,request,**kwargs):
    ...


text:
Q: Could not convert Date-Time to epoch milliseconds 2018-03-09T09:00:00.687294374+08

This is the date time data i've got from TRTH(Thomson Reuters Tick History) for HongKong.
I want to convert it to epoch time but i am unable to do so because of the extra precision it has.I know only how to convert date time in seconds precision to epoch time which could be done by following code
import time
datetime = '15.07.2011 16:02:09'
pattern = '%d.%m.%Y %H:%M:%S'
epoch = int(time.mktime(time.strptime(datetime, pattern)))
print epoch

But i don't know how to convert the data i have. Please help.
EDIT 1:I got to know that hong kong time is UTC+8 so that +08 is there for it so i can remove that and then the string left to convert to epoch is
2018-03-09T09:00:00.687294374

A: Datetime with nanoseconds is not possible, only microseconds. Perhaps you can try the following (with Python 3):
from datetime import datetime, timezone
s = '2018-03-09T09:00:00.687294374'  # your string
dt = datetime.strptime(s[:-3], '%Y-%m-%dT%H:%M:%S.%f')  # removing the nanoseconds
timestamp = dt.replace(tzinfo=timezone.utc).timestamp() # get POSIX timestamp
print(timestamp)

1520586000.687294

Documentation: datetime.time & datetime.timestamp()
Please also check out:
1) Converting datetime.date to UTC timestamp in Python
2) Parsing datetime strings containing nanoseconds
And perhaps it might be possible with Python 3.7:  PEP 564 -- Add new time functions with nanosecond resolution


text:
Q: How to dynamicly access a object and then edit its content So i have for example such an object:
let htmlDom = [
  {
    type: "div",
    att: {
      class: ["test", "test2"],
      id: "yoyo",
      "data-hello": ["jan", "john"],
    },
    content: "Hello",
    child: [
      {
        type: "div",
        content: "test",
        child: [{}],
      },
    ],
  },
];

And now i want to dynamicly acess it, for example: htmlDom[0].child[0].child[0], and now the numbers of children can vary and the numbers generally. lets say for example i have an array of [0, 0, 0], How can i then acess that path dynamicly by using the numbers in the array, and then change the content of the last child[0]? The thing is that for example the array can later on vary to [0,2,4,3,6] and such, and depending on the array lenght i need to create more .child[]

A: You can first grab the last index from your array of indexes using .pop(), and then use .reduce() on the now modified indexes array to iterate over your children arrays. By setting the accumulator as the starting htmlDom you can access the  objects  at each index and its child array for each iteration of .reduce(), where the child array from each object is returned. This child array is then used as the acc for the next call/iteration of your reduce method. Once you have found the last child array, you can use index which you previously popped off your array to set/update the value:

let htmlDom = [ { type: "div", att: { class: ["test", "test2"], id: "yoyo", "data-hello": ["jan", "john"], }, content: "Hello", child: [ { type: "div", content: "test", child: [{}], }, ], }, ];

const changeByIdxs = (arr, [...idxs], value) => {
  const lastIdx = idxs.pop();
  const finalArr = idxs.reduce((acc, i) => acc[i].child, arr);
  finalArr[lastIdx] = value;
}

changeByIdxs(htmlDom, [0, 0, 0], {x: 1});
console.log(htmlDom);

The above can be implemented with for loops if you find that easier to understand:

const htmlDom = [{ type: "div", att: { class: ["test", "test2"], id: "yoyo", "data-hello": ["jan", "john"], }, content: "Hello", child: [{ type: "div", content: "test", child: [{}], }, ], }, ];
const changeByIdxs = (arr, [...idxs], value) => {
  const lastIdx = idxs.pop();
  let finalArr = arr;
  for (let i = 0; i < idxs.length; i++) {
    const idx = idxs[i];
    finalArr = finalArr[idx].child;
  }
  finalArr[lastIdx] = value
}

changeByIdxs(htmlDom, [0, 0, 0], {x: 1});
console.log(htmlDom);


text:
Q: Reference type initialized inside local block is uninitialized outside local block In the following code, I have declared a reference type variable outside of try-catch block. Then I initialize it inside the try block and try to use it again inside final block. But the compiler is warning me about the variable being uninitialized inside the final block.
From my understand, since I've initialized the file variable in the try block, it shouldn't be null in the final block.
import java.io.*;

class test {
    public static void main (String ... args) throws IOException{
        FileInputStream file;
        // Solution : FileInputStream file = null;

        try {
            file = new FileInputStream("data");
        }
        catch(IOException exc) {
            System.out.println("Error Occured!");
        }
        finally {
            file.close(); // Error : variable file might not have been initialized
        }
    }
}

I solved this problem by initializing file variable as null.
My question is, why after initializing a reference variable inside a try block, the variable will remain uninitialized in the final block?

I run into the same problem when initializing file variable inside a if statement,
import java.io.*;

class test{
    public static void main (String ... args) throws IOException{
    FileInputStream file;
    // Solution : FileInputStream file = null;

    int i = 0;
    if(i > 5){
        file = new FileInputStream("data");
    }

    file.close(); // Error : variable file might not have been initialized
  }
}

A: The problem is that if new FileInputStream("data") throws, then the file variable will not be set from within the final block.  You can fix this by doing a catch with resources.
try (FileInputStream file = new FileInputStream("data")){
}
catch(IOException exc){
    System.out.println("Error Occured!");
}

If you do try with resources then you will not need the final block to close the stream.... java will close it for you.
You can also just check to see if it is null before closing it in the final block.

A: The error is might be uninitialized and it might be, if the constructor throws an Exception (which it might). Alternatively, you could use the try-with-resources close which will close() for you
try (InputStream file = new FileInputStream("data")) {
    // ...
}
catch(IOException exc){
    // What error.
    System.out.println("Error Occurred! " + exc.toString());
    exc.printStackTrace();
}

Or,
finally {
  if (file != null) {
    try {
      file.close();
    } catch (Exception ignored) {
    }
  }
}


text:
Q: Google maps event after custom tiles loaded I have a problem. I am loading custom map tiles using overlayMapTypes.insertAt() AKA MVCArray.insertAt() and i need to know then my tiles are loaded.
google.maps.event.addListener(map, 'tilesloaded', function() {
        if (map.overlayMapTypes.getLength() == 0) {
            map.overlayMapTypes.insertAt(0, new ItemsMapType(new google.maps.Size(256, 256)));
        }
});

Is there event that fires after that or something?
p.s idle event fires too soon.
Thank you for your help in advance.

A: have you checked https://developers.google.com/maps/documentation/javascript/


text:
Q: Replace values in fifth column I have multiple text
Name 1:10:34 date short_id 10
Name 1:10:45 date short_id 10
Name 1:20:54 date short_id 20
Name 1:30:43 date short_id 30
Name 1:40:43 date short_id 40
Name 1:40:13 date short_id 40
Name 1:20:01 date short_id 20
Name 1:10:01 date short_id 10

I want to replace the fifth column , but when I use  sed 's/\b10\b/user1/g' the second column also changes
The output should look like this :
Name 1:10:34 date short_id user1
Name 1:10:45 date short_id user1
Name 1:20:54 date short_id user2
Name 1:30:43 date short_id user3
Name 1:40:43 date short_id user4
Name 1:40:13 date short_id user4
Name 1:20:01 date short_id user2
Name 1:10:01 date short_id user1

--- update ---
if there is no user1, there will be a name
and the second column is just time, it has nothing to do with the name
something like this
Name 1:10:34 date short_id John
Name 1:10:45 date short_id John
Name 1:20:54 date short_id Robert
Name 1:30:43 date short_id Jennifer
Name 1:40:43 date short_id Mary
Name 1:40:13 date short_id Mary
Name 1:20:01 date short_id Robert
Name 1:10:01 date short_id John

A: Two more awk solutions.
$ awk '{$5="user"substr($5,1,1)}1' file
Name 1:10:34 date short_id user1
Name 1:10:45 date short_id user1
Name 1:20:54 date short_id user2
Name 1:30:43 date short_id user3
Name 1:40:43 date short_id user4
Name 1:40:13 date short_id user4
Name 1:20:01 date short_id user2
Name 1:10:01 date short_id user1
$

$ awk '{$5="user"$5/10}1' x1
Name 1:10:34 date short_id user1
Name 1:10:45 date short_id user1
Name 1:20:54 date short_id user2
Name 1:30:43 date short_id user3
Name 1:40:43 date short_id user4
Name 1:40:13 date short_id user4
Name 1:20:01 date short_id user2
Name 1:10:01 date short_id user1
$

A: Okay, unfortunally, sed doesn't know that 10 is John. So if you don't want to write another substitution for each user, you might want to use a second file users.txt with a translation table like this:
10 John
20 Robert
30 Jennifer
40 Mary

Then you feed both files into this sed command:
sed '/^[0-9]* [[:alnum:]]*$/{H;d;};G;s/ \([0-9]*\)\n.*\n\1 \([[:alnum:]]*\)/ \2/;P;d' users.txt yourfile.log

The translation table is read first and stored into the hold space. For the other files, the hold space with the translations is appended and the replacement is performed if possible. Then P prints the line only to the first line break, so no mess is printed if a user ID is unknown.
If you are interested in a more detailed explanation, see How to perform replacements defined in one file on another file or feel free to ask.

A: awk 'gsub(/0/, "", $5) { print $1, $2, $3, $4, "user" $5 }' INPUT

gsub removes number "0" in the 5th column. Then awk prints column 1-4, and combines word "user" with 5th column (there is no "," between "user" and $5).

A: If all you want to change is the last column you don't need the g modifier for global and you will want to add the $ anchor to limit it to the last column.
I.e.: sed 's/\b10$/user1/'
That is assuming you'll want to change only the 10.
If the 10, 20 etc. match directly to user 1,2 etc. something like the following may work:
sed 's/\b\([1-4]\)0$/user\1/'

A: Using sed
sed 's/\(.*\) \(.\).*/\1 user\2/' input_file
Name 1:10:34 date short_id user1
Name 1:10:45 date short_id user1
Name 1:20:54 date short_id user2
Name 1:30:43 date short_id user3
Name 1:40:43 date short_id user4
Name 1:40:13 date short_id user4
Name 1:20:01 date short_id user2
Name 1:10:01 date short_id user1

A: Just use awk:
$ awk '!($NF in users){ users[$NF]="user"(++cnt) } { $NF=users[$NF] } 1' file
Name 1:10:34 date short_id user1
Name 1:10:45 date short_id user1
Name 1:20:54 date short_id user2
Name 1:30:43 date short_id user3
Name 1:40:43 date short_id user4
Name 1:40:13 date short_id user4
Name 1:20:01 date short_id user2
Name 1:10:01 date short_id user1

The above assumes you want each user to get a unique ID based on the order they appear in the input. If that's not what you need then edit your question to clarify your requirements.

A: Using Raku (formerly known as Perl_6)
raku -ne 'given .words -> $w {put "$w.[0..3] ", (S/ (\d+) /user{$0.substr(0,1)}/ with $w.[4]) };'

OR
raku -ne 'put .[0..3], " ", (S/ (\d+) /user{$0.substr(0,1)}/ with .[4]) given .words;'

The Raku code here breaks lines into whitespace-separated words. The first 4 columns (index .[0..3]) are output. Then digits in the 5th column are matched, and substitute with the word user followed by the first digit.
[A nicety of the with .[4] clause in the column 5 substitution is that it tolerates missing values in that column].
Sample Input:
Name 1:10:34 date short_id 10
Name 1:10:45 date short_id 10
Name 1:20:54 date short_id 20
Name 1:30:43 date short_id 30
Name 1:40:43 date short_id 40
Name 1:40:13 date short_id 40
Name 1:20:01 date short_id 20
Name 1:10:01 date short_id 10

Sample Output:
Name 1:10:34 date short_id user1
Name 1:10:45 date short_id user1
Name 1:20:54 date short_id user2
Name 1:30:43 date short_id user3
Name 1:40:43 date short_id user4
Name 1:40:13 date short_id user4
Name 1:20:01 date short_id user2
Name 1:10:01 date short_id user1

https://raku.org


text:
Q: A combinatorial problem concerned with logic circuits Consider a logic circuit with two-bit gates only. The length of each gate is the number of bit lines that the gate crosses. How hard is to compute the maximum length for a given circuit? Notice that two circuits are, say, isomorphic, if they differ only up to a permutation of the bit lines. Notice that there are clearly $n!$ ways to arrange $n$ bit lines.

A: If I understand your question correctly, you're trying to find a permutation of the bit lines so the maximum gate "length" is as small as possible. This is called the bandwidth problem:
Given a graph $G = (V,E)$ find a permutation $\pi : V \rightarrow [1 \ldots n]$ such that $$\max_{(i,j) \in E} |\pi(i) - \pi(j)|$$ is minimized.
The wikipedia article has more information on the complexity (it's NP-hard and APX-hard) and algorithms. The bandwidth problem is interesting also because it was used to introduce the idea of volume-respecting embeddings.


text:
Q: How do I filter objects and create a list of a specific field from the remaining objects in MongoDB? I have a documents that looks like this:
_id: ObjectId('...')
name: Team A
players: [
    {
        name: Michael
        position: Goalkeeper
    },
    {
        name: Frank
        position: Defender
    },
    {
        name: Mike
        position: Goalkeeper
    }
]

I want to make an aggregation that simply returns a list of Goalkeeper names, like this..
Players: [
    Michael,
    Mike
]

This is what I have so far:
{
    $match: { name: "Team A" }
},
{
   $project: {
       players: {
           $filter: {
               input: "$players",
               cond: {$eq: ["$$this.position", "Goalkeeper"]}
           }
        },
        _id: 0
    }
}

This filters the players Array so it only contains goalkeepers. Now I need to somehow take the names of each object out and store it in another Array. How do I achieve that?

A: Use $reduce to iterate through the array and use $cond to conditionally $setUnion the entry into the accumulator.
db.collection.aggregate([
  {
    $project: {
      players: {
        "$reduce": {
          "input": "$players",
          "initialValue": [],
          "in": {
            "$cond": {
              "if": {
                $eq: [
                  "$$this.position",
                  "Goalkeeper"
                ]
              },
              "then": {
                "$setUnion": [
                  "$$value",
                  [
                    "$$this.name"
                  ]
                ]
              },
              "else": "$$value"
            }
          }
        }
      }
    }
  }
])

Mongo Playground

A: You can use also $reduce/$filter  as follow:
db.collection.aggregate([
{
 $match: {
    name: "Team A"
 }
 },
 {
  "$project": {
    players: {
    "$reduce": {
      input: {
        "$filter": {
          input: "$players",
          cond: {
            $eq: [
              "$$this.position",
              "Goalkeeper"
            ]
          }
        }
      },
      "initialValue": [],
      "in": {
        $concatArrays: [
          "$$value",
          [
            "$$this.name"
          ]
        ]
      }
    }
  }
 }
}
])

playground
Explained:

*

*$filter only the Goalkeeper array objects to provide to $reduce.

*$reduce with $concatArrays only the names.

*Project only the $reduce-d player names array.


text:
Q: Android Accessibility : characters announced twice Precondition : Accessibility Talkback on.
Problem : While typing in characters from soft keyboard into the edit text, the characters are announced twice.
(I think once by the keyboard and once by the edit text).

A: Problem: Sighted users don't understand/empathize well with the types of information that blind users need. They just use a keyboard with TalkBack on, without actually closing their eyes and experiencing it the way a blind or partially sighted user would.
Solution: Close your eyes and actually use the keyboard the same way a TalkBack user would. You will discover that there are actually two relevant pieces of information here. The key that you're going to select and the key that you've actually selected.
Real Solution: Let Android do its thing unless you REALLY know what you're doing. More often than not, well intentioned, developers just muck things up when they start trying too hard. Provide content descriptions for your non-text controls, hook up some nice data associations when necessary and otherwise leave things alone.


text:
Q: How to pass language from web page to Keycloak using Spring security adapter I work on a web app secured by Keycloak, and I have a small problem regarding language of the keycloak login page.
My web app starts with a home page on which there is two buttons.
The first button allow to enter some parts of the app that are not secured.
The second button allow to enter the whole app, secured by Keycloak (using Spring security adapter).
On the home page, I have the possibility to change the language of the web app.
If I change the language on the home page, the not secured part of the web app will be in the chosen language.
But if I change the language on the home page, when I click on the button to access to the secured part of the app, I am redirected to the Keycloak login page, but the language on the Keycloak login page doesn't change, it stays as the default one and I have to change it manually.
I have seen that kc_locale can be used in the url of Keycloak to set the language that Keycloak must use.
The problem is that I am not calling Keycloak, Spring security adapter is, and I have no idea how to pass the information to the adapter.
I tried a few things, but nothing worked.
Is there a way to do that and if yes, how ?
Thank you !

A: I had the same problem and the best I could do is  to provide a login link with  the locale as a parameter like this
/sso/login?ui_locales=en-US
/sso/login is configured by the Keycloak Spring Adapter - not by me - so it should work for you too.
The class OAuthRequestAuthenticator which does the whole redirect stuff picks the parameter up and passes it on to keycloak.
Look for OAuth2Constants.UI_LOCALES_PARAM in code
However this doesn't work if you go first to a protected url and the adapter redirects internally to /sso/login (without the locale param).
Cheers,
Ana


text:
Q: How to obtain a current user locale from Spring without passing it as a parameter to functions? I am using Spring 3.1 and want to find the locale active for the current user is there a way to grab the locale directly without being forced to pass it from the controller to the service layer ... etc.
does spring store the locale in a thread local storage where it can be grabbed by calling some static method?

A: It depends on where you have configured to store the locale, in session or in cookie?
In my application I have configured to store the user locale in its session with below mentioned configuration.
    <mvc:interceptors>
        <ref bean="localeChangeInterceptor"/>
    </mvc:interceptors>

    <bean id="localeChangeInterceptor" class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
        <property name="paramName" value="lang"/>
    </bean>

    <bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
        <property name="defaultLocale" value="en"/>
    </bean>

    <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <property name="basenames">
        <list>
            <value>/WEB-INF/i18n/labels</value>
            <value>/WEB-INF/i18n/messages</value>
            <value>/WEB-INF/i18n/include</value>
        </list>
        </property>
        <property name="defaultEncoding" value="UTF-8"/>
    </bean>

If you have done somthing like this then you can easily retrieve the locale parameter from the session.
Hope this helps you.
Cheers.

A: We had the same need, so came up with putting Locale into ThreadLocal context. We already had an object (some user information) stored in ThreadLocal context, so just appended it (looks like a hack, but the quickest solution we found).

A: I was also looking for how to access the locale without passing the Locale around, but I'm still pretty new to Spring and found most solutions to be confusing. It turns out, though, that Spring MVC does store the locale in thread local storage. It can be accessed by:
Locale locale = LocaleContextHolder.getLocale();

The last approach [...] is based on a thread local in order to provide the current locale in any entity of your architecture. [...] You must be aware that the content of the LocaleContextHolder corresponds by default to the locale specified within the Web request.

From: Configuring locale switching with Spring MVC 3. (That post also offers alternative configurations/methods for getting the locale, which might be useful for anyone looking to do this).
You can also view the LocaleContextHolder docs from Spring here.


text:
Q: VSCODE shows warnings as errors My VSCODE shows warnings as if they were errors (specifically linter warnings).

I want linter warnings to show with different unerline color. I tried modifying my settings.json adding the following configuration
    "workbench.colorCustomizations": {
        "editorError.foreground": "#ff0000",
        "editorWarning.foreground": "#ffc400",
        "editorInfo.foreground": "#35ffab"
    },

But it seems like VSCODE thinks that those are not warnings but errors

A: By default @typescript-eslint/no-unused-vars's level is error.
To downgrade this to a warning, you can change your .eslintrc.js :
module.exports = {
  ...
  rules: {
    ...
    "@typescript-eslint/no-unused-vars": ["warn"]
  }
}

NB: You may have to restart your vscode to see the changes

A: Figured it out.
Turns out for some reason the default Typescript linter (that shows warnings properly) was disabled.
Eslint was the culprit showing warnings as error (which makes sense, considering it's a linter that by definition should fail if there are lint issues)
After disabling ESLint and enabling the built in default validator (image attached)

Warnings show up correctly now (without red underlines/errors in the problems window)


text:
Q: Select Table Column Heading as Value I have a table as follows:

ItemNumber -- Description -- 31.03.2015 -- 31.04.2015 -- 31.05.2015 --
  31.06.2015
========= -- ======== -- ======== -- ======== -- ======== -- =========
001
  ..................xyz..................null................1000...............null................null
002
  ..................xya..................2000................null...............3000................null
003
  ..................xyb..................null................4000...............null................5000
004
  ..................xyc..................6000................7000...............null................null
005
  ..................xyd..................null................8000...............9000................null
006
  ..................xye..................null................10000...............null................null
===================================================================

How can I write a query to return the values such that I can get the column heading of the fields that have a value (are not null) and also get that column heading such as:

ItemNumber -- Description -- Quantity -- Date
========= -- ======== -- ====== -- ====
001.............. -- xyz........... -- 1000...... -- 04/31/2015 12:00:00 AM
002.............. -- xya........... -- 2000...... -- 03/31/2015 12:00:00 AM
002.............. -- xya........... -- 3000...... -- 05/31/2015 12:00:00 AM
003.............. -- xyb........... -- 4000...... -- 04/31/2015 12:00:00 AM

An so on...
Sorry for the terrible formatting, I cannot figure out how to create the proper spacing without the dots.

A: You can do this with a massive union all:
select t.*
from (select ItemNumber, Description, '31.03.2015' as date, `31.03.2015` as quantity
      from table
union all
      select ItemNumber, Description, '31.04.2015' as date, `31.04.2015` as quantity
      from table
      . . .
     ) t
where quantity is not null;

In Oracle, you would use double quotes rather than backticks to escape the column name.
And, if you have a lot of data, there are other ways to express the query, so you only scan the table once.


text:
Q: How to create a data validation list based on certain criteria and data from another workbook? I have two Excel spreadsheet files (2 workbooks), one stores all the data, another wants to create a list based on certain criteria from the data in the previous workbook. Here are the two files:
File A:
    A       B
1   Chen    China
2   Li      China
3   Smith   Britain
4   Tanaka  Japan
5   Hironi  Japan

On File B, I have two cells:
    A       B
    China   ?

Cell A1 is a list of countries such as China, Japan, etc. I have no problem creating this. But B1 needs to have a data validation list that reads data from File A. The list should not list all the items but based on the value of A1, say if A1 is China, B1 will have a list of two names: Chen and Li.
I can achieve it if all the sheets in the same workbook, but no matter how I tried, I couldn't figure it out how to do that with separate spreadsheet files. I prefer using formula, but if necessary writing VBA code is also not a problem.
Thanks!

A: Not sure where you are with your formula but with a couple of tweaks this array should work, or at least provide a basis for you to solve your problem. The tweaks are (1) switch columns so the country is colA; (2) replace data file.xls and the sheet no. with your own; (3) drop the formula in B1 and drag it to (say) F1. Then you will need to edit the row reference in the formula by adding 1 each time i.e. the row ref in B1 will be ROW(1:1).... C1 will be ROW(2:2) etc

=IF(ISERROR( INDEX('[data file.xls]Sheet7'!$A$1:$B$5,SMALL(IF('[data
  file.xls]Sheet7'!$A$1:$A$5=$A$1,ROW('[data
  file.xls]Sheet7'!$A$1:$A$5)),ROW(1:1)),2)),"---", INDEX('[data
  file.xls]Sheet7'!$A$1:$B$5,SMALL(IF('[data
  file.xls]Sheet7'!$A$1:$A$5=$A$1,ROW('[data
  file.xls]Sheet7'!$A$1:$A$5)),ROW(1:1)),2))

Remember this is an array formula so shift+ control+ enter. Hope it helps.


text:
Q: Tooltip for pagination buttons in DataTables I have a datatable where I have to show the tooltip on every row and in the pagination buttons as well. I have implemented the tooltip option for the rows wherever required, but not able to figure out that how do we set the tooltip for the controls like pagination buttons (Prev and Next buttons), search (textbox) and sort (dropdown) in datatables.
HTML:

            Name
            Position
            Office
            Age
            Start date
            Salary

            Tiger Nixon
            System Architect
            Edinburgh
            61
            2011/04/25
            $320,800

            Garrett Winters
            Accountant
            Tokyo
            63
            2011/07/25
            $170,750

            Ashton Cox
            Junior Technical Author
            San Francisco
            66
            2009/01/12
            $86,000

            Cedric Kelly
            Senior Javascript Developer
            Edinburgh
            22
            2012/03/29
            $433,060

            Airi Satou
            Accountant
            Tokyo
            33
            2008/11/28
            $162,700

            Brielle Williamson
            Integration Specialist
            New York
            61
            2012/12/02
            $372,000

            Herrod Chandler
            Sales Assistant
            San Francisco
            59
            2012/08/06
            $137,500

            Rhona Davidson
            Integration Specialist
            Tokyo
            55
            2010/10/14
            $327,900

            Colleen Hurst
            Javascript Developer
            San Francisco
            39
            2009/09/15
            $205,500

            Sonya Frost
            Software Engineer
            Edinburgh
            23
            2008/12/13
            $103,600

            Jena Gaines
            Office Manager
            London
            30
            2008/12/19
            $90,560

            Quinn Flynn
            Support Lead
            Edinburgh
            22
            2013/03/03
            $342,000

            Charde Marshall
            Regional Director
            San Francisco
            36
            2008/10/16
            $470,600

JS:
$(document).ready(function() {
var table = $('#example').DataTable();
$('#example tbody').on( 'click', 'tr', function () {
    if ( $(this).hasClass('selected') ) {
        $(this).removeClass('selected');
    }
    else {
        table.$('tr.selected').removeClass('selected');
        $(this).addClass('selected');
    }
});
$('#example').dataTable({
bJQueryUI: true,
retrieve: true,
    "sPaginationType": "full_numbers"}).makeEditable({"aoColumns": [
{
    cssclass: "required"
},
{
    cssclass: "required"
},
{
    indicator: 'Saving...',
    tooltip: 'Click to edit',  //tooltip for row
    type: 'text',
    submit:'Save'
},
{
    indicator: 'Saving...',
    tooltip: 'Click to enter age',  //tooltip for row
    loadtext: 'loading...',
    type: 'select',
    onblur: 'submit',
    data: "{'':'Select', 'A':60,'B':12,'C':23,'D':25,'E':65}"
},
{
    indicator: 'Saving...',
    tooltip: 'Click to select',  //tooltip for row
    loadtext: 'loading...',
    type: 'select',
    onblur: 'submit',
    data: "{'':'Select...', 'A':'A','B':'B','C':'C'}"
},
{   cssclass: "required" }
]
});
});

Here is the JSFiddle for the same. Any help would be appreciated.

A: By tooltip I guess you mean titles? For some peculiar reason, this is not part of the native API. In my opinion, it would be obvious to include title / tooltips-options in the language construct ...
$('.paginate_button').each(function() {
    var text = $(this).text(),
        title = isNaN(text) ? text+' page' : 'Page '+text;
    $(this).attr('title', title);
});

Will set title on the pagination buttons, as "Previous page", "Page 3" etc.
$('.dataTables_filter input').attr('title', 'Type here to search in the table');

$('.dataTables_length select').attr('title', 'Select number of visible rows');

–  for filter / search box and the length menu.

Place the above inside a draw.dt event so title for the control elements is updated each time the table is redrawn :
table.on('draw.dt', function() {
    $('.paginate_button').each(function() {
          var text = $(this).text(),
            title = isNaN(text) ? text+' page' : 'Page '+text;
        $(this).attr('title', title);
    });
    $('.dataTables_filter input').attr('title', 'Type here to search in the table');
    $('.dataTables_length select').attr('title', 'Select number of visible rows');
})

A: Please, consider use titleAttr:, example:
                    "buttons": [
                        {
                            extend: 'pageLength',
                            className: 'pageLength',
                            titleAttr: 'Search',
                            text: ''
                        },
                        {
                            extend: 'copy',
                            titleAttr: 'Copy to clipboard',
                            className: 'copyButton',
                            text: ''
                        },
                        {
                            extend: 'excel',
                            titleAttr: 'Copy to excel file',
                            text: ''
                        },
                        {
                            extend: 'pdf',
                            titleAttr: 'Copy pdf file',
                            text: ''
                        },
                        {
                            extend: 'csv',
                            titleAttr: 'Copy to csv file',
                            text: ''
                        },
                        {
                            extend: 'print',
                            titleAttr: 'Print the results',
                            title: '',
                            exportOptions: {
                                columns: ':visible',
                                stripHtml: false,
                            },
                            text: '',
                            customize: function (win) {
                                $(win.document.body)
                                    .css('font-size', '10pt')
                                    .prepend(
                                        ''
                                    );

                                $(win.document.body).find('table')
                                    .addClass('compact')
                                    .css('font-size', 'inherit');
                            }
                        },
                    ]


text:
Q: how to generate a graph using 'random' and 'networkX' libraries? I have an assignment where I have to create a graph using the random library with for loops and also compute the probability whether there is an edge between two vertices. The body of the code is as given below.
How can I construct an graph?
# generate edges in G_rand at random:
for i in range(0,k) :
    for j in range(0,i) :
        # Add an edge between vertices i and j, with probability edge_probab
        # ...

A: Here is a possible solution:
import random
import networkx as nx

edge_probability = 0.3
n_nodes = 10

G = nx.DiGraph()

G.add_nodes_from(range(n_nodes))

for u in G.nodes:
    for v in G.nodes:
        if random.random() < edge_probability:
            G.add_edge(u, v)


text:
Q: Gerrit push to review answer Change..closed I am trying to publish a commit i've made and had to rebase before pushing, now my branch is up-to-date but when I do git review  it ask a question:
[user]$ git review *originbranch*

**You are about to submit multiple commits. This is expected if you are
submitting a commit that is dependent on one or more in-review
commits. Otherwise you should consider squashing your changes into one
commit before submitting.**

The outstanding commits are:

c7d455d A
372b1b9 B
27dea57 C
1e600e2 D
713422e E
c84bea9 H
7e2b81a I

When i say yes the outcome is:
remote: Resolving deltas: 100% (223/223)
remote: Processing changes: refs: 1, done
To ssh://gerrit.hq.md.checkpoint.com:29418/ipssvc
 ! [remote rejected] HEAD -> refs/publish/*originbranch*/CHANGE **(change 1298 closed)**
error: failed to push some refs to 'ssh://URL'

change 1298 is referring to change D, and it actually is closed but was part of the rebasing,
help?

A: You didn't rebase correctly.  Because of that, git review is trying to upload several more commits than just yours.
How many commits are you trying to upload for review?  Assuming just one (A c7d455d), and you are working on the master branch:
git fetch
git checkout origin/master
git cherry-pick c7d455d

You then should be able to upload like normal.
If you have multiple commits to upload, you can cherry-pick them in order or use git rebase


text:
Q: Single page feedback page to store data I have a single page for getting feedback for a set of questions and answers to choose from. 50 users are going to provide feedback for the questions. After the users have given the rating for the feedback questions, I need to do some calculation and need to generate a report in excel format.
Is it possible to do the same without using JSP Servlet or other server side technology?

A: I just wrote an answer and then deleted it.  I misunderstood your question.
It sounds like what you want to do is collect the data on the web server that the users submit and then format it into an Excel file.
There is a trick that I've used repeatedly for this.
Arrange the data into an HTML table, and save a web page with the table into a file with the .xls extension.  Click on the file and Windows will open the file in Excel.  Excel will interpret the table as a spreadsheet which you can then save as an Excel Spreadsheet.

A: There are PaaS/BaaS/MBaaS providers, which you can use to store the answers in the cloud. Some of them offer server-side JavaScript hosting option. I've tried only one (which I am developing).
In case the submitted data isn't sensitive, you can save the answers in a free JayStorm Open app and you can open the records directly from Excel without writing any code.
Seems like an hour of development it's OK to build your report using Excel.
There are many BaaS providers, but as I know you need to develop at least in Node to return the results in CSV/XLS from the rest.


text:
Q: Android action chooser - how to handle intents inside the Activity? I've the following statement in my Manifest.xml:
<activity android:name="com.example.app.SelectLinks">

        <intent-filter>

        <action android:name="android.intent.action.VIEW" />
        <action android:name="android.intent.action.PICK" />
        <action android:name="android.intent.action.OPEN" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
        <data android:scheme="file" />
        <data android:mimeType="*/*" />
        <data android:pathPattern=".*\\.pls" />

        </intent-filter>

    </activity>

My app appears in the action chooser when I try to open the .pls file. The problem is I'don't know how to handle this on the Activity's site. Any examples appreciated.

A: In the activity call getIntent(). It returns an Intent object that started the activity.
You can obtain the data and other information from the intent by calling its methods such as getAction(), getType(), getData(), getCategories() and getExtras().
See Intent documentation for more information.
Note that if the launchMode of the activity is singleTop, implement onNewIntent() callback, there the intent is passed as a parameter. More about that here.


text:
Q: Concentrate two lists alternating python I want to combine two lists in an alternating way in Python.
list1 = ['A']
list2 = [1, 2, 3, 4]

What I've tried:
combination = [x for y in zip(list1, list2) for x in y]
# Output:
['A', 1]

# Expected output:
['A', 1, 'A', 2, 'A', 3, 'A', 4]

How can I combine these two lists and get the expected output? (Preferably list comprehension)

A: list1*len(list2) will repeat the first list elements as many times as the length of the second list.
combination = [x for y in zip(list1*len(list2), list2) for x in y]

['A', 1, 'A', 2, 'A', 3, 'A', 4]

A: One way is to use itertools cycle function:
from itertools import cycle

list1 = ['A']
list2 = [1, 2, 3, 4]

combination = [x for y in zip(cycle(list1), list2) for x in y]

This also works with
list1 = ['A', 'B']


text:
Q: Angular lazy loading with children for named outlets First of all let me mention that below mentioned is simplified example of my all routes. Just the part that is not working. I have an angular project (it's nativescript angular project actually, but I guess the problem is in angular actually). The version of angular used is 8.2.x.
I have following app-routing.module.ts, which basically redirects everything to HomeModule:

const routes: Routes = [
    { path: '', redirectTo: 'home', pathMatch: 'full' },
    { path: 'home', loadChildren: () => import('~/app/home/home.module').then((m) => m.HomeModule) }
];

Then comes home-routing.module.ts, which has following in it:

const routes: Routes = [
    {
        path: '',
        component: HomeComponent,
        children: [
            {
                path: '',
                component: Outlet1Component,
                outlet: 'outlet1',
            },
            {
                path: '',
                component: Outlet2Component,
                outlet: 'outlet2',
            },
        ],
    },
];

Now HomeComponent is successfully loaded and it has several named outlets in it and I want those outlets also to load their own components, that are configured in router. But that part is not working and I don't now how to fix that.
UPDATE
Here are 2 Nativescript playground examples:

*

*version 1

*version 2
The first version works correctly (per angular logic) and loads the components for outlets. The second version doesn't load the components for outlets.
Also nativescript repo issue for reference.

A: You just need to do some small changes.
change your app-routing.module.ts to
const routes: Routes = [
    { path: '', redirectTo: '/home/default/(outlet1:outlet1route//outlet2:outlet2route)', pathMatch: 'full' },
    { path: 'home', loadChildren: () => import('~/app/home/home.module').then((m) => m.HomeModule) }
];

and the home-routing.module.ts to
const routes: Routes = [
    {
        path: 'default',
        component: HomeComponent,
        children: [
            {
                path: 'outlet1route',
                component: Outlet1Component,
                outlet: 'outlet1',
            },
            {
                path: 'outlet2route',
                component: Outlet2Component,
                outlet: 'outlet2',
            },
        ],
    },
];

This it will navigate to home component and then it will load both Outlet1Component and Outlet2Component in each respective outlet.


text:
Q: Obtain a character entered by the user and store it into a variable (Java) The code below is to get a string entered by a user in a text box (from a GUI) and store it into a variable called aString:
aString = txtString.getText();

The code below does not work just like the code above because it is a char rather than string. What is the other way of obtaining a character from the user (as char) and storing it in a variable to be later used in the program?
char aChar = txtCharToString.getText();

A: you could use this if you need the whole characters:
String str = txtCharToString.getText().toString();
char[] aChar = str.toCharArray();

or like this if just the first char:
char aChar = txtCharToString.getText().charAt(0);


text:
Q: Show that, for large N, the proportion of positive integers n≤N...
Show that, for large $N$, the proportion of positive integers $n ≤ N$
(a) not divisible by $2^7$is $1 − \frac{1}{2^7}$
(b) not divisible by any of $2^7, 3^4, 5^3, 7^2, 11^2, 13^2, 17^2, 19^2, 23^2$ is $(1-\frac{1}{3^4})(1-\frac{1}{2^7})\cdots(1-\frac{1}{23^2}) ≈ .931.$

For part a, the number of naturals $i\leq n$ that are divisible by $p$ (call this count $c$) satisfies $\frac{n}{p}-1\lt c\lt \frac{n}{p}+1$, so the density $d = \lim_{n\rightarrow\infty}\frac{c}{n}$ satisfies $\frac{1}{p}-\frac{1}{n}\lt d\lt \frac{1}{p}+\frac{1}{n}$ for all $n$; therefore we must have $d=\frac{1}{p}$
How do I apply this to part (b)?

A: It is pure probability at that point. not divisible by an of a,b,c,d, or e is the same as (not divisible by a and not divisible by b and ...) which are independent for large N so you have P(not divisible by a)*P(not divisible by b)P(not divisble by c)...


text:
Q: New line python3 I am trying to write a string converted from a tuple to a file where after the string ends I wish to input a new line but using \n I came across an error.
Ms = 2
Mbh = 4.3e6
Msu = Ms/Mu
Mbu = Mbh/Mu
n = 1
test = '"scattter -n',n,'-A 0.005 -g 1e-5 -t 100000 -i "-M',Mbu,' -rm 3 -R 0 -v 0.0.86680911331878907 -t-q 0.5 -a 1.0 -e 0 -r1 9.8863538914005233E-003 -t1 -q 1 -a 6.2500000000000000E-002 -e 0 -r1 9.8863538914005233E-003 -r2 9.8863538914005233e-003"'

string = str(test)
f = open("set1_M2.dat", 'w')
f.write(string\n) #New line
f.write("n, Mbu, Msu\n")
f.write(str([n, Mbu, Msu]))
f.close()

And here is the traceback that I get when I run this error:
f.write(string\n)
                 ^
SyntaxError: unexpected character after line continuation character

I am not sure on how to combat this, I have tried to adjust the quotations on the string but the original "test" needs to stay the same.

A: Did you try:
f.write("\n")

?
This says to write the newline to file f. Read more here: writing string to a file on a new line everytime?


text:
Q: Aiming to discern verbs and what may get requested to go after them or not I think I may get transitive verbs, (request an argument after them) and intransitive verbs, (may not request an argument after them).

"Being chosen is".

I think this got discerned a complete sentence. So a copulative verb is may not request an argument. So it may seem intransitive?
May this seem a complete sentence?

I won't.

I, subject, will, modal verb(?), not, adverb.
There seems no noun here, no object.
I think I may get transitive and intransitive verbs. May copulative (copular[?]) verbs and modal verbs request an argument, object, noun after them?

A: To be a complete sentence the copula is, which is the verb heading the clause, requires a complement; for instance:

Being chosen is a great honor.

The construction BE + the past participle of a verb is the passive voice. In this construction, the object of the active verb (the 'Patient' which is acted on) becomes the subject of the passive construction, with the active-voice subject (the 'Agent', the person performing the action) left unexpressed, or expressed with a by phrase. But this is only a syntactical change; the semantic relationships are unchanged. The construction is employed to move the 'focus' of the sentence, or to avoid expressing the Agent

subjectThe votersagent     chose         objectJohnpatient.  =
        subjectJohnpatient   was chosen   by the votersagent.

*

*Note that (aside from a category of exceptions which I won't go into here), only transitive verbs can be cast in the passive voice, because only transitive verbs have objects which can be cast as the subject of a passive construction.

In your example, the verb BE is cast in the -ing form and acts as a gerund. In this particular case the subject of being chosen (the Patient of choose) is also omitted; presumably it can be inferred from the context.


text:
Q: Porque ocorre "undefined" mesmo definindo o elemento exato a ser atingido? Estou aplicando uma injeção na barra de endereço do navegador web, sobre a página de um vídeo no youtube, no qual desejo extrair a data da postagem do mesmo.
Se abrirmos este link vemos uma div similar a esta:

Ao selecionarmos a data da postagem e em seguida usar a ferramenta "View Selection Source" disponível no próprio navegador web, podemos ver o código-fonte da linha selecionada:

(fonte: mplayerplugin @ sites.google.com)
De posse do nome da classe watch-time-text, tentei fazer o seguinte:
javascript:postado=document.getElementsByClassName("watch-time-text").innerHTML; alert(postado);

E ocorreu o seguinte:

(fonte: mplayerplugin @ sites.google.com)
Porque ocorre esse undefined mesmo o elemento existindo na pagina?
Porque um gif vale mais do que mil palavras

A: O método getElementsByClassName retorna uma coleção de elementos e não um elemento apenas.
Se você tem certeza que só existe um elemento com esta classe pode usar o índice 0 pra obtê-lo.
postado = document.getElementsByClassName("watch-time-text")[0].innerHTML;
alert(postado);


text:
Q: how to append .csv files in a folder ( side by side with 2 columns gap) I am appending 10 CSV file in a folder, I want to merge them vertically not horizontally, how can I do that
this is the format I am looking for
[df1  df2  df3 ......... df10]

but  Not like this
[

df1
df2
...
df10

]

The code
import pandas as pd
import glob

path = r' ' # use your path
all_files = glob.glob(path + "/*.csv")

li = []

this is the code i am trying
for filename in all_files:
    df = pd.read_csv(filename, index_col=None, header=0)
    li.append(df)

frame1 = pd.concat(li, axis=0, ignore_index=True)
frame1.to_csv('name of 'folder )

A: I don't want to just give code as that might have errors as I am a newbie in Python, but I would help with the step-by-step process of doing this. You need to:

*

*Create ten dataframes with the ten csv files

*Transpose them using the ".T" function(rows become columns and vice-versa). This would
be a lot easier if you just write a simple function for that.

*Convert dataframes to csv
df.to_csv(file_name, sep=',') #Seperator can be anything you want

*Merge them with glob or glob2

*Convert to dataframe again

*Transpose back using the .T function


text:
Q: mysql - find all students of a class if at least one student attended I have four tables to map students and classes they attend, and to keep attendance info with start and end times.
Reproducible table schemas with records:
CREATE TABLE IF NOT EXISTS `student` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
)ENGINE=InnoDB;

INSERT INTO `student` (`id`, `name`) VALUES
(1, 'student 1'),
(2, 'student 2'),
(3, 'student 3'),
(4, 'student 4'),
(5, 'student 5');

CREATE TABLE IF NOT EXISTS `class` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
)ENGINE=InnoDB;

INSERT INTO `class` (`id`, `name`) VALUES
(1, 'class 1'),
(2, 'class 2');

CREATE TABLE IF NOT EXISTS `student_class` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `student_id` int(11) DEFAULT NULL,
  `class_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  FOREIGN KEY (`student_id`) REFERENCES `student` (`id`),
  FOREIGN KEY (`class_id`) REFERENCES `class` (`id`)
)ENGINE=InnoDB;

INSERT INTO `student_class` (`id`, `student_id`, `class_id`) VALUES
(1, 1, 1),
(2, 2, 1),
(3, 3, 1),
(4, 4, 2),
(5, 5, 2);

CREATE TABLE IF NOT EXISTS `attendance` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `student_class_id` int(11) DEFAULT NULL,
  `start_time` time DEFAULT NULL,
  `end_time` time DEFAULT NULL,
  PRIMARY KEY (`id`),
  FOREIGN KEY (`student_class_id`) REFERENCES `student_class` (`id`)
)ENGINE=InnoDB;

INSERT INTO `attendance` (`id`, `student_class_id`, `start_time`, `end_time`) VALUES
(1, 1, '09:00:00', '10:00:00');

Problem:
I need to list down rows which only shows all attendance of a class to which at least one student attended,
(even if the rest of students have null for start_time, end_time).
Here is my current sql:
SELECT c.id classId, sc.id mapperId, a.start_time startTime, a.end_time endTime FROM class c
JOIN student_class sc ON sc.class_id = c.id
LEFT JOIN attendance a ON a.student_class_id = sc.id;

The result should look like this.

classId
mapperId
startTime
endTime

1
1
09:00:00
10:00:00

1
2
NULL
NULL

1
3
NULL
NULL

A: @user you can get the result set you are looking for my using another instance of your query modified slightly as a sub query, like this:
SELECT c.id classId,
    sc.id mapperId,
    a.start_time startTime,
    a.end_time endTime
FROM class c
JOIN student_class sc ON sc.class_id = c.id
LEFT JOIN attendance a ON a.student_class_id = sc.id
WHERE `c`.`id` IN (
  SELECT DISTINCT c.id classId
  FROM class c
  JOIN student_class sc ON sc.class_id = c.id
  JOIN attendance a ON a.student_class_id = sc.id
  )

Here is a mock up of the answer on sqlfiddle.com

A: Just add a condition for the class id
SELECT c.id classId, sc.id mapperId, a.start_time startTime,
a.end_time endTime FROM class c
JOIN student_class sc ON sc.class_id = c.id
LEFT JOIN attendance a ON a.student_class_id = sc.id
where c.id in (select distinct sc.class_id
            from attendance a
            join student_class sc
            on a.student_class_id = sc.id);

A: Based on your question answer will be like this
  SELECT cls.id, stdclass.id AS mapperId , att.start_time ,att.end_time FROM attendance att INNER JOIN student_class stdclass ON att.student_class_id = stdclass.id INNER JOIN class cls ON stdclass.class_id = cls.id INNER JOIN student std ON stdclass.student_id = std.id


text:
Q: Use a specific minSdkVersion only in a Debug mode How can I use a specific minSdkVersion only in a debug mode?
I want to use the minSdkVersion 21 for debug mode, but minSdkVersion 15 for the release. I don't wanna use flavors for this because will give troubles.
I think the could be like this (but don't work):
defaultConfig {
        applicationId "blacktoad.com.flapprototipo"
        minSdkVersion 15

        debug{
            minSdkVersion 21
        }

        targetSdkVersion 23
        versionCode 42
        versionName "1.72"

        multiDexEnabled true
    }

A:
I don't wanna use flavors for this because will give troubles.

I don't think you can do it without productFlavors. I am leaving this answer here for others who have no issue using productFlavors.
https://developer.android.com/studio/build/multidex.html#dev-build
Basically all you need to do is declare productFlavors with different minSdkVersion:
productFlavors {
    dev {
        // Enable pre-dexing to produce an APK that can be tested on
        // Android 5.0+ without the time-consuming DEX build processes.
        minSdkVersion 21
    }
    prod {
        // The actual minSdkVersion for the production version.
        minSdkVersion 14
    }
}

A: It took me almost a day to create this script. Please take note of this for keepsake, but only use this as a last resort.
android.applicationVariants.all { variant ->

    //Making specific variant disablements for faster build
    if (variant.buildType.name.contains("debug")) {
        println "Making min version to 21 and disabling multidex"
        variant.mergedFlavor.setMultiDexEnabled false

        def versionMin = new com.android.builder.core.DefaultApiVersion(21)
        variant.mergedFlavor.setMinSdkVersion versionMin
    }
}

A: There exist a better way to do it without Product Flavors or hooking into the build flow.
Example:
  buildTypes {
     debug {
       defaultConfig.minSdkVersion 19
       defaultConfig.vectorDrawables.useSupportLibrary = true
       defaultConfig.multiDexEnabled = true
     ...

A: I know this is an old question, but there is a very simple solution, even without setting up separate flavors. Just replace the line;
minSdkVersion 21

with
minSdkVersion gradle.startParameter.taskNames.toString().contains("Release")?16:21

and viola, it will work.

A: Try this
androidComponents {
    beforeVariants(selector().withName("debug")) { variantBuilder ->
        variantBuilder.minSdk = 21
}}

For more information about beforeVariants, can check this link


text:
Q: Ubuntu server and PHP $_SERVER['REMOTE_ADDR'] Ive set up my own server with LAMP. Im using ubuntu server. When i try to find the user ip with:
 $_SERVER['REMOTE_ADDR']
it returns the server ip.
I have a static ip on my home router (eg, 58.83.2283.2) which forwards all HTTP requests from port 80 to my laptop server (eg, 192.134.1)
So $_SERVER['REMOTE_ADDR'] is returning "192.134.1" and not the user ip.

A: This is a consequence of using NAT.
Either run an HTTP proxy on the router (and use X-Forwarded-For instead of REMOTE_ADDR) or give the machine running the HTTP server its own Internet facing IP address.


text:
Q: Special Character check using Java Pattern I want to generate Two patterns with below information,
1)The following special characters cannot be entered in the first name, last name, email, phone number fields in the Account form:
Pattern  " [ ] : ; | = + * ? < > / \ ,
Names cannot start with a period
2)The following special characters cannot be entered in the Company address fields:
Pattern < > / \ |
Please give me an idea.
Thanks in advance

A: Try these patterns
for 1st point
(?i)^([a-z][^"\[:\]\|=\+\*\?<>\\\/\r\n]+)$

for 2st point
(?i)^([a-z][^<>\\\/\|\r\n]+)$

Explanations
1st Pattern

"(?i)" +                               -- Match the remainder of the regex with the options: case insensitive (i)
"^" +                                  -- Assert position at the beginning of a line (at beginning of the string or after a line break character)
"(" +                                  -- Match the regular expression below and capture its match into backreference number 1
   "[a-z]" +                              -- Match a single character in the range between "a" and "z"
   "[^\"\\[:\\]\\|=\\+\\*\\?<>\\\\\\/\r\n]" +       -- Match a single character NOT present in the list below
                                             -- The character """
                                             -- A [ character
                                             -- The character ":"
                                             -- A ] character
                                             -- A | character
                                             -- The character "="
                                             -- A + character
                                             -- A * character
                                             -- A ? character
                                             -- One of the characters "<>"
                                             -- A \ character
                                             -- A / character
                                             -- A carriage return character
                                             -- A line feed character
      "+" +                                  -- Between one and unlimited times, as many times as possible, giving back as needed (greedy)
")" +
"$"                                    -- Assert position at the end of a line (at the end of the string or before a line break character)

2nd Pattern

"(?i)" +                  -- Match the remainder of the regex with the options: case insensitive (i)
"^" +                     -- Assert position at the beginning of a line (at beginning of the string or after a line break character)
"(" +                     -- Match the regular expression below and capture its match into backreference number 1
   "[a-z]" +                 -- Match a single character in the range between "a" and "z"
   "[^<>\\\\\\/\\|\r\n]" +       -- Match a single character NOT present in the list below
                                -- One of the characters "<>"
                                -- A \ character
                                -- A / character
                                -- A | character
                                -- A carriage return character
                                -- A line feed character
      "+" +                     -- Between one and unlimited times, as many times as possible, giving back as needed (greedy)
")" +
"$"                       -- Assert position at the end of a line (at the end of the string or before a line break character)

code
try {
    boolean foundMatch = subjectString.matches("(?i)^([a-z][^\"\\[:\\]|=+*?<>\\\\/\\r\\n]+)$");
} catch (PatternSyntaxException ex) {
    // Syntax error in the regular expression
}

A: Instead of using a regular expression, which you're obviously not confident with, you could use the String.contains() method.
However, if you must use regex, like Mayur Patel said, "[ab]" basically means a or b ! You should check out regularexpressions.info

A: Below is the solution of my problem
1) (?i)^([a-z][^\"\[:\]|=+*.?<>\\/\r\n]+)$
2) (?i)^([a-z][^\"<>|\\/\r\n]+)$
I've also added period symbol in 1) point for checking not to start Names with period symbol.
Thanks a lot Cylian and Andy for the help, It really helped me a lot.
Thanks again :)


text:
Q: How to hide divs on hover? I've got a header for my site that looks like this:
.header-cont {
    width:100%;
    position:fixed;
    top:0px;
}
.header {
    height:50px;
    background:#F0F0F0;
    border:1px solid #CCC;
    width:950px;
    margin:0px auto;
}
.header-button {
    background: #73e3eb;
    background-image: -webkit-linear-gradient(top, #73e3eb, #5ec9d1);
    background-image: -moz-linear-gradient(top, #73e3eb, #5ec9d1);
    background-image: -ms-linear-gradient(top, #73e3eb, #5ec9d1);
    background-image: -o-linear-gradient(top, #73e3eb, #5ec9d1);
    background-image: linear-gradient(to bottom, #73e3eb, #5ec9d1);
    -webkit-border-radius: 13;
    -moz-border-radius: 13;
    border-radius: 13px;
    font-family: Lora;
    color: #6293ad;
    font-size: 20px;
    padding: 20px 15px 10px 15px;
    text-decoration: none;
}
.clearfix:after {
    display:block;
    clear:both;
}
.menu-wrap {
    width:100%;
    box-shadow:0px 1px 3px rgba(0,0,0,0.2);
    background:#3e3436;
}
.menu {
    width:1000px;
    margin:0px auto;
}
.menu li {
    margin:0px;
    list-style:none;
    font-family:'Ek Mukta';
}
.menu a {
    transition:all linear 0.15s;
    color:#919191;
}
.menu li:hover > a, .menu .current-item > a {
    text-decoration:none;
    color:#be5b70;
}
.menu .arrow {
    font-size:11px;
    line-height:0%;
}
.menu > ul > li {
    float:left;
    display:inline-block;
    position:relative;
    font-size:19px;
}
.menu > ul > li > a {
    padding:10px 40px;
    display:inline-block;
    text-shadow:0px 1px 0px rgba(0,0,0,0.4);
}
.menu > ul > li:hover > a, .menu > ul > .current-item > a {
    background:#2e2728;
}
.menu li:hover .sub-menu {
    z-index:1;
    opacity:1;
}
.sub-menu {
    width:150px;
    padding:5px 0px;
    position:absolute;
    top:100%;
    left:0px;
    z-index:-1;
    opacity:0;
    transition:opacity linear 0.15s;
    box-shadow:0px 2px 3px rgba(0,0,0,0.2);
    background:#2e2728;
}
.sub-menu li {
    display:block;
    font-size:16px;
}
.sub-menu li a {
    padding:10px 30px;
    display:block;
}
.sub-menu li a:hover, .sub-menu .current-item a {
    background:#3e3436;
}

Home

▼Sites

Site A

Site B

Site C

Site D

About

Sorry for the long code, but there it is. My problem is that when you hover over the area below the 'Sites' item, the div that is the dropdown list shows. I'd like to change it so that it only shows when you hover on 'Sites', but I'm not sure how. Anybody out there know?

A: Instead of using the opacity property, you should use the visibility property. The opacity property simply makes the element see-through. The visibility property hides the element entirely, but keeps the spacing of the element in the document's normal flow.
JSFiddle Example
.menu li:hover .sub-menu {
    visibility: visible;
}

.sub-menu {
    width:150px;
    padding:5px 0px;
    position:absolute;
    top:100%;
    left:0px;
    visibility: hidden;
    transition:opacity linear 0.15s;
    box-shadow:0px 2px 3px rgba(0,0,0,0.2);
    background:#2e2728;
}

You also don't need the z-index property.
Alternatively, you could use display: none; and display: block; as well, which does the same thing as the visibility property, except that it doesn't keep the spacing in the document's normal flow.


text:
Q: Adobe Flash Builder (1046: Type was not found or was not a compile-time constant) I am using Adobe Flash Builder for the first time, and I am trying to create a Flex project. I am going to be embedding a flash game in a nodeJS app, so I am using https://github.com/sinnus/socket.io-flash. Socket.io-flash requires websocketJS, and I have added both the socket.io-flash folder (straight from github), and the websocketJS folder (also from github) to Flash Builder's source path (so the files should be getting recognized when they are imported - and they are). I am getting this error for two of the imports:
1046: Type was not found or was not a compile-time constant: SocketIOEvent.

and...
1046: Type was not found or was not a compile-time constant: SocketIOErrorEvent.

Like I said, the import lines are fine (no errors being thrown there) - the errors come from the method declarations - here is my .mxml file:
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
               xmlns:s="library://ns.adobe.com/flex/spark"
               xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600">
    <fx:Declarations>
        <!-- Place non-visual elements (e.g., services, value objects) here -->
    </fx:Declarations>
    <s:VGroup>
        <s:TextArea id="textArea" width="300" height="300"/>
        <s:Button label="Connect" click="onConnectClick()"/>
        <s:Button label="Send" click="onSendClick()"/>
        <s:Button label="Disconnect" click="onDisconnectClick()"/>
    </s:VGroup>
    <fx:Script>
        <![CDATA[
            import com.adobe.serialization.json.JSON;
            import io.socket.flash.ISocketIOTransport;
            import io.socket.flash.ISocketIOTransportFactory;
            import io.socket.flash.SocketIOErrorEvent;
            import io.socket.flash.SocketIOEvent;
            import io.socket.flash.SocketIOTransportFactory;
            import io.socket.flash.WebsocketTransport;
            import io.socket.flash.XhrPollingTransport;

            private var _socketIOTransportFactory:ISocketIOTransportFactory = new SocketIOTransportFactory();
            private var _ioSocket:ISocketIOTransport;

            private function onConnectClick():void
            {
                _ioSocket = _socketIOTransportFactory.createSocketIOTransport(XhrPollingTransport.TRANSPORT_TYPE, "localhost:9000/socket.io", this);
                _ioSocket.addEventListener(SocketIOEvent.CONNECT, onSocketConnected);
                _ioSocket.addEventListener(SocketIOEvent.DISCONNECT, onSocketDisconnected);
                _ioSocket.addEventListener(SocketIOEvent.MESSAGE, onSocketMessage);
                _ioSocket.addEventListener(SocketIOErrorEvent.CONNECTION_FAULT, onSocketConnectionFault);
                _ioSocket.addEventListener(SocketIOErrorEvent.SECURITY_FAULT, onSocketSecurityFault);
                _ioSocket.connect();
            }

            **private function onSocketConnectionFault(event:SocketIOErrorEvent):void**
            {
                logMessage(event.type + ":" + event.text);
            }

            **private function onSocketSecurityFault(event:SocketIOErrorEvent):void**
            {
                logMessage(event.type + ":" + event.text);
            }

            private function onDisconnectClick():void
            {
                _ioSocket.disconnect();
            }

            **private function onSocketMessage(event:SocketIOEvent):void**
            {
                if (event.message is String)
                {
                    logMessage(String(event.message));
                }
                else
                {
                    logMessage(JSON.encode(event.message));
                }
            }

            private function onSendClick():void
            {
                _ioSocket.send({type: "chatMessage", data: "Привет!!!"});
                _ioSocket.send({type: "chatMessage", data: "Delirium tremens"});
                _ioSocket.send("HELLO!!!");
            }

            **private function onSocketConnected(event:SocketIOEvent):void**
            {
                logMessage("Connected" + event.target);
            }

            **private function onSocketDisconnected(event:SocketIOEvent):void**
            {
                logMessage("Disconnected" + event.target);
            }

            private function logMessage(message:String):void
            {
                textArea.text = textArea.text + message + "\n";
            }
        ]]>
    </fx:Script>
</s:Application>

I have encased the lines where the errors are thrown from with '**' (it is having trouble with what is being imported for some reason). In my Flash Builder project I have, in the libs folder, the websocketJS folder, and the socket.io-flash folder, and they have both been added to the source path. Any help would be greatly appreciated - thanks!

A: The function "logMessage" is simply not defined. Use "trace" as alternative (e.g.  trace(event.type + ":" + event.text);