text:
Q: Python conditional statement within a Class What is the best way to achieve having class attributes that change, based on input that has been passed in via a cli argument?
What I've written works perfectly fine, however feels overly messy and bad design. Is there a better way to go about this?
The example below has four different inputs, however as this program grows larger this would become very messy.
Here's some short example code;
class Example(object):

    def __init__(self, var1):
        self.var1 = var1
        self.var2 = None
        self.var3 = None
        self.var4 = None

        if var1 == 'foo':
            self.var2 = 'foo2'
            self.var3 = 'foo3'
            self.var4 = 'foo4'
        elif var1 == 'bar':
            self.var2 = 'bar2'
            self.var3 = 'bar3'
            self.var4 = 'bar4'
        elif var1 == 'foobar':
            self.var2 = 'foobar2'
            self.var3 = 'foobar3'
            self.var4 = 'foobar4'
        elif var1 == 'barfoo':
            self.var2 = 'barfoo2'
            self.var3 = 'barfoo3'
            self.var4 = 'barfoo4'

def main()

    parser = argparse.ArgumentParser()
    parser.add_argument('input')
    args = parser.parse_args()

    example = Example(args.input)

    print(example.var2) # returns 'foo2'

Example of calling with an argument;
python main.py foo

A: There are many ways to clean this up, as suggested in the comments. For something of the size and scale of your example, I would do something like this:
class Example:
    _DEPENDENT_VALS = {
        'foo': ('foo2', 'foo3', 'foo4'),
        'bar': ('bar2', 'bar3', 'bar4'),
        'foobar': ('foobar2', 'foobar3', 'foobar4'),
        'barfoo': ('barfoo2', 'barfoo3', 'barfoo4')
    }

    def __init__(self, var1):
        self.var1 = var1
        self.var2 = None
        self.var3 = None
        self.var4 = None

        if var1 in Example._DEPENDENT_VALS:
            self.var2, self.var3, self.var4 = Example._DEPENDENT_VALS[var1]

This method might not always be appropriate depending on the number and type of values you're setting but it's one way to go about it.

A: ls=['foo','bar','foobar','barfoo'] #adds the list of prefixes

if self.var1 in ls:
    self.var2= f'{self.var1}2'
    self.var3= f'{self.var1}3'
    self.var4= f'{self.var1}4'

A: Define a dict mapping prefixes to a tuple of the three modifiers, then use it to initialize them:
class Example:
    _var_suffixes = {'foo': ('1', '2', '3'),
                     'bar': ('1', '2', '3'),
                     'foobar': ('1', '2', '3'),
                     'barfoo': ('1', '2', '3'),
                     }
    def __init__(self, var1):
        self.var1 = var1
        self.var2 = None
        self.var3 = None
        self.var4 = None

        if var1 in self._var_suffixes:
            suf2, suf3, suf4 = self._var_suffixes[var1]
            self.var2 = var1 + suf2
            self.var3 = var1 + suf3
            self.var4 = var1 + suf4

Optionally, this may make more sense to store var2 through var4 as a list (especially if the number of suffixes is variable by key), in which case you'd do something like this, which is even simpler:
class Example:
    _var_suffixes = {'foo': ('1', '2'),
                     'bar': ('1', '2', '3'),
                     'foobar': ('1', '2', '3', '4'),
                     'barfoo': ('1', '2', '3', '4', '5'),
                     }
    def __init__(self, var1):
        self.var1 = var1
        self.varlist = []

        for suf in self._var_suffixes.get(var1, ()):
            self.varlist.append(var1 + suf)

    # Optional property for access by name
    @property
    def var2(self):
        try:
            return self.varlist[0]
        except IndexError:
            return None

A: The class body is just Python code. It has specific scope rules, but anything goes otherwise. This means you can create functions conditionally:
class C:
    if some_condition:
        def optional_method(self):
            pass

or pull methods from elsewhere:
import some_module

class D:
    method_name = some_module.function_that_accepts_self

A: One approach is to keep __init__ as "dumb" as possible, define separate class methods for each "style" of object, and push the burden of selecting the right class method to call to the caller.
class Example:

    def __init__(self, var1, var2, var3, var4):
        self.var1 = var1
        self.var2 = var2
        self.var3 = var3
        self.var4 = var4

    @classmethod
    def foo(cls):
        return cls('foo', 'foo2', 'foo3', 'foo4')

    @classmethod
    def bar(cls):
        return cls('bar', 'bar2', 'bar3', 'bar4')

    # etc

# Instead of Example('foo')
e = Example.foo()

The only thing you lose here is the ability to pass an unknown value to Example and get a properly initialized value back, for example,
x = "..."  # Assumed to be foo, bar, foobar, or barfoo
e = Example(x)

However, the caller can always use whatever method you might have hidden in side Element.__init__ to pick the values for var2 et al. to pick which class method to all. For example,
x = "foo"
e = getattr(Example, x)()  # e = Example.foo()

A: Don't know if the best option but assuming that actual values aren 'foo1' 'foo2' but something else or more complex I would go for updating the self.dict
Two ways (I think the seccond is more clear)
class A():
    def __init__(self,var1):
        self.var1 = var1
        fooDict = {'var2':'foo2','var3':'foo3','var4':'foo4'}
        foovarDict = {'var2':'foovar2','var3':'foovar3','var4':'foovar4'}
        if var1 == 'foo':
            self.__dict__ = {**self.__dict__,**fooDict}
        elif var1 == 'foovar':
            self.__dict__ = {**self.__dict__,**foovarDict}

    def getVars(self):
        print(self.var1)
        print(self.var2)
        print(self.var3)
        print(self.var4)

a = A('foo')
a.getVars()

#ouputs
#foo
#foo2
#foo3
#foo4

b = A('foovar')
b.getVars()

#outputs
#foovar
#foovar2
#foovar3
#foovar4

Second way:
class A():
    def __init__(self,var1):
        self.var1 = var1
        fooDict = {'var2':'foo2','var3':'foo3','var4':'foo4'}
        foovarDict = {'var2':'foovar2','var3':'foovar3','var4':'foovar4'}
        if var1 == 'foo':
            self.__dict__.update(fooDict)
        elif var1 == 'foovar':
            self.__dict__.update(foovarDict)

    def getVars(self):
        print(self.var1)
        print(self.var2)
        print(self.var3)
        print(self.var4)

a = A('foo')
a.getVars()

b = A('foovar')
b.getVars()

with same outputs


text:
Q: iOS App Store app icon: 1024x1024 or 3072x3072? Reference: https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/MobileHIG/IconMatrix.html#//apple_ref/doc/uid/TP40006556-CH27-SW1
Does the app icon for the iOS App Store need to be 3072 x 3072 px for the latest iPhone since it's an @3x scale factor device?

A: No, the image sizes listed in the table are absolute values.
The Icon has to be of size 1024 x 1024
In addition the app store icon is somewhat special since it is completely unaffected by the actual hardware. The device does not change the image size you need to provide for the store.

redpajama_set_name: RedPajamaStackExchange


text:
Q: wrong URL configuration/pattern in django In django template, to call url for a link this is what I have done
{% for url in request.session.url %}

        {{url.name}}

{% endfor %}

With the above when I load the page the links comes out very well as expected.
e.g. www.url.com/ for home
     www.url.com/staff/firstpage for firstpage
     www.url.com/staff/secondpage for secondpage etc

But when I click on any of the links it would extend the link of the existing page e.g. clicking on firstpage with
link www.url.com/staff/firstpage result turns out to be
e.g. www.url.com/staff/firstpage for home
     www.url.com/staff/firstpage/firstpage for firstpage
     www.url.com/staff/firstpage/secondpage for secondpage etc

This is my url.py
app_name="application_name"
urlpatterns=[
    url(r"^staff/",include('application_name.staff_url', namespace='staff')),
    url(r"^customer/",include('application_name.customer_url', namespace='customer')),
]

my staff_url.py
from application_name import views
app_name="staff"
urlpatterns=[
    url(r"^customers/",views.customers, name='customers'),
    url(r"^orders/$", views.orders, name='orders'),
    url(r"^payments/$", views.payments, name='payments'),
]

but when I use {% url %} i.e. instead of {{linkfield}} i am using {% url url.linkfield %}
it is producing error in the console i.e.
  raise NoReverseMatch(msg)
dango.urls.exceptions.NoReverseMatch: Reverse for 'whatever_linkname' not found. 'whatever_linkname' is not

a valid view function or pattern name.
This is my url.py
app_name="application_name"
urlpatterns=[
    url(r"^staff/",include('application_name.staff_url', namespace='staff')),
    url(r"^customer/",include('application_name.customer_url', namespace='customer')),
]

my staff_url.py
from application_name import views
app_name="staff"
urlpatterns=[
    url(r"^customers/",views.customers, name='customers'),
    url(r"^orders/$", views.orders, name='orders'),
    url(r"^payments/$", views.payments, name='payments'),
]

my customer_url.py
from application_name import views
app_name="customer"
urlpatterns=[
    url(r"^items/",views.items, name='items'),
    url(r"^checkout/$", views.checkout, name='checkout'),
    url(r"^make_payment/$", views.make_payment, name='make_payment'),
]

staf url would be staff/orders or staff/payments
customer urls would be customer/items or customer/checkout etc
Please what can i do

A: This is how u can do it:
In your case for example:

*

*If you don't have an app_name u don't need to write it.


text:
Q: How to force overwrite already deployed files in android delphi How to be sure that deployed files will be overwritten in android device?
Regarding:
http://docwiki.embarcadero.com/RADStudio/Rio/en/Deployment_Manager you can specify Overwrite feature for each file.

*Always: Deploy the local file if it is newer than the remote file, overwriting the remote file

*Never: Select this option for a file if you want to exclude it from being deployed.
It means, when you updating the app, and in destination path, remote file already exists (in mobile device), the file will be NOT overwritten, if it's timestamp is newer. Is it possible to force overwrite the newer files on device?
case study:I want to deploy "read only" database within application. In next update, I want to deploy actualized version, so DB file has to be overwritten. But what if database driver changes this file in device? (It is not guaranteed that db file will be not changed, even there will be no insert or update in DB - Probably driver can write some META data...).
What if user will have a wrong time in device (e.g. future years) and therefore "old" file in device will have newer timestamp?


text:
Q: When executing LOAD DATA in Hive, does it copies the data? When loading data stored in HDFS into HIVE, does this data from HDFS gets copied into a different format used by HIVE? Or does it uses the original files to store/select/insert/modify the data?
Context:
LOAD DATA INPATH '/home/user/sample.txt' OVERWRITE INTO TABLE employee;
Does HIVE uses /home/user/sample.txt always to store/select/insert/modify the data, or does it creates a new file occupying new space at HDFS/HBASE?

A: LOAD DATA INPATH does nothing except moving the HDFS files into the location of the table, and by "moving" I mean a metadata operation of the HDFS.

A: It is explained in the documentation :

If the keyword LOCAL is not specified, then Hive will either use the full URI of filepath, if one is specified, or will apply the following rules:
  [...]
  Hive will move the files addressed by filepath into the table (or partition)


text:
Q: Is there something analogous to syzygy for Noether identities? In variational calculus, Emily Noether's influence includes Noether identities.
Has anything been written about a relation analogous to syzygies for her identities?
Note both of these concepts are related to Hilbert's works.


text:
Q: How to handle signals when process is waiting in waitpid? I have a parent process with a user-defined signal handler. Whenever a signal received, I set a global variable and in my main loop i am checking whether the signal is received or not before each input processing.
I spawning a process to process the user input and use waitpid to collect the child wait status. Meanwhile if the parent process received the user-defined signal, how to handle it efficiently ?
Minimized code snip from my application
#include <stdio.h>
#include <signal.h>

volatile sig_atomic_t g_signal_number =0;

void sig_hup_handler()
{
 g_signal_number = SIGHUP;
}

void do_process_cleanup() {

  //Execute

}

int execute_user_input(char *str)
{

    pid_t cpid,w;
    cpid = fork();
    if (cpid == -1) {
        perror("fork");
        exit(EXIT_FAILURE);
    }
    if (cpid == 0) { //Child may take 10-20 second to process the string.
      execute_command(str);
      _exit(0);
    } else {
       w = waitpid(cpid, &status, 0);
    }
}

main()
{
  char str[1024];
  signal(SIGHUP, sig_int_handler);

  while(1) {

      if(g_signal_number)
      {
          do_process_cleanup();
          break;
      }
      get_user_input(str);
      if(!strcmp(str,"end"))
          break;
      execute_user_input(str);

  }
      exit(0;)
}

I tried the below code to fix this issue. Could someone suggest a better way to handle this problem ?
while (1) {

   int ret = waitpid(cpid, &status, WNOHANG);

   if(ret > 0)
         break;
   if(ret < 0)
         if(errno == EINTR)
             continue;
   if(g_signal_number)  // break the loop if signal recieved
       break
    sleep(1);
}

Also tried with SA_RESTART flag, But it didn't worked in my Linux flavor for waitpid system call.
   int main() {
   :
   sa.sa_handler = sig_hup;
   sigemptyset(&sa.sa_mask);
   sa.sa_flags = SA_RESTART;
   :
   while(1) {
        ret=waitpid(child_pid, &status, 0);
        /*
         *if waipid returns -1 and errno is set to
         *EINTR and g_signum is set,
         *break the loop.
         */
        if(ret == -1 && errno == EINTR && g_signum) {
             printf("signal is set, so break the loop\n");
             break;
        }
        printf("waitpid restart...\n");
   }

From the strace output i could see, After sending SIGHUP to PID 17618 also waitpid is not interrupted.
-bash-4.1$ strace -p 17618
Process 17618 attached
wait4(17619, 0x7ffc4a2e2c34, 0, NULL)   = ? ERESTARTSYS (To be restarted if SA_RESTART is set)
--- SIGHUP {si_signo=SIGHUP, si_code=SI_USER, si_pid=26521, si_uid=332691} ---
rt_sigreturn()                          = 61
wait4(17619,

Environment: a RedHat-like distro, 2.6.39 kernel
Update
If someone hit this issue in future please refer the answer for Why doesn't Linux accept() return EINTR?

A: The way SA_RESTART handled is a bit implementation defined. My Linux flavor(RedHat-like distro, 2.6.39 kernel) doesn't obey SA_RESTART for waitpid system call.
but i am able to solve this issue by setting sigaction inside signal handler.
/*
 *test_signal.c
 */
#include <signal.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
static struct sigaction sa;
/****Set this variable when SIGHUP received****/
volatile sig_atomic_t g_signum = 0;

/****SIGHUP HANDLER****/
void sig_hup(int signum) {
    /****Set the signal number****/
    g_signum = signum;
    /****Time to intrupt the system call****/
    sigaction(SIGHUP, &sa, 0);

}
int main() {
    int status,ret;
    pid_t child_pid;
    sa.sa_handler = sig_hup;
    sigemptyset(&sa.sa_mask);
    sigaction(SIGHUP, &sa, 0);
    child_pid = fork();
    if(child_pid == 0) {
        sleep(1);//Let the parent print the msg first
        printf("pid:%d:child going to sleep in a loop\n",getpid());
        while(1) {
            sleep(10);
        }
    }
    else{
        printf("parent pid: %d child pid: %d\n",getpid(),child_pid);
        while(1) {
            ret=waitpid(child_pid, &status, 0);
            /*
             *if waitpid returns -1 and errno is set to
             *EINTR and g_signum is set,
             *break the loop.
             */
            if(ret == -1 && errno == EINTR && g_signum) {
                 printf("signal is set, so break the loop\n");
                 break;
            }
            printf("waitpid restart...\n");
       }
    }
return 0;
}

Output:
-bash-4.1$ ./test_signal
parent pid: 11122 child pid: 11123
pid:11123:child going to sleep in a loop
signal is set, so break the loop
-bash-4.1$

Send the SIGHUP to parent:
-bash-4.1$ kill -s SIGHUP 11122

Strace Output:
-bash-4.1$ strace -p 11122
Process 11122 attached
wait4(11123, 0x7ffca4b72c24, 0, NULL)   = ? ERESTARTSYS (To be restarted if SA_RESTART is set)
--- SIGHUP {si_signo=SIGHUP, si_code=SI_USER, si_pid=26521, si_uid=332691} ---
rt_sigaction(SIGHUP, {0x400714, [], SA_RESTORER, 0x33c6432660}, NULL, 8) = 0
rt_sigreturn()                          = -1 EINTR (Interrupted system call)
write(1, "signal is set, so break the loop"..., 33) = 33
exit_group(0)                           = ?
+++ exited with 0 +++
-bash-4.1$


text:
Q: C# Checkboxlist Ok so I have a checkbox list with n checkboxes. Everytime I check a box I want that number to get added to a list (Chosen). When the box is unchecked I want to remove it from the list. Then when I hit a button I want to display the list in a textbox. Here is my code:
public partial class _Default : System.Web.UI.Page
{
    List<int> Chosen = new List<int>();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["Chosen"] == null)
        {
            Session["Chosen"] = new List<int>();
        }

        Chosen = (List<int>)Session["Chosen"];

        for (int i = 0; i < Numbers.Items.Count; i++)
        {
            if (Numbers.Items[i].Selected) { Chosen.Add(i + 1); }
            else { Chosen.Remove(i + 1); }
        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        foreach (var i in Chosen)
        {
            TextBox1.Text = Chosen[i].ToString();
        }
    }
}

Needless to say it does not work the way I want it to. When I select 1 and hit the button it writes 1 into the box, but if I unselect it and hit the button it leaves 1 there. Also if I select any number other than 1 I get an error on this line:
TextBox1.Text = Chosen[i].ToString();

Saying index is out of range. Yet when I debug the numbers seem to be allocating to the list properly.

A: Is this what you need?
<asp:TextBox ID="textBox1" runat="server">
</asp:TextBox>
<asp:CheckBoxList ID="Numbers" runat="server"
                   OnSelectedIndexChanged="UpdateCheckBoxex" AutoPostBack="true">
    <asp:ListItem Text="One" Value="One" />
    <asp:ListItem Text="Two" Value="Two" />
    <asp:ListItem Text="Three" Value="Three" />
    <asp:ListItem Text="Four" Value="Four" />
</asp:CheckBoxList>

protected void UpdateCheckBoxex(object sender, EventArgs e)
{
    string s = string.Empty;
    new List<ListItem>(Numbers.Items.Cast<ListItem>().Where(i => i.Selected)).ForEach(x => s += string.Format("{0}, ", x.Text));
    textBox1.Text = s;
}

In this case you don't need Chosen, but if you still need to populate it, you dont need foreach loop
List<int> Chosen = new List<int>();
Chosen.AddRange(Numbers.Items.Cast<ListItem>().Where(i => i.Selected).Select(x => Numbers.Items.IndexOf(x) + 1));

A: Try using:
TextBox1.Text = i.ToString();

Also, this will only show the last item selected. If you have multiples selected, you will have to concatenate all and then assign to TextBox1.Text. Or use this:
TextBox1.Text += i.ToString() + " ";

A: Suppose this is your CheckBoxList
<asp:CheckBoxList ID="Numbers" runat="server" AutoPostBack="True"
        onselectedindexchanged="Numbers_SelectedIndexChanged">
        <asp:ListItem>1</asp:ListItem>
        <asp:ListItem>2</asp:ListItem>
        <asp:ListItem>3</asp:ListItem>
        <asp:ListItem>4</asp:ListItem>
        <asp:ListItem>5</asp:ListItem>
    </asp:CheckBoxList>

The Code behind event: Edited
 protected void Numbers_SelectedIndexChanged(object sender, EventArgs e)
{
    List<int> Chosen = new List<int>();
  if (Session["Chosen"] == null)
    {
        Session["Chosen"] = new List<int>();
    }
    Chosen = (List<int>)Session["Chosen"];

    foreach (ListItem it in Numbers.Items)
        if (it.Selected)
        {
            if (!Chosen.Contains(Convert.ToInt32(it.Text)))
                Chosen.Add(Convert.ToInt32(it.Text));
        }
        else if (Chosen.Contains(Convert.ToInt32(it.Text)))
                Chosen.Remove(Convert.ToInt32(it.Text));
    TextBox5.Text="";
    foreach (int n in Chosen)
        TextBox5.Text +=  n.ToString() + " , ";

    Session["Chosen"] = Chosen;

  }

This does what you have explained as per my understanding
Edited and Tested

A: Instead of using TextBox1.Text = Chosen[i].ToString();
use
TextBox1.Text = String.Empty;
foreach (var i in Chosen)
{
   TextBox1.Text += i.ToString();
}

The problem is that when you use foreach, the value of i is actually a value of the actual element of the Chosen list, not an index.
The way you wrote is working well in a for loop:
    for (int i = 0; i < Chosen.Count; i++)
    {
        TextBox1.Text += Chosen[i].ToString();
    }


text:
Q: SQL server version error (datetime2) At my client machine application throwing below error. seems like error is related to sql server.
Application is developed in VS 2010, WPF.

The version of SQL Server in use does not support datatype 'datetime2'

any help would be appreciated.

A: if you are using Entity framework and sql server then actually issue is in Entity framework.
you have to make some changes in entity framework.
check below link would be helpful.
Entity Framework Error - The version of SQL Server in use does not support datatype 'datetime2'

A:
Application is developed in VS 2010, WPF

Irrelevant.

The version of SQL Server in use does not support datatype 'datetime2'

Well, it is quite exact in what it says, is is not? You use something in sql level with the datetime2 data type, the sql server version the client uses does not support that. Reason is- that is not an old data type, so old sql versions do not support it.
Simple like that.
Your fault.
Likely you have not specified a proper version as required so the client runs on a very old version of sql server.
Or the clients fault.
Tell him to upgrade or change your programming to use an older data type.


text:
Q: How do you encode the difference between atom charge and bond type in NetworkX so that they play a role in Graph Edit Distance? TLDR: How do you use node_match attributes to get NetworkX to recognise C+ and C atoms as different?
Here is an example of a pair of molecules I have calculated GED for.

I got a value of 0 for the GED using the following code:
import networkx as nx

def get_graph(mol):
  atoms = [atom.GetAtomicNum() for atom in mol.GetAtoms()]
  am = Chem.GetAdjacencyMatrix(mol,useBO=True)
  for i,atom in enumerate(atoms):
    am[i,i] = atom
  G = nx.from_numpy_matrix(am)
  return G

G1 = get_graph(mol1)
G2 = get_graph(mol2)

GED= nx.graph_edit_distance(G1, G2, edge_match=lambda a,b: a['weight'] == b['weight'])

print(GED)

So my understanding of the edge_match=lambda in this case is that it is being used to distinguish between single bonds and double bonds, is this correct? I believe this to be the case because when I run the code for propene and propane it gives a GED of 1, which to me would signify the change of the edge (double bond to single bond).
However, I believe that the reason that this code gives a GED of 0 for these two molecules is because it is considering the C+ and C atoms to be the same? Therefore considering the two structures as identical. How would I encode for the graph structure to recognise the C+ and C as different? I have been reading the NetworkX documentation for atom_match attributes but I really don't understand how I can use this to do what I want to do. If this isn't the solution then would I have to encode the Hydrogen numbers somehow?
(Side note: When using the same code for the same structures but with B in place of C, it gives a GED of 2, which I believe is because the B is set as BH where C is just C+. Picture of molecules below)

A: The reason networkx considers both C+ and C atoms as the same is because you are feeding atomic numbers (which doesn't change irrespective of the charge) to the adjacency matrix in this line:
am[i,i] = atom

There are two methods to make networkx differentiate between C+ and C.
Method 1: (Naive Method)
Adding Hydrogens to all the carbon atoms:
This method takes way too long to output the GED (more than 40 mins). So I do not think this method is efficient.
Method 2: (Hacky Method)
In this method, we capture information regarding the formal charge on the atoms, and on id of the C+ atom we add the formal charge to the atomic number and feed the sum to the adjacency matrix, in essence making networkx differentiate between C and C+ atoms since they now have different "atomic numbers" in the adjacency matrix. This method outputs the expected GED of 2.0.
from rdkit import Chem
from rdkit.Chem.Draw import IPythonConsole
IPythonConsole.ipython_useSVG=True
import networkx as nx

smiles_1 = 'CC(C)(C)[C+](C=C)(C=C)'
smiles_2 = 'CC(C)(C)C(C=C)(C=[C+])'

mol1 = Chem.MolFromSmiles(smiles_1)
mol2 = Chem.MolFromSmiles(smiles_2)

def get_graph(mol):
  atomic_nums = [atom.GetAtomicNum() for atom in mol.GetAtoms()]
  formal_charges = [atom.GetFormalCharge() for atom in mol.GetAtoms()]
  ad_matrix = Chem.GetAdjacencyMatrix(mol,useBO=True)
  for i,(a_num,f_c) in enumerate(zip(atomic_nums, formal_charges)):
    if f_c !=0:
      ad_matrix[i,i] = a_num + f_c
    else:
      ad_matrix[i,i] = a_num
  G = nx.from_numpy_array(ad_matrix)
  return G

G1 = get_graph(mol1)
G2 = get_graph(mol2)

GED= nx.graph_edit_distance(G1, G2, edge_match=lambda a,b: a['weight'] == b['weight'])

print((GED) )
# >> Outputs 2.0

Also note: from_numpy_matrix is deprecated in the latest version of networkx (version 3.0). So I have used from_numpy_array instead.


text:
Q: moment js issue with french format ACTUAL ISSUE:
am using momentjs and below code to validate date format
date = moment(dateVal, fmt);

if format is YYYY-MM-DD, and if dateVal is 2017-04, then date value is not coming as null. moment function is sending 2017-04-01 as the date back instead of "invalid date" or null. how do i change the code for the moment to show invalid date.
i tried this
date = moment(dateVal, fmt, true);

but for some reason when i use this, isValid is always coming as false, even when i send valid date and format.  for eg, 1/4/2017 with format MM/DD/YYYY is giving error with date = moment(dateVal, fmt, true)
here is my code
 var CustomDateValidate = function (dateVal, fmt) {
    var date = null;
    if (dateVal !== null && dateVal !== undefined) {
        fmt = defaultFor(fmt, getHiddenData().dateFormatJavascriptMoment); // here for en the fmt will be "MM/DD/YYYY" and for fr the fmt will be "YYYY-MM-DD"

        date = moment(dateVal, fmt, true);
        if (!(date.isValid())) {
            date = null;
        }
        //else
        if (date.year().toString().length < 4) {
            date = null;
        } else if (date.toString().toLowerCase() === 'invalid date') {
            date = null;
        } else if (date._i.toString().length > 10) {
            date = null;
        }
    }
    return date;

plz help.


text:
Q: Check Permission of a React Page used inside a Webview I need to check the permission of a React Page. This page is inside a webview.
the mobile app that use the webview is made in React-Native.
I used <WebView> from the library react-native-webview
this is my permission request inside the React Page
  const checkPermissions = () => {
    try {
      const permissions = navigator.mediaDevices.getUserMedia({ audio: true });
      permissions
        .then((stream) => {
          console.log('permission granted');
        })
        .catch((e) => {
          console.log('permission denied');
        });
    } catch (e) {
      console.log(e);
      alert(e);
    }
  };

this is the WebView
<WebView
 source={{ uri:'Http://192.168.1.138:3000/#/permissionTestPage' }}
 onNavigationStateChange={onNavigationStateChange}
 originWhitelist={['*']}
 allowsInlineMediaPlayback={true}
 mediaPlaybackRequiresUserAction={false}
 javaScriptEnabled={true}
 domStorageEnabled={true}
 mediaCapturePermissionGrantType='grantIfSameHostElsePrompt'
/>

this is the error on the mobile device that opened the webview


text:
Q: Complexity of FFT algorithms (Cooley-Tukey, Bluestein, Prime-factor) I need to be able to explain the complexity of three Fast Fourier Transform algorithms: Cooley-Tukey's, Bluestein's and Prime-factor algorithm.
Unfortunatelly, I'm a little lost in the process.

Discrete Fourier Transform general formula
\begin{align}
x &= \{x_0, ... , x_{N-1}\}\\
0 &\leq n \leq N-1 \\
X_n &= \sum^{N-1}_{k=0}x_k \cdot e^{\frac{-i\cdot 2\pi \cdot k \cdot n}{N}}
\end{align}
Here's the complexity pretty clear (at least I think :-) ):

*

*We have a fixed number of multiplications and one division in the sum $\Rightarrow$ complexity of the sum content is $$O(1)$$

*The sum itself contains a loop from 0 to N-1, so the loop runs N-times $\Rightarrow$ the complexity of the whole sum is $$O(N) \cdot O(1) = O(N)$$

*And now, we have this sum for every n $\Rightarrow$ the sum will be "executed" N-times (the size of n is N) $\Rightarrow$ The complexity is $$O(N) \cdot O(N) = O (N^2)$$

Cooley-Tukey's algorithm
The point is in dividing the sum according to the Danielson-Lanczos lemma:
$$
X_n = \sum^{\frac{N}{2}-1}_{k=0} x_{2n} \cdot e^{\frac{-i\cdot 2\pi \cdot k \cdot n}{\frac{N}{2}}} + e^{\frac{-i \cdot 2\pi \cdot n}{N}}\sum^{\frac{N}{2}-1}_{k=0} x_{2n+1} \cdot e^{\frac{-i\cdot 2\pi \cdot k \cdot n}{\frac{N}{2}}}
$$
Every sum can be recursively divided $log_2(N)$ times:
              N
       N/2        N/2
    N/4   N/4  N/4   N/4
             ...
   1         ...        1

*

*Every sum has $O(1)$ complexity as above, so the only thing that matters is the number of iterations: $O(N), O(2\cdot \frac{N}{2}), O(4 \cdot \frac{N}{4})$... So, every step has the complexity $$O(N)$$.

*We have $log_2(N)$ steps, so the complexity of $X_N$ will be
$$O(N \cdot log N)$$

*But still, this is the result just for one $X_n \Rightarrow$ Why is not the complexity multiplied by 'n' again? (as in the step 3 in the general DFT) Or is there a mistake in previous steps?

Bluestein's algorithm
The point is here in rewriting the formula to the "special" shape, where the sum is the convolution of two sequences.

*

*The multiplication of the sum and the exponential before it has a constant complexity $$O(1)$$

*Because the sum is the convolution, we can use the convolution theorem, so we must compute Fourier transforms for both sequences (which can need to be padded with zeros) and multiply them. Multiplication and zero padding are $O(1)$, Fourier transforms can be again $O(N \cdot log N)$ (we'll use Cooley-Tukey for them), so the complexity is
$$
2 \cdot O(N \cdot log N) + O(1) = O(N \cdot log N)
$$

*And again - this is just for one $X_n$ - Why shouldn't I multiply the complexity by O(N) for every 'n'?

Prime-factor algorithm

And here I have simply no idea how should I compute the complexity... I'd say that two nested sums are like two loops, so $O(N^2)$, but it's obviously wrong...

A: The FFT complexity is usually given in terms of number of multiplications ($mul$) and additions ($add$).
General formula
That's correct $$O(N^2 \times mul + N^2 \times add)$$
Cooley-Tukey
First remember the algorithm:
$$X_k = E_k + t_k O_k, k \le \frac N 2$$
$$X_k = E_{k-\frac N 2} - t_{k-\frac N 2}O_{k-\frac N 2}, k > \frac N 2$$
where $E$ is DFT of the even indexed samples, $O$ DFT of the odd indexed samples, and $t$ is the twiddle factor.
We also know that $N = 2^L,L\ge 0$
The number of operations to compute $X$ of size $N=2^L$ if $E,O,t$ are known is:
$$2^{L-1} \times mul + 2^{L} \times add$$
To compute the $E$ and $O$ we need to do the computation twice but of size $2^{L-1}$ and so on. For a $i \le L$ we have to do the computation $2^{L-i}$ times.
Putting this together the total complexity is:
$$\sum_{i=1}^{L}2^{L-i}O(2^{i-1} \times mul + 2^{i} \times add) = \sum_{i=1}^{L}O(2^{L-1} \times mul + 2^{L} \times add) = O(L\cdot 2^{L-1} \times mul + L \cdot 2^{L} \times add) = O(log(N)\frac N 2 \times mul + log(N)N\times add)$$
Bluestein's algorithm
Unfortunately, I'm not familiar with this algorithm
Prime-factor algorithm
$$N = N_1\cdot N_2$$
where $N_1$ and $N_2$ are relatively prime.
Notice that the algorithm is essentially DFT applied twice.  The inner sum is DFT of size $N_1$ that has to be calculated for each $n_2$ (i.e. $N_2$ times).  The outer sum is DFT of size $N_2$ calculated $N_1$ times.  The complexity thus is:
$$O(N_2\cdot O(DFT_{N_1}) + N_1 \cdot O(DFT_{N_2})) = O(N_2\cdot N_1^2\times (mul + add) + N_1 \cdot N_2^2\times (mul + add)) = O(N\cdot (N_1+N_2)\times (mul + add)) $$
For trivial factorization $N_1=N,N_2=1$, the complexity is $O(N^2)$, but for $N_1$ and $N_2$ of similar size, this is close to $O(N \sqrt N)$.


text:
Q: How to effectively query "any" in Django? For example, the query is:
a = request.GET['country']
b = request.GET['name']
c = request.GET['title']
...
result = models.Data.objects.filter('country' = a, 'name' = b, 'title' = c, ...)

What should I do if one of these a b c is "Any"?
I mean if I receive from the frontend, a="Any", how should I effectively free this limit in filter?

A: You can make a function to build a Q object from a parameter:
def _get_filter(name, value):
    return Q() if value == 'Any' else Q((name, value))

and combine them with &:
q = (
    _get_filter('country', request.GET['country']) &
    _get_filter('name', request.GET['name']) &
    _get_filter('title', request.GET['title'])
)

result = models.Data.objects.filter(q)

If possible, I'd also get the source of the request (frontend?) to send a better value to indicate "Any", like an empty string.

A: You don't have to do everything in a single query.  The query is not run until after everything is done.
You can use:
result = models.Data.objects.all()

if a != 'any':
    result = result.filter('country' = a)
if b != 'any':
    result = result.filter('name' = b)
if c != 'any':
    result = result.filter('title' = c)
...

The query won't run against the database until everything is finished, so this really doesn't add any extra queries.


text:
Q: Write listeners for Views getting from OnItemClickListener List View and Custom Adapter in different classes. Custom Adapter have 2 textViews
In OnItemClickListener i created listeners for textviews. TextView listeners some time working some time not working.
listView.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                final int pos, final long id) {

            TextView tv1 = (TextView) view.findViewById(R.id.tv1);

            tv1.setOnClickListener(new OnClickListener() {

                public void onClick(View v) {
                    Toast.makeText(act, "tv1 clicked", 300).show();
                }
            });

            TextView tv2 = (TextView) view.findViewById(R.id.tv2);

            tv2.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View arg0) {
                    Toast.makeText(act, "tv2 clicked", 300).show();
                }
            });

            // listViewListeners(parent, view, pos, id);
        }
    });

A: You are trying to register click event on child views when clicked on parent, so for the first time it won't work as parent will take the touch from user, but based on child element elevation and event listener, it takes clicks from child.
To avoid those use interface
interface ClickListener{
  void tvOneClicked(int position);
  void tvTwoClicked(int position);
}

and while calling your adapter from activity pass above interface as in
adapter = new CustomAdapter(this,some_layout,somedata, new ClickListener(){
     @Override
     public void tvOneClicked(int position){
        //Toast.makeText(act, "tv1 clicked", 300).show();
     }

     @Override
     public void tvOneClicked(int position){
        //Toast.makeText(act, "tv2 clicked", 300).show();
     }});

And in your Adapter, use this to call activity when any of your textview
clicked
private ClickListener clickListener;
 public CustomAdapter(Activity act,int layout,List<> data, ClickListener listener){
    this.clickListener = listener;
 }

 public void getView(...){

   ...
    tv1.setOnClickListener(new OnClickListener() {
                @override
                public void onClick(View v) {
                     clickListener.onOneClicked(position);
                }
            });
            tv2.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View arg0) {
                    clickListener.onTwoClicked(position);
                }
            });
   ...
  }


text:
Q: Viewcontroller does not have a member named Within my code my variables are not being recognized multiple times throughout my code,
let now = NSDate()
let nowData = NSKeyedArchiver.archivedDataWithRootObject(now)
var error : NSError?

This error occurs twice throughout my code, the first occurrence is on the second line, highlighting the word now,  and the error reads  Viewcontroller.type does not have a member named now. Secondly inside of one of my IBActions when I send the time, nowData is highlighted and the error message is "Viewcontroller does not have a member named nowData".  I am unsure as to why these variables are simply not being recognized throughout my code although they are declared right in plain sight.  Perhaps this is an xcode error?
    self.session.sendData(nowData, toPeers:   self.session.connectedPeers, withMode: MCSessionSendDataMode.Unreliable, error: &error)

A: Instance variables with inline initializations can't depend on other instance members. If your instance variables depend on each other at initialization, initialize them in init instead of inline.
class MyClass
{
    let first: FirstType
    let second: SecondType

    init() {
        first = getFirst()
        second = getSecondWithFirst(first)
    }
}


text:
Q: Does spark.jdbc.write use connection pooling? I am using spark to push some hive tables to a RDBMS using
     spark.write.jdbc(...)
I am seeing lots of open /killed connections on the RDBMS side, pretty much one per task. So my question is-does it use connection pooling? If so, how do I configure one? If not, is the only way to do it all manually using
df.rdd.forachPartition { // Open a connection, prepare batch and insert ??? }


text:
Q: Possible eigenvalues of a projection matrix What are the possible eigenvalues of a projection matrix? I know that a projection matrix is any square matrix $A$ such that $A^2 = A$. Thus, we obtain
$$
A^2v = \lambda^2 v \\
Av = \lambda v
$$
for some vector $v \neq 0$. The above imply that $\lambda v = \lambda^2 v$ so $\lambda^2 - \lambda = 0$ so $\lambda = 0, 1$. Does this seem right? For some reason I feel like $-1$ should also be an eigenvalue.


text:
Q: When i'm Starting the Tomcat server in eclipse to deploy the application getting Error, Even I cleaned project many times also When I am trying to start my Apache Tomcat Server, I am getting the below error.
Please find the stacktrace below:
SEVERE: Error configuring application listener of class com.fss.connect.listener.ConnectHttpSessionListener
java.lang.ClassNotFoundException: com.fss.connect.listener.ConnectHttpSessionListener
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1308)
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1142)
    at org.apache.catalina.core.DefaultInstanceManager.loadClass(DefaultInstanceManager.java:518)
    at org.apache.catalina.core.DefaultInstanceManager.loadClassMaybePrivileged(DefaultInstanceManager.java:499)
    at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:118)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4734)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5255)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:147)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1408)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1398)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
    at java.util.concurrent.FutureTask.run(FutureTask.java:166)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
    at java.lang.Thread.run(Thread.java:722)

Feb 07, 2020 1:03:39 PM org.apache.catalina.core.StandardContext listenerStart
SEVERE: Error configuring application listener of class com.fss.connect.listener.LoadLog4jContext
java.lang.ClassNotFoundException: com.fss.connect.listener.LoadLog4jContext
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1308)
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1142)
    at org.apache.catalina.core.DefaultInstanceManager.loadClass(DefaultInstanceManager.java:518)
    at org.apache.catalina.core.DefaultInstanceManager.loadClassMaybePrivileged(DefaultInstanceManager.java:499)
    at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:118)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4734)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5255)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:147)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1408)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1398)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
    at java.util.concurrent.FutureTask.run(FutureTask.java:166)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
    at java.lang.Thread.run(Thread.java:722)

Feb 07, 2020 1:03:39 PM org.apache.catalina.core.StandardContext listenerStart
SEVERE: Error configuring application listener of class com.fss.connect.listener.LoadContext
java.lang.ClassNotFoundException: com.fss.connect.listener.LoadContext
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1308)
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1142)
    at org.apache.catalina.core.DefaultInstanceManager.loadClass(DefaultInstanceManager.java:518)
    at org.apache.catalina.core.DefaultInstanceManager.loadClassMaybePrivileged(DefaultInstanceManager.java:499)
    at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:118)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4734)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5255)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:147)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1408)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1398)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
    at java.util.concurrent.FutureTask.run(FutureTask.java:166)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
    at java.lang.Thread.run(Thread.java:722)

I tried performing "Clean Tomcat Working Directory" but issue still exists. Please show me the right steps to debug this issue.


text:
Q: flask restplus marshall self reference I have model Category, which can have parent Category(self reference), so I can make hierarchy of categories.
from project import db

class Category(db.Model):
    __tablename__ = "categories"
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(64), nullable=False)
    parent_category_id = db.Column(db.Integer, db.ForeignKey('categories.id'), nullable=True)
    child_categories = db.relationship('Category', backref=db.backref('parent', remote_side=[id]), lazy=True)

    def __init__(self, name, parent_category_id=None):
        self.name = name
        self.parent_category_id = parent_category_id

I don't know how to write serializer. Here is my try:
from flask_restplus import fields
from project import api

category = api.model('Category', {
    'id': fields.Integer(),
    'name': fields.String(required=True)
})
category['parent'] = fields.Nested(category)

This throws error:
RecursionError: maximum recursion depth exceeded while calling a Python object

So how do I define it properly?

A: You caused cycle import. It's because that category and category["parent"] used the same model name.
Try this:
from flask_restplus import fields
from project import api

category = api.model('Category', {
    'id': fields.Integer(),
    'name': fields.String(required=True)
})
category['parent'] = fields.Nested(api.model("ParentModel", {}))


text:
Q: How to update height prop with useRef in React? I need to dynamically define the size of HTML element and set its height to component. I tried to do this with useRef but it doesn't work as expected because of state which contains the previous value (not the current one). Could someone help me with this?
And here's the link:  CodeSandBox https://codesandbox.io/s/happy-water-fzqk8?file=/src/App.js
The below code works fine but there's hardcored variable HEIGHT which defines the height of a tab. My task is to make the height dynamic
import { useState } from 'react';

const HEIGHT = {
  0: 200,
  1: 400,
  2: 800,
}

function App() {
  const [tab, setTab] = useState(0);

  const switchTab = (id) => {
    setTab(id);
  };

  return (

        {tab === 0 && (

Tab 1

            <input />
            <button onClick={() => switchTab(1)}>Go to tab 2</button>

Some text here

        )}
        {tab === 1 && (

Tab 2

            <input />
            <button onClick={() => switchTab(0)}>Go to tab 1</button>
            <button onClick={() => switchTab(2)}>Go to tab 3</button>

              Some more text here. Some more text here. Some more text here. Some more text here.
              Some more text here. Some more text here. Some more text here

        )}

        {tab === 2 && (

Tab 3

            <input />
            <button onClick={() => switchTab(0)}>Go to tab 1</button>
            <button onClick={() => switchTab(1)}>Go to tab 2</button>

        )}

  );
}

What I tried:

*

*Added useRef and state which holds the element height

    const elRef = useRef(0);
    const [height, setHeight] = useState(elRef.current.offsetHeight);

*Added function which calculates the size of an element and then sets it to state variable

      const resizeHeight = useCallback(() => {
        const size = elRef.current.offsetHeight;
        setHeight(size)
      }, [elRef]);

*Added state Height to styles this way

It doesn't work((
Here's the link...with the state height - undefined
https://codesandbox.io/s/objective-brown-zq7ih?file=/src/App.js

A: You can easily update your elRef reference in the switchTab handler without using useEffect and any useCallback hooks:
const elRef = useRef(0);

const SwitchTab = (id) => {
  setTab(id);
  setHeight(elRef.current.offsetHeight)
};

Now pass the elRef to the ref property of your target div:
  return (

    // ------------------------> added here
        {tab === 0 && (

Tab 1

            <input />
            <button onClick={() => switchTab(1)}>Go to tab 2</button>

Some text here

        )}
        {tab === 1 && (

Tab 2

            <input />
            <button onClick={() => switchTab(0)}>Go to tab 1</button>
            <button onClick={() => switchTab(2)}>Go to tab 3</button>

              Some more text here. Some more text here. Some more text here. Some more text here.
              Some more text here. Some more text here. Some more text here

        )}

        {tab === 2 && (

Tab 3

            <input />
            <button onClick={() => switchTab(0)}>Go to tab 1</button>
            <button onClick={() => switchTab(1)}>Go to tab 2</button>

        )}

  );


text:
Q: Why does my C# function returning the position of a letter in the alphabet work? I have a function that returns the position of a letter in the alphabet. How does it work?
This is how my C# looks like:
    private int CalculateLetterPosition(char cCharacter)
    {
        int iReturn = 0;
        int iCharacterValue = (int)cCharacter;
        if (iCharacterValue >= 97 && iCharacterValue <= 122)
        {
            iReturn = iCharacterValue - 96;
        }
        return iReturn;
    }

A: So all letters(or chars) have numeric representations. Basically,

*

*Your code casts the text char value to its ASCII numeric value.

*Subtracts 96 from the numeric value since 97 is the ASCII code for 'a'.

*Final result will be the position in the alphabet.

For example:
You provide b to your function.

*

*b stands for 98 in ASCII table.

*98 - 96 = 2

A: in the ASCII code table the small "a" starts at position 97 in a row.
Therefore you only have to subtract 96 from its ASCII postion. Your code only works for lowercase letters, and only for letters within the ASCII range.


text:
Q: Pandas skip missing values in map function Any help on how can I skip missing values in my world field. I thought na_action='ignore' would help, but it doesn't for my case .
df['world'] = df['world'].map(lambda x: x.rstrip('L.locoMoco'),na_action='ignore')

Thanks

A: If world is an object column, call str.rstrip directly.
df['world'] = df['world'].str.rstrip('L.locoMoco')

If the column is one of objects, NaNs are preserved. However, if you have numeric values, they're are coerced to NaNs, so if this is not intended behaviour, I'd suggest, either

*

*Coercing those values to string (to preserve them), or

*Using slower alternatives like a for loop or apply.


text:
Q: Android - Save image to SD and then Load Image I've designed quickly a piece of code which loads from an specified URL and then saves it to the SD card, however it is not saving to the SD.
URL myFileUrl = new URL( Image_HTML);
String filepath = Environment.getExternalStorageDirectory().getAbsolutePath();
try {
    HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
    conn.setDoInput(true);
    conn.connect();
    InputStream is = conn.getInputStream();
    bm = BitmapFactory.decodeStream(is);
    FileOutputStream fos = new FileOutputStream(filepath+image_name);
    bm.compress(CompressFormat.PNG, 100, fos);
    fos.flush();
    fos.close();

    bm = BitmapFactory.decodeFile(filepath+image_name);
    image_loader_view.setImageBitmap(bm);

} catch (FileNotFoundException e) {

    e.printStackTrace();
    Log.i("Hub", "FileNotFoundException: "+ e.toString());

} catch (IOException e) {

    e.printStackTrace();
    Log.i("Hub", "IOException: "+ e.toString());
}

I have tried to make this code as lightweight as possible, and I have also activated the EXTERNAL.STORAGE.WRITE in the android manifest.

A: Couple things.
When you use a FileOutputStream you have to make sure the directory you are trying to write to is created before you try to write a file to it.  If not you have to create it.  This can be done via mkdirs() method of the File class.
Next I'm not sure the call to getAbsolutePath is required, due to the type of file system Android uses.  I've never had to use it to save to SD before.
I'd try these and see if one of them will solve it for you.


text:
Q: How to get piv card authentication and certificate information I searched around there is a IIS related method (http://technet.microsoft.com/en-us/library/cc732116.aspx) but I can't get it to work.
I need to get the piv card authenticated from a web application then return certificate to the web application. How can I do that in C#.net
UPDATE: just in case, someone else is interested. I found a solution (not perfect) but working which I put in this thread Smart card authentication using a client certificate

A: I found a solution (not perfect but working) which I put in this thread Smart card authentication using a client certificate


text:
Q: Reply after a given delay I would like to implement an simple timer within a communication.
My scenario is a small math trainer where you train 5 minutes, after the 5 minutes of normal interaction I would like to inform the user that the time is now up. I don't want to wait until the user has finished his next input/answer (optional just if there is currently no input).
Is there any way to "push" an answer time based?

A: The Conversation API does not support a push model. When you get the users response, you can check the timer and respond appropriately.

A: Sadly it looks like they are not interested in adding any sort of delay features:
Dialogflow (API.AI) Forums :- Adding a delay to responses, so it feels more real
But this is one reason why building a server side solution in between your deployment integration (ex. Facebook messenger) and API.ai is so useful- it let's you customize fulfillments, including sending fulfillments triggered by your own custom logic built on top of API.ai solutions.
So in the case of FB messenger as a simple example, you could do something like below, and just build any logic you want to call sendTextMessage:

function sendTextMessage(recipientId, text) {
    sendTypingOff(recipientId)
    var messageData = {
        recipient: {
            id: recipientId
        },
        message: {
            text: text
        }
    }
    callSendAPI(messageData);
}

//Calls FB messenger API. If successful returns a message ID in response
function callSendAPI(messageData) {
    request({
        uri: 'https://graph.facebook.com/v2.6/me/messages',
        qs: {
            access_token: config.FB_PAGE_TOKEN
        },
        method: 'POST',
        json: messageData

    }, function (error, response, body) {
        if (!error && response.statusCode == 200) {
            var recipientId = body.recipient_id;
            var messageId = body.message_id;

            if (messageId) {
                console.log("Successfully sent message with id %s to recipient %s",
                    messageId, recipientId);
            } else {
                console.log("Successfully called Send API for recipient %s",
                    recipientId);
            }
        } else {
            console.error("Failed calling Send API", response.statusCode, response.statusMessage, body.error);
        }
    });
}

A: This is probably irrelevant for you by now but I'm writing an answer for people who might visit here.
You can implement this with events in Dialogflow (formerly API.ai). See here for documentation.
You define an intent based on an event called, say, time-is-up, and have a timer on your end that triggers this event after five minutes.


text:
Q: How to compress JS data in rails I have a Rails + React app that is ~3mb (too big!)
About 2mb of that is a single instance variable, @songs, that's passed to the react component like this:
<%= react_component('SongApp', songData: @songs, songId: @song_id, allBooks: Book.reactify) %>

By passing the data in like that, I can immediately use it as this.props.songData in the component.
I want to compress this data (which is a JSON string)—so the client device doesn't need to download so much—and decompress within the React component on the client device. How can I do this?

A: Use Rack::Deflater
Rack::Deflater middleware compresses responses at runtime using deflate or trusty ol' gzip. Inserted correctly into your Rack app, it can drastically reduce the size of your HTML / JSON controller responses
Add it to config/application.rb thusly
module YourApp
 class Application < Rails::Application
   config.middleware.use Rack::Deflater
 end
end

Answer Number 2
For the response to be in gzip format we don't have to change the render method call.
If the request has the header Accept-Encoding: gzip, Rails will automatically compress the JSON response using gzip.
If you don't want the user to send a request with preset header., you can add the header to the request manually in the controller before rendering the response:
request.env['HTTP_ACCEPT_ENCODING'] = 'gzip'
render :json => response.to_json()enter code here

check this gist


text:
Q: How to work with duplicates within a list where you have to replace elements based on decisions? We get 8 numbers and have to input them into a list.
we then have run the element through decisions and replace them based on the outcome. the decisions are:

*

*If the value of the element is less than the array index, the element must be replaced with the index plus ten.

*If the value of the element is equal to the index, the element must be doubled.

*If the value of the element is greater than the index, the element must be replaced by the index squared.

    array = []
    array1 = []
    for i in range(8):
        num = int(input())
        array.append(num)

    for j in array:
        x = 0
        r = array.index(j)
        if j < r:
            x += r + 10
            array1.append(x)
        elif j == r:
            x += j + j
            array1.append(x)
        elif j > r:
            x += r * r
            array1.append(x)
        else:
            pass

    print(array)
    print(array1)

input:
0
3
4
6
5
4
2
3

Expected Output:
[0, 3, 4, 6, 5, 4, 2, 3]
[0, 1, 4, 9, 16, 15, 16, 17]

My Output:
[0, 3, 4, 6, 5, 4, 2, 3]
[0, 1, 4, 9, 16, 4, 16, 1]

A: The problem is that you are finding the index using index method over the list, it returns the first occurrence index.
Use enumerate method to get index while iterating.
array = []
array1 = []
for i in range(8):
    num = int(input())
    array.append(num)

for r, j in enumerate(array):
    x = 0
    if j < r:
        x += r + 10
        array1.append(x)
    elif j == r:
        x += j + j
        array1.append(x)
    elif j > r:
        x += r * r
        array1.append(x)
    else:
        pass

print(array)
print(array1)


text:
Q: Execute function only once every pc session (pc start) I have a driver that I haven't made and I manual map it. Say the function is ManualMap(); as an example.
That function gets called everytime I run my program. It's basically in main();
Now what I want to do is to make that function only be called once every session. So if PC was restarted, that function will be called, if u run the program again during the same pc session, it won't run the function.
Now if you restart PC, the function will be called when you run the program.
bool main(){
    if (has_run_before_during_this_session()){
        return;
    }
    ManualMap();
    Save_Something_To_Run_Check_Next_Time();
}

A: You will have to use canary. The simplest way to do this is to create a file on disk each time you run ManualMap().
Then you need to make sure that when your computer is started that file gets deleted. This will be OS-dependent. You create a script that will delete the file and then make sure it runs on startup (Windows, Linux).


text:
Q: How to periodically check isCancelled() inside doInBackground() of AsyncTask and return if needed ? I saw and read many post and the doc. I understand one can insert a few isCancelled(); in between some code blocks. What about a bigger workload that cannot be split into parts like Url fetching ?
I tried this dummy project to try to find a solution : while the asynctask is working, I want to check periodically the isCancelled() and skip all what is left in doInBackground() .
I tried this :
@Override
protected Void doInBackground(Void... params) {

    strUrlBase = "http://www.legorafi.fr/2012/12/20/portrait-benoit-le-fameux-ami-noir-de-tous-les-racistes/";
    if (fgDebugLocal){Log.i(tagLocal, tagLocal + "strUrlBase = " + strUrlBase);};
    timer = new Timer();
    timer.scheduleAtFixedRate(new TimerTask() {

        @Override
        public void run() {
            if (isCancelled()) {
                if (fgDebugLocal){Log.e(tagLocal, tagLocal + "timer asyncTask : isCancelled true" );};
                timer.cancel();
                return;
            } else {
                if (fgDebugLocal){Log.e(tagLocal, tagLocal + "timer asyncTask : isCancelled FALSE" );};
            }
        }
    },0, 100);

    for (int i = 0; i<15; i++ ) {
        HttpURLConnection urlConnection = null;
        try {
            url = new URL(strUrlBase);
            https = (HttpURLConnection) url.openConnection();
            https.setDoOutput(true);

            urlConnection = https;

            if (urlConnection.getInputStream() != null){ // Crash there :(
                inputStream = new BufferedInputStream(urlConnection.getInputStream());
                reader = new BufferedReader(new InputStreamReader(inputStream));

                ByteArrayBuffer baf = new ByteArrayBuffer(50);
                int current = 0;
                while((current=reader.read())!=-1){
                    baf.append((byte)current);
                }
                strJson = new String (baf.toByteArray());
                if (fgDebugLocal){Log.i(tagLocal, tagLocal + "check le gorafi number "+i+" - " + strJson.substring(0, 100));};

                https.disconnect();
            } else {
                if (fgDebugLocal){Log.i(tagLocal, "urlConnection.getInputStream() != null");};
                fgErrorConn = true;
                varResultRequest = -1;
            }

        } catch (IOException e) {
            if (fgDebugLocal){Log.i(tagLocal, "IOException = "+e.getMessage());};
            fgErrorPb = true;
            varResultRequest =0;
            //publishProgress(100);
        }
    }
    varResultRequest = 1;
    return null;
}

The timertask correctly detect the value of isCancelled() but I can't find a way to act after that. Any idea ? or any other way ?
Ty

A: Cancel method is public, so you can override it. Inside your custom implementation you can first: call base version, then abort any pending http connection. You must be carefull because cancel will be called possibly from GUI thread, but I suppose it should work.


text:
Q: Spring-Webapps: shared resources and separated development/maven modules? I have two WARs, each one using Hibernate-Search+Lucene. As far as I understand it, that setup would produce two separate Hibernate und Lucene instances if loaded separately into tomcat etc.
The two WARs are generated by two separate maven modules. I want to keep that separation.
How do I merge the separate instances in production?
I thought about the maven-shade-plugin to merge the WARs. Is there a better of doing that, ie. a more automatic/more standard way?

A: Look at Maven WAR Overlays. What is the reason for defining two separate WAR files?
General idea is to have Base WAR (shared resources?) and two customized WARs (diffs) for diffrent environment with Maven Overlays.

A: I have personally tried shade, overlay and cargo uberwar strategies for merging two wars. my personal favourite for this requirement is Cargo uberwar. It not only allows basic overlay functionalities but also enhances by additional features which you may like to use. Control over merging strategies of files from different wars is one such example. You may like to merge at least web.xml. You can refer to more examples at http://cargo.codehaus.org/Merging+WAR+files
It may seem additional work setting it up but the configuration options are worth it.


text:
Q: How to remove hover effect on selected row? I changed the .k-state-selected to a different color, works fine. However when I hover over the selected row the hover color is blue.
I have tried
.k-grid tr:hover{
      background:transparent;
    }
and that works fine for rows that are not selected, but not for the selected row.
Essentially I need to remove the hover effect on a selected row and can't figure it out

$("#grid").kendoGrid({
  columns: [{
      field: "name"
    },
    {
      field: "age"
    }
  ],
  dataSource: [{
      name: "Jane Doe",
      age: 30
    },
    {
      name: "John Doe",
      age: 33
    }
  ],
  selectable: "row"
});
.k-grid .k-state-selected {
  background: #ec971f;
}
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2019.3.1023/styles/kendo.common.min.css" />
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2019.3.1023/styles/kendo.rtl.min.css" />
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2019.3.1023/styles/kendo.silver.min.css" />
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2019.3.1023/styles/kendo.mobile.all.min.css" />

A: Try it:

$("#grid").kendoGrid({
  columns: [{
      field: "name"
    },
    {
      field: "age"
    }
  ],
  dataSource: [{
      name: "Jane Doe",
      age: 30
    },
    {
      name: "John Doe",
      age: 33
    }
  ],
  selectable: "row"
});
.k-grid .k-state-selected {
  background: #ec971f;
}

.k-grid .k-state-selected:hover {
  background:  #ec971f!important;
  color:#000;
}
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2019.3.1023/styles/kendo.common.min.css" />
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2019.3.1023/styles/kendo.rtl.min.css" />
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2019.3.1023/styles/kendo.silver.min.css" />
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2019.3.1023/styles/kendo.mobile.all.min.css" />

A: .k-grid tr:hover doesn't work because of the rules of CSS specificity. In other words, .k-grid .k-state-selected is more specific than .k-grid tr:hover.
.k-grid .k-state-selected:hover should work for you.
Example


text:
Q: Voice and Video call integration of zegocloud with rails I am new to rails and i get a chance to implement voice and video call features to the app but i have to do it with the zegocloud.
i did a lot search for implementation of voice and video call but most of the articles is on twilio.
what should i do or which gem i should pic to integrate it.


text:
Q: Google get email proper scopes A lot of the documentation on google talks about the email scope to replace the https://www.googleapis.com/auth/userinfo.email, pared with the endpoint https://www.googleapis.com/userinfo/v2/me. Documentation found here https://developers.google.com/+/api/oauth#email.
Yet there is more documentation that states even that is being replaced in favor of the plus api and endpoint and the people.get endpoint. Documentation found here https://developers.google.com/+/api/auth-migration#email.
I have an application that needs to request the user email for both authentication and to verify they have installed our app.. A bonus is when I try to add the email scope to the developer console, or use it in my app, it tells me that email is not a valid scope.
My question is what are the proper scopes that need be applied in my app and in the google developer console? Need to be sure of this since the Google Apps Marketplace V2 has rules about prompting users.

A: You need to use the "email+profile" scope. That's the only way you will comply with the marketplace requirements to hide the user consent window.
Don't worry about the API console saying this is not a valid scope, it works when you provide it to the OAuth endpoint.
Here's an explanatory blog post with a sample in Java and all the required configuration steps.


text:
Q: WAN Link Speed and TCP Window Sizes on Windows 2003 / XP I currently have a data center connected to two remote locations via MPLS - 2M and 6M respectively. The 2M connection (to Asia from the US) has about 300ms of latency and when transferring between clients (XP, 2003 Server) and server (2003 Server) a single flow won't exceed .65 Mbps.
I can get a very nice connection via FTP that fills up pretty much the entire 2 Mbps with a single threaded FTP connection but CIFS or whatever else TCP based seems to be gimped horribly.
It's been suggested that this is a TCP window size issue but when referring to this to change the window size to 64K (or larger, I've tried a range of window sizes) it doesn't change my transfer speed at all. I've peeked at Network Monitor to see what window sizes I'm negotiating and it's reporting that if I set it to 64K it's really negotiating 64K and so on.
I don't really have much experience with any of this insanity so was hoping someone might have some insight into what I'm missing or some things to consider.

A: IMHO, low level hacks like changing the window size aren't the first place to start. 300ms latency is horrible. Have you looked at packet loss? FTP has less overhead than Windows file copying so it's generally going to run faster.

A: We have the same problem as you do, the only way to solve the problem of accessing CIFS via the MPLS link is to speed it up with CIFS accelerator like Riverbed devices or F5 Networks devices. It will be worst if you are using windows file sharing, and without a local domain controller due to the chatty protocol from MS. With exception of Vista and above due to SMBv2.
We get around 250ms to US DC from APAC and 220ms to our European DC.


text:
Q: FAILURE: Build failed with an exception. Android Java when I try to run the application, I encounter a long error as follows. How can I solve this?
Can you help me?
FAILURE: Build failed with an exception.
Executing tasks: [:app:assembleDebug] in project /Users/Developer/projectname
FAILURE: Build failed with an exception.

*

*What went wrong:
Execution failed for task ':app:checkDebugDuplicateClasses'.

A failure occurred while executing com.android.build.gradle.internal.tasks.CheckDuplicatesRunnable
Duplicate class androidx.collection.LruCache found in modules collection-1.1.0 (androidx.collection:collection:1.1.0) and jetified-support-v4-r7 (com.google.android:support-v4:r7)
Duplicate class androidx.core.accessibilityservice.AccessibilityServiceInfoCompat found in modules core-1.3.2-runtime (androidx.core:core:1.3.2) and jetified-support-v4-r7 (com.google.android:support-v4:r7)
Duplicate class androidx.core.app.ActivityCompat found in modules core-1.3.2-runtime (androidx.core:core:1.3.2) and jetified-support-v4-r7 (com.google.android:support-v4:r7)
Duplicate class androidx.core.app.NavUtils found in modules core-1.3.2-runtime (androidx.core:core:1.3.2) and jetified-support-v4-r7 (com.google.android:support-v4:r7)
Duplicate class androidx.core.app.NotificationCompat found in modules core-1.3.2-runtime (androidx.core:core:1.3.2) and jetified-support-v4-r7 (com.google.android:support-v4:r7)
Duplicate class androidx.core.app.NotificationCompat$Builder found in modules core-1.3.2-runtime (androidx.core:core:1.3.2) and jetified-support-v4-r7 (com.google.android:support-v4:r7)
Duplicate class androidx.core.app.ServiceCompat found in modules core-1.3.2-runtime (androidx.core:core:1.3.2) and jetified-support-v4-r7 (com.google.android:support-v4:r7)
Duplicate class androidx.core.app.ShareCompat found in modules core-1.3.2-runtime (androidx.core:core:1.3.2) and jetified-support-v4-r7 (com.google.android:support-v4:r7)
Duplicate class androidx.core.app.ShareCompat$IntentBuilder found in modules core-1.3.2-runtime (androidx.core:core:1.3.2) and jetified-support-v4-r7 (com.google.android:support-v4:r7)
Duplicate class androidx.core.app.ShareCompat$IntentReader found in modules core-1.3.2-runtime (androidx.core:core:1.3.2) and jetified-support-v4-r7 (com.google.android:support-v4:r7)
Duplicate class androidx.core.app.TaskStackBuilder found in modules core-1.3.2-runtime (androidx.core:core:1.3.2) and jetified-support-v4-r7 (com.google.android:support-v4:r7)
Duplicate class androidx.core.content.IntentCompat found in modules core-1.3.2-runtime (androidx.core:core:1.3.2) and jetified-support-v4-r7 (com.google.android:support-v4:r7)
Duplicate class androidx.core.content.pm.ActivityInfoCompat found in modules core-1.3.2-runtime (androidx.core:core:1.3.2) and jetified-support-v4-r7 (com.google.android:support-v4:r7)
Duplicate class androidx.core.database.DatabaseUtilsCompat found in modules core-1.3.2-runtime (androidx.core:core:1.3.2) and jetified-support-v4-r7 (com.google.android:support-v4:r7)
Duplicate class androidx.core.os.ParcelableCompat found in modules core-1.3.2-runtime (androidx.core:core:1.3.2) and jetified-support-v4-r7 (com.google.android:support-v4:r7)
Duplicate class androidx.core.os.ParcelableCompatCreatorCallbacks found in modules core-1.3.2-runtime (androidx.core:core:1.3.2) and jetified-support-v4-r7 (com.google.android:support-v4:r7)
Duplicate class androidx.core.util.DebugUtils found in modules core-1.3.2-runtime (androidx.core:core:1.3.2) and jetified-support-v4-r7 (com.google.android:support-v4:r7)
Duplicate class androidx.core.util.LogWriter found in modules core-1.3.2-runtime (androidx.core:core:1.3.2) and jetified-support-v4-r7 (com.google.android:support-v4:r7)
Duplicate class androidx.core.util.TimeUtils found in modules core-1.3.2-runtime (androidx.core:core:1.3.2) and jetified-support-v4-r7 (com.google.android:support-v4:r7)
Duplicate class androidx.core.view.AccessibilityDelegateCompat found in modules core-1.3.2-runtime (androidx.core:core:1.3.2) and jetified-support-v4-r7 (com.google.android:support-v4:r7)
Duplicate class androidx.core.view.MenuCompat found in modules core-1.3.2-runtime (androidx.core:core:1.3.2) and jetified-support-v4-r7 (com.google.android:support-v4:r7)
Duplicate class androidx.core.view.MenuItemCompat found in modules core-1.3.2-runtime (androidx.core:core:1.3.2) and jetified-support-v4-r7 (com.google.android:support-v4:r7)
Duplicate class androidx.core.view.MotionEventCompat found in modules core-1.3.2-runtime (androidx.core:core:1.3.2) and jetified-support-v4-r7 (com.google.android:support-v4:r7)
Duplicate class androidx.core.view.VelocityTrackerCompat found in modules core-1.3.2-runtime (androidx.core:core:1.3.2) and jetified-support-v4-r7 (com.google.android:support-v4:r7)
Duplicate class androidx.core.view.ViewCompat found in modules core-1.3.2-runtime (androidx.core:core:1.3.2) and jetified-support-v4-r7 (com.google.android:support-v4:r7)
Duplicate class androidx.core.view.ViewConfigurationCompat found in modules core-1.3.2-runtime (androidx.core:core:1.3.2) and jetified-support-v4-r7 (com.google.android:support-v4:r7)
Duplicate class androidx.core.view.ViewGroupCompat found in modules core-1.3.2-runtime (androidx.core:core:1.3.2) and jetified-support-v4-r7 (com.google.android:support-v4:r7)
Duplicate class androidx.core.view.accessibility.AccessibilityEventCompat found in modules core-1.3.2-runtime (androidx.core:core:1.3.2) and jetified-support-v4-r7 (com.google.android:support-v4:r7)
Duplicate class androidx.core.view.accessibility.AccessibilityManagerCompat found in modules core-1.3.2-runtime (androidx.core:core:1.3.2) and jetified-support-v4-r7 (com.google.android:support-v4:r7)
Duplicate class androidx.core.view.accessibility.AccessibilityManagerCompat$AccessibilityStateChangeListenerCompat found in modules core-1.3.2-runtime (androidx.core:core:1.3.2) and jetified-support-v4-r7 (com.google.android:support-v4:r7)
Duplicate class androidx.core.view.accessibility.AccessibilityNodeInfoCompat found in modules core-1.3.2-runtime (androidx.core:core:1.3.2) and jetified-support-v4-r7 (com.google.android:support-v4:r7)
Duplicate class androidx.core.view.accessibility.AccessibilityRecordCompat found in modules core-1.3.2-runtime (androidx.core:core:1.3.2) and jetified-support-v4-r7 (com.google.android:support-v4:r7)
Duplicate class androidx.core.widget.EdgeEffectCompat found in modules core-1.3.2-runtime (androidx.core:core:1.3.2) and jetified-support-v4-r7 (com.google.android:support-v4:r7)
Duplicate class androidx.cursoradapter.widget.CursorAdapter found in modules cursoradapter-1.0.0-runtime (androidx.cursoradapter:cursoradapter:1.0.0) and jetified-support-v4-r7 (com.google.android:support-v4:r7)
Duplicate class androidx.cursoradapter.widget.CursorAdapter$ChangeObserver found in modules cursoradapter-1.0.0-runtime (androidx.cursoradapter:cursoradapter:1.0.0) and jetified-support-v4-r7 (com.google.android:support-v4:r7)
Duplicate class androidx.cursoradapter.widget.CursorAdapter$MyDataSetObserver found in modules cursoradapter-1.0.0-runtime (androidx.cursoradapter:cursoradapter:1.0.0) and jetified-support-v4-r7 (com.google.android:support-v4:r7)
Duplicate class androidx.cursoradapter.widget.CursorFilter found in modules cursoradapter-1.0.0-runtime (androidx.cursoradapter:cursoradapter:1.0.0) and jetified-support-v4-r7 (com.google.android:support-v4:r7)
Duplicate class androidx.cursoradapter.widget.CursorFilter$CursorFilterClient found in modules cursoradapter-1.0.0-runtime (androidx.cursoradapter:cursoradapter:1.0.0) and jetified-support-v4-r7 (com.google.android:support-v4:r7)
Duplicate class androidx.cursoradapter.widget.ResourceCursorAdapter found in modules cursoradapter-1.0.0-runtime (androidx.cursoradapter:cursoradapter:1.0.0) and jetified-support-v4-r7 (com.google.android:support-v4:r7)
Duplicate class androidx.cursoradapter.widget.SimpleCursorAdapter found in modules cursoradapter-1.0.0-runtime (androidx.cursoradapter:cursoradapter:1.0.0) and jetified-support-v4-r7 (com.google.android:support-v4:r7)
Duplicate class androidx.cursoradapter.widget.SimpleCursorAdapter$CursorToStringConverter found in modules cursoradapter-1.0.0-runtime (androidx.cursoradapter:cursoradapter:1.0.0) and jetified-support-v4-r7 (com.google.android:support-v4:r7)
Duplicate class androidx.cursoradapter.widget.SimpleCursorAdapter$ViewBinder found in modules cursoradapter-1.0.0-runtime (androidx.cursoradapter:cursoradapter:1.0.0) and jetified-support-v4-r7 (com.google.android:support-v4:r7)
Duplicate class androidx.fragment.app.BackStackRecord found in modules fragment-1.1.0-runtime (androidx.fragment:fragment:1.1.0) and jetified-support-v4-r7 (com.google.android:support-v4:r7)
Duplicate class androidx.fragment.app.BackStackState found in modules fragment-1.1.0-runtime (androidx.fragment:fragment:1.1.0) and jetified-support-v4-r7 (com.google.android:support-v4:r7)
Duplicate class androidx.fragment.app.BackStackState$1 found in modules fragment-1.1.0-runtime (androidx.fragment:fragment:1.1.0) and jetified-support-v4-r7 (com.google.android:support-v4:r7)
Duplicate class androidx.fragment.app.DialogFragment found in modules fragment-1.1.0-runtime (androidx.fragment:fragment:1.1.0) and jetified-support-v4-r7 (com.google.android:support-v4:r7)
Duplicate class androidx.fragment.app.Fragment found in modules fragment-1.1.0-runtime (androidx.fragment:fragment:1.1.0) and jetified-support-v4-r7 (com.google.android:support-v4:r7)
Duplicate class androidx.fragment.app.Fragment$InstantiationException found in modules fragment-1.1.0-runtime (androidx.fragment:fragment:1.1.0) and jetified-support-v4-r7 (com.google.android:support-v4:r7)
Duplicate class androidx.fragment.app.Fragment$SavedState found in modules fragment-1.1.0-runtime (androidx.fragment:fragment:1.1.0) and jetified-support-v4-r7 (com.google.android:support-v4:r7)
Duplicate class androidx.fragment.app.Fragment$SavedState$1 found in modules fragment-1.1.0-runtime (androidx.fragment:fragment:1.1.0) and jetified-support-v4-r7 (com.google.android:support-v4:r7)
Duplicate class androidx.fragment.app.FragmentActivity found in modules fragment-1.1.0-runtime (androidx.fragment:fragment:1.1.0) and jetified-support-v4-r7 (com.google.android:support-v4:r7)
Duplicate class androidx.fragment.app.FragmentManager found in modules fragment-1.1.0-runtime (androidx.fragment:fragment:1.1.0) and jetified-support-v4-r7 (com.google.android:support-v4:r7)
Duplicate class androidx.fragment.app.FragmentManager$BackStackEntry found in modules fragment-1.1.0-runtime (androidx.fragment:fragment:1.1.0) and jetified-support-v4-r7 (com.google.android:support-v4:r7)
Duplicate class androidx.fragment.app.FragmentManager$OnBackStackChangedListener found in modules fragment-1.1.0-runtime (androidx.fragment:fragment:1.1.0) and jetified-support-v4-r7 (com.google.android:support-v4:r7)
Duplicate class androidx.fragment.app.FragmentManagerImpl found in modules fragment-1.1.0-runtime (androidx.fragment:fragment:1.1.0) and jetified-support-v4-r7 (com.google.android:support-v4:r7)
Duplicate class androidx.fragment.app.FragmentManagerImpl$1 found in modules fragment-1.1.0-runtime (androidx.fragment:fragment:1.1.0) and jetified-support-v4-r7 (com.google.android:support-v4:r7)
Duplicate class androidx.fragment.app.FragmentManagerImpl$2 found in modules fragment-1.1.0-runtime (androidx.fragment:fragment:1.1.0) and jetified-support-v4-r7 (com.google.android:support-v4:r7)
Duplicate class androidx.fragment.app.FragmentManagerImpl$3 found in modules fragment-1.1.0-runtime (androidx.fragment:fragment:1.1.0) and jetified-support-v4-r7 (com.google.android:support-v4:r7)
Duplicate class androidx.fragment.app.FragmentManagerImpl$4 found in modules fragment-1.1.0-runtime (androidx.fragment:fragment:1.1.0) and jetified-support-v4-r7 (com.google.android:support-v4:r7)
Duplicate class androidx.fragment.app.FragmentManagerImpl$5 found in modules fragment-1.1.0-runtime (androidx.fragment:fragment:1.1.0) and jetified-support-v4-r7 (com.google.android:support-v4:r7)
Duplicate class androidx.fragment.app.FragmentManagerState found in modules fragment-1.1.0-runtime (androidx.fragment:fragment:1.1.0) and jetified-support-v4-r7 (com.google.android:support-v4:r7)
Duplicate class androidx.fragment.app.FragmentManagerState$1 found in modules fragment-1.1.0-runtime (androidx.fragment:fragment:1.1.0) and jetified-support-v4-r7 (com.google.android:support-v4:r7)
Duplicate class androidx.fragment.app.FragmentPagerAdapter found in modules fragment-1.1.0-runtime (androidx.fragment:fragment:1.1.0) and jetified-support-v4-r7 (com.google.android:support-v4:r7)
Duplicate class androidx.fragment.app.FragmentState found in modules fragment-1.1.0-runtime (androidx.fragment:fragment:1.1.0) and jetified-support-v4-r7 (com.google.android:support-v4:r7)
Duplicate class androidx.fragment.app.FragmentState$1 found in modules fragment-1.1.0-runtime (androidx.fragment:fragment:1.1.0) and jetified-support-v4-r7 (com.google.android:support-v4:r7)
Duplicate class androidx.fragment.app.FragmentStatePagerAdapter found in modules fragment-1.1.0-runtime (androidx.fragment:fragment:1.1.0) and jetified-support-v4-r7 (com.google.android:support-v4:r7)
Duplicate class androidx.fragment.app.FragmentTransaction found in modules fragment-1.1.0-runtime (androidx.fragment:fragment:1.1.0) and jetified-support-v4-r7 (com.google.android:support-v4:r7)
Duplicate class androidx.fragment.app.ListFragment found in modules fragment-1.1.0-runtime (androidx.fragment:fragment:1.1.0) and jetified-support-v4-r7 (com.google.android:support-v4:r7)
Duplicate class androidx.fragment.app.ListFragment$1 found in modules fragment-1.1.0-runtime (androidx.fragment:fragment:1.1.0) and jetified-support-v4-r7 (com.google.android:support-v4:r7)
Duplicate class androidx.fragment.app.ListFragment$2 found in modules fragment-1.1.0-runtime (androidx.fragment:fragment:1.1.0) and jetified-support-v4-r7 (com.google.android:support-v4:r7)
Duplicate class androidx.fragment.app.SuperNotCalledException found in modules fragment-1.1.0-runtime (androidx.fragment:fragment:1.1.0) and jetified-support-v4-r7 (com.google.android:support-v4:r7)
Duplicate class androidx.loader.app.LoaderManager found in modules jetified-support-v4-r7 (com.google.android:support-v4:r7) and loader-1.0.0-runtime (androidx.loader:loader:1.0.0)
Duplicate class androidx.loader.app.LoaderManager$LoaderCallbacks found in modules jetified-support-v4-r7 (com.google.android:support-v4:r7) and loader-1.0.0-runtime (androidx.loader:loader:1.0.0)
Duplicate class androidx.loader.app.LoaderManagerImpl found in modules jetified-support-v4-r7 (com.google.android:support-v4:r7) and loader-1.0.0-runtime (androidx.loader:loader:1.0.0)
Duplicate class androidx.loader.app.LoaderManagerImpl$LoaderInfo found in modules jetified-support-v4-r7 (com.google.android:support-v4:r7) and loader-1.0.0-runtime (androidx.loader:loader:1.0.0)
Duplicate class androidx.loader.content.AsyncTaskLoader found in modules jetified-support-v4-r7 (com.google.android:support-v4:r7) and loader-1.0.0-runtime (androidx.loader:loader:1.0.0)
Duplicate class androidx.loader.content.AsyncTaskLoader$LoadTask found in modules jetified-support-v4-r7 (com.google.android:support-v4:r7) and loader-1.0.0-runtime (androidx.loader:loader:1.0.0)
Duplicate class androidx.loader.content.CursorLoader found in modules jetified-support-v4-r7 (com.google.android:support-v4:r7) and loader-1.0.0-runtime (androidx.loader:loader:1.0.0)
Duplicate class androidx.loader.content.Loader found in modules jetified-support-v4-r7 (com.google.android:support-v4:r7) and loader-1.0.0-runtime (androidx.loader:loader:1.0.0)
Duplicate class androidx.loader.content.Loader$ForceLoadContentObserver found in modules jetified-support-v4-r7 (com.google.android:support-v4:r7) and loader-1.0.0-runtime (androidx.loader:loader:1.0.0)
Duplicate class androidx.loader.content.Loader$OnLoadCompleteListener found in modules jetified-support-v4-r7 (com.google.android:support-v4:r7) and loader-1.0.0-runtime (androidx.loader:loader:1.0.0)
Duplicate class androidx.loader.content.ModernAsyncTask found in modules jetified-support-v4-r7 (com.google.android:support-v4:r7) and loader-1.0.0-runtime (androidx.loader:loader:1.0.0)
Duplicate class androidx.loader.content.ModernAsyncTask$1 found in modules jetified-support-v4-r7 (com.google.android:support-v4:r7) and loader-1.0.0-runtime (androidx.loader:loader:1.0.0)
Duplicate class androidx.loader.content.ModernAsyncTask$2 found in modules jetified-support-v4-r7 (com.google.android:support-v4:r7) and loader-1.0.0-runtime (androidx.loader:loader:1.0.0)
Duplicate class androidx.loader.content.ModernAsyncTask$3 found in modules jetified-support-v4-r7 (com.google.android:support-v4:r7) and loader-1.0.0-runtime (androidx.loader:loader:1.0.0)
Duplicate class androidx.loader.content.ModernAsyncTask$4 found in modules jetified-support-v4-r7 (com.google.android:support-v4:r7) and loader-1.0.0-runtime (androidx.loader:loader:1.0.0)
Duplicate class androidx.loader.content.ModernAsyncTask$AsyncTaskResult found in modules jetified-support-v4-r7 (com.google.android:support-v4:r7) and loader-1.0.0-runtime (androidx.loader:loader:1.0.0)
Duplicate class androidx.loader.content.ModernAsyncTask$InternalHandler found in modules jetified-support-v4-r7 (com.google.android:support-v4:r7) and loader-1.0.0-runtime (androidx.loader:loader:1.0.0)
Duplicate class androidx.loader.content.ModernAsyncTask$Status found in modules jetified-support-v4-r7 (com.google.android:support-v4:r7) and loader-1.0.0-runtime (androidx.loader:loader:1.0.0)
Duplicate class androidx.loader.content.ModernAsyncTask$WorkerRunnable found in modules jetified-support-v4-r7 (com.google.android:support-v4:r7) and loader-1.0.0-runtime (androidx.loader:loader:1.0.0)
Duplicate class androidx.localbroadcastmanager.content.LocalBroadcastManager found in modules jetified-support-v4-r7 (com.google.android:support-v4:r7) and localbroadcastmanager-1.0.0-runtime (androidx.localbroadcastmanager:localbroadcastmanager:1.0.0)
Duplicate class androidx.localbroadcastmanager.content.LocalBroadcastManager$1 found in modules jetified-support-v4-r7 (com.google.android:support-v4:r7) and localbroadcastmanager-1.0.0-runtime (androidx.localbroadcastmanager:localbroadcastmanager:1.0.0)
Duplicate class androidx.localbroadcastmanager.content.LocalBroadcastManager$BroadcastRecord found in modules jetified-support-v4-r7 (com.google.android:support-v4:r7) and localbroadcastmanager-1.0.0-runtime (androidx.localbroadcastmanager:localbroadcastmanager:1.0.0)
Duplicate class androidx.localbroadcastmanager.content.LocalBroadcastManager$ReceiverRecord found in modules jetified-support-v4-r7 (com.google.android:support-v4:r7) and localbroadcastmanager-1.0.0-runtime (androidx.localbroadcastmanager:localbroadcastmanager:1.0.0)
Duplicate class androidx.viewpager.widget.PagerAdapter found in modules jetified-support-v4-r7 (com.google.android:support-v4:r7) and viewpager-1.0.0-runtime (androidx.viewpager:viewpager:1.0.0)
Duplicate class androidx.viewpager.widget.PagerTitleStrip found in modules jetified-support-v4-r7 (com.google.android:support-v4:r7) and viewpager-1.0.0-runtime (androidx.viewpager:viewpager:1.0.0)
Duplicate class androidx.viewpager.widget.PagerTitleStrip$PageListener found in modules jetified-support-v4-r7 (com.google.android:support-v4:r7) and viewpager-1.0.0-runtime (androidx.viewpager:viewpager:1.0.0)
Duplicate class androidx.viewpager.widget.ViewPager found in modules jetified-support-v4-r7 (com.google.android:support-v4:r7) and viewpager-1.0.0-runtime (androidx.viewpager:viewpager:1.0.0)
Duplicate class androidx.viewpager.widget.ViewPager$1 found in modules jetified-support-v4-r7 (com.google.android:support-v4:r7) and viewpager-1.0.0-runtime (androidx.viewpager:viewpager:1.0.0)
Duplicate class androidx.viewpager.widget.ViewPager$2 found in modules jetified-support-v4-r7 (com.google.android:support-v4:r7) and viewpager-1.0.0-runtime (androidx.viewpager:viewpager:1.0.0)
Duplicate class androidx.viewpager.widget.ViewPager$ItemInfo found in modules jetified-support-v4-r7 (com.google.android:support-v4:r7) and viewpager-1.0.0-runtime (androidx.viewpager:viewpager:1.0.0)
Duplicate class androidx.viewpager.widget.ViewPager$LayoutParams found in modules jetified-support-v4-r7 (com.google.android:support-v4:r7) and viewpager-1.0.0-runtime (androidx.viewpager:viewpager:1.0.0)
Duplicate class androidx.viewpager.widget.ViewPager$OnAdapterChangeListener found in modules jetified-support-v4-r7 (com.google.android:support-v4:r7) and viewpager-1.0.0-runtime (androidx.viewpager:viewpager:1.0.0)
Duplicate class androidx.viewpager.widget.ViewPager$OnPageChangeListener found in modules jetified-support-v4-r7 (com.google.android:support-v4:r7) and viewpager-1.0.0-runtime (androidx.viewpager:viewpager:1.0.0)
Duplicate class androidx.viewpager.widget.ViewPager$PagerObserver found in modules jetified-support-v4-r7 (com.google.android:support-v4:r7) and viewpager-1.0.0-runtime (androidx.viewpager:viewpager:1.0.0)
Duplicate class androidx.viewpager.widget.ViewPager$SavedState found in modules jetified-support-v4-r7 (com.google.android:support-v4:r7) and viewpager-1.0.0-runtime (androidx.viewpager:viewpager:1.0.0)
Duplicate class androidx.viewpager.widget.ViewPager$SavedState$1 found in modules jetified-support-v4-r7 (com.google.android:support-v4:r7) and viewpager-1.0.0-runtime (androidx.viewpager:viewpager:1.0.0)
Duplicate class androidx.viewpager.widget.ViewPager$SimpleOnPageChangeListener found in modules jetified-support-v4-r7 (com.google.android:support-v4:r7) and viewpager-1.0.0-runtime (androidx.viewpager:viewpager:1.0.0)

 Go to the documentation to learn how to <a href="d.android.com/r/tools/classpath-sync-errors">Fix dependency resolution errors</a>.

*

*Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

*Get more help at https://help.gradle.org
Deprecated Gradle features were used in this build, making it incompatible with Gradle 7.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/6.5/userguide/command_line_interface.html#sec:command_line_warnings
BUILD FAILED in 9s
27 actionable tasks: 1 executed, 26 up-to-date

run :

build gradle (app):
apply plugin: 'com.onesignal.androidsdk.onesignal-gradle-plugin'
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-kapt'
apply plugin: 'com.google.gms.google-services'
apply plugin: 'com.google.firebase.crashlytics'

def keystorePropertiesFile = rootProject.file("keystore.properties")
// Initialize a new Properties() object called keystoreProperties.
def keystoreProperties = new Properties()
// Load your keystore.properties file into the keystoreProperties object.
keystoreProperties.load(new FileInputStream(keystorePropertiesFile))

android {
    signingConfigs {
        release {
            storeFile file(keystoreProperties['storeFile'])
            storePassword keystoreProperties['storePassword']
            keyAlias keystoreProperties['keyAlias']
            keyPassword keystoreProperties['keyPassword']
        }
    }
    compileSdkVersion 30
    buildToolsVersion '30.0.3'
    defaultConfig {
        applicationId "com.ligradyo.android"
        minSdkVersion 17
        targetSdkVersion 30
        versionCode 10
        versionName "1.1.0"
        multiDexEnabled true
        testInstrumentationRunner 'androidx.test.runner.AndroidJUnitRunner'
        manifestPlaceholders = [onesignal_app_id               : "4193dbe8-83d0-4d1c-8625-1cb42c2a37ae",
                                onesignal_google_project_number: "658644867384"]

        archivesBaseName = "ligradyo-$versionName"
    }
    sourceSets { main { assets.srcDirs = ['src/main/assets', 'src/main/assets/'] } }
    buildTypes {
        release {
            minifyEnabled false
            signingConfig signingConfigs.release
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')

    implementation 'androidx.appcompat:appcompat:1.2.0'
    implementation "androidx.core:core-ktx:1.3.2"
    implementation 'com.google.android.material:material:1.3.0'
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'com.android.support:multidex:1.0.3'
    implementation 'com.mcxiaoke.volley:library:1.0.19'
    implementation 'com.google.code.gson:gson:2.8.6'

    // Retrofit
    implementation 'com.squareup.retrofit2:retrofit:2.6.4'
    implementation 'com.squareup.retrofit2:converter-gson:2.6.4'

    //Glide
    implementation 'com.github.bumptech.glide:glide:4.12.0'
    kapt 'com.github.bumptech.glide:compiler:4.12.0'

    implementation 'com.nostra13.universalimageloader:universal-image-loader:1.9.5'
    implementation 'com.viewpagerindicator:library:2.4.1'

    // Add the Firebase Crashlytics SDK.
    implementation platform("com.google.firebase:firebase-bom:26.8.0")
    implementation "com.google.firebase:firebase-crashlytics"
    implementation "com.google.firebase:firebase-analytics"
    implementation "com.google.firebase:firebase-auth"
    implementation 'com.google.firebase:firebase-messaging'
    implementation 'com.google.firebase:firebase-core'

    implementation 'com.google.android.gms:play-services-gcm:17.0.0'
    implementation 'com.google.android.gms:play-services-location:18.0.0'
    implementation 'com.google.android.gms:play-services-analytics:17.0.0'

    implementation 'com.onesignal:OneSignal:3.15.6'

    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.2'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'

}

build gradle (project)
// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    ext.kotlin_version = '1.4.32'
    repositories {
        google()
        jcenter()
        maven {
            url 'https://maven.google.com/'
            name 'Google'
        }
        maven { url 'https://plugins.gradle.org/m2/' }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:4.1.3'
        classpath 'com.google.gms:google-services:4.3.5'
        classpath 'gradle.plugin.com.onesignal:onesignal-gradle-plugin:0.12.10'
        classpath 'com.google.firebase:firebase-crashlytics-gradle:2.5.2'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        maven { url "http://dl.bintray.com/populov/maven" }
        maven { url "https://jitpack.io" }
        mavenCentral()
        jcenter()
        maven {
            url 'https://maven.google.com/'
            name 'Google'
        }
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

A: I created a new project and moved my existing activity and design pages, checked the pages and added the latest version of the required libraries to the project and was able to solve the problem.


text:
Q: What does this mean: [ x[1:] for x in self.files if x != '/'] What does this mean:
[x[1:] for x in self.files if x != '/']

If possible would you mind explaining it in imperative equivalent?

A: Let's see the expression one step at a time. This part returns a list of files in the current object:
self.files

Now let's iterate over the list and call x each element in turn:
for x in self.files

But let's not take all of them, let's just consider those that are not called '/':
for x in self.files if x != '/'

For each of the files that pass the filter, let's remove the first character in the file's name:
x[1:] for x in self.files if x != '/'

And finally, let's put the results in a new list:
[x[1:] for x in self.files if x != '/']

FYI, what we just did it's called a list comprehension. As pointed by @PasteBT and @aga, the code is equivalent to this explicit loop:
ans = []                  # create a new empty list
for x in self.files:      # iterate over it, using x as variable
    if x != '/':          # if the element is not 'x'
        ans.append(x[1:]) # add it after removing 1st char

Now ans will contain the same list as the one returned by the list comprehension.

A: It's list comprehension which constructs a new list which elements are slices of filenames in the variable self.files excluding the filename of root directory. Each slice consists of n-1 letters in a filename, from the second (where second letter in a string has index of 1) to the last.
An imperative equivalent of this code will be a little bit more verbose:
lst = []
for x in self.files:
    if x != "/":
        lst.append(x[1:])

A: same as:
ret = []
for x in self.files:
    if x != '/':
        ret.append(x[1:])
return ret