text:
Q: How to convert a String[] to int[] in C# and .NET 2.0? I've got :
string[] strArray = new string[3] { "1", "2", "12" };

And I want something like this
int[] intArray = Convert.toIntArray(strArray);

I work int C# .net v2.0, I don't want to write a lot of code.
How can I do that?
Thank you.

A: You can use the Array.ConvertAll method for this purpose, which "converts an array of one type to an array of another type."
int[] intArray = Array.ConvertAll(strArray,
                                  delegate(string s) { return int.Parse(s); });

(EDIT: Type-inference works fine with this technique. Alternatively, you could also use an implicit method-group conversion as in Marc Gravell's answer, but you would have to specify the generic type-arguments explicitly.)
Using a for-loop:
int[] intArray = new int[strArray.Length];

for (int i = 0; i < strArray.Length; i++)
   intArray[i] = int.Parse(strArray[i]);

For completeness, the idiomatic way of doing this in C# 4.0 would be something like:
var intArray = strArray.Select(int.Parse).ToArray();

or:
//EDIT: Probably faster since a fixed-size buffer is used
var intArray = Array.ConvertAll(strArray, int.Parse);

A: using System.Collections.Generic;

int Convert(string s)
{
    return Int32.Parse(s);
}

int[] result = Array.ConvertAll(input, new Converter<string, int>(Convert));

or
int[] result = Array.ConvertAll(input, delegate(string s) { return Int32.Parse(s); })

A: int[] intArray = Array.ConvertAll(strArray, int.Parse);

or in C# 2.0 (where the generic type inference is weaker):
int[] intArray = Array.ConvertAll<string,int>(strArray, int.Parse);

A: Array.ConvertAll Generic Method
Converts an array of one type to an array of another type.

A: When you are sure, all items are definitely parsable, this will do the trick:
string[] strArray = new string[3] { "1", "2", "12" };
int[] intArray = new int[strArray.Length];
for (int i = 0; i < strArray.Length; i++)
{
    intArray[i] = int.Parse(strArray[i]);
}

A: Something like this, but you want to keep a bit of error checking ( my if is really lame, just as example ):
static private int[] toIntArray(string[] strArray)
{
    int[] intArray = new int[strArray.Length];
    for (int index = 0; index < strArray.Length; index++)
    {
            intArray[index] = Int32.Parse(strArray[index]);
    }
    return intArray;
}

And use it like this:
string[] strArray = new string[3] { "1", "2", "12" };
int[] interi = toIntArray(strArray);


text:
Q: poste.io Let's encrypt certificate issue exception I am using the poste.io mail server.  While trying to issue the SSL cert using lets encrypt, it throws below error.  Anyone has observed it already and could fix it?
[2016-11-08 00:12:44] LEScript.INFO: Account already registered. Continuing.
[2016-11-08 00:12:44] LEScript.INFO: Starting certificate generation process for domains
[2016-11-08 00:12:44] LEScript.INFO: Requesting challenge for mail.domain.ltd
[2016-11-08 00:12:45] LEScript.INFO: Sending signed request to /acme/new-authz
[2016-11-08 00:12:45] LEScript.INFO: Got challenge token for mail.domain.ltd
[2016-11-08 00:12:45] LEScript.INFO: Token for mail.domain.ltd saved at /opt/www//.well-known/acme-challenge/UEyhta88fiS_E5WTn-SOxKI-lqbsK1-eTOceiE_UnTQ and should be available at http://mail.domain.ltd/.well-known/acme-challenge/UEyhta88fiS_E5WTn-SOxKI-lqbsK1-eTOceiE_UnTQ
[2016-11-08 00:12:47] LEScript.ERROR: Please check http://mail.domain.ltd/.well-known/acme-challenge/UEyhta88fiS_E5WTn-SOxKI-lqbsK1-eTOceiE_UnTQ - token not available
[2016-11-08 00:12:47] LEScript.ERROR: #0 /opt/mailserver-admin/src/Analogic/LetsEncryptBundle/Handler/LeHandler.php(55): Analogic\ACME\Lescript->signDomains(Array)
[2016-11-08 00:12:47] LEScript.ERROR: #1 /opt/mailserver-admin/src/Analogic/LetsEncryptBundle/Controller/LeController.php(74): Analogic\LetsEncryptBundle\Handler\LeHandler->renew(true)
[2016-11-08 00:12:47] LEScript.ERROR: #2 [internal function]: Analogic\LetsEncryptBundle\Controller\LeController->issueAction(Object(Symfony\Component\HttpFoundation\Request))
[2016-11-08 00:12:47] LEScript.ERROR: #3 /opt/mailserver-admin/var/bootstrap.php.cache(3040): call_user_func_array(Array, Array)
[2016-11-08 00:12:47] LEScript.ERROR: #4 /opt/mailserver-admin/var/bootstrap.php.cache(2995): Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object(Symfony\Component\HttpFoundation\Request), 1)
[2016-11-08 00:12:47] LEScript.ERROR: #5 /opt/mailserver-admin/var/bootstrap.php.cache(2335): Symfony\Component\HttpKernel\HttpKernel->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)
[2016-11-08 00:12:47] LEScript.ERROR: #6 /opt/mailserver-admin/web/app.php(19): Symfony\Component\HttpKernel\Kernel->handle(Object(Symfony\Component\HttpFoundation\Request))
[2016-11-08 00:12:47] LEScript.ERROR: #7 {main}

Have posted in https://bitbucket.org/analogic/mailserver/issues/139/lets-encrypt-certificate-issue-exception but seems they only respond to pro customers. :(

A: Problem solved.  My firewall disabled the port 25.  Once the port is open, it started to work.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Most efficient way of selecting thousands of rows from a list of ids Are there any scalable ways of selecting thousands of rows using mysql IN or something similar?
E.g.
SELECT * FROM awesomeTable WHERE id IN (1,2,3,4......100000)

Is this possible or am I just dreaming? Schema is InnoDB, can be changed if another would provide a more scalable solution.
For reference I am getting search results from a set of ids returned from Solr. I'd like to use mysql for the final retrieval as it would make sorting and final filtering of these results much easier (I won't get into the details of why).
EDIT:
The query could be use a LIMIT clause as long as the IN still contained all 100000 of the ids
E.g.
SELECT * FROM awesomeTable WHERE id IN (1,2,3,4......100000) LIMIT 10;

A: I that were me, and not really knowing your framework, you should try inserting those ID into a temporary table and using this table with a simple inner join. That could prove to be as fast as this IN.

A: I came up to the same question while inserting into mysql tables.
The possible query size depends on your mysql configuration.
My approach was to split the big ids collection into some parts.
Using Ruby on Rails:
all_ids.each_slice(10000) do |ids_part|
  query = "INSERT INTO ..."
end

Perhaps this could also be a solution for selecting rows by ids.


text:
Q: Problem with redirecting I have a problem with ASP.NET.
I have button on ex. index.aspx which redirect us to index2.aspx, but before that, first page - index.aspx - was reloaded. I don't need it because function in "load" is running again.
How to solve that problem?

A: Use a link instead of a button, if you want that the user goes directly to the new page.
A button will always cause a PostBack and fire the Click event of the button, so you can deal with the user input.
You can also make sure the code in the Load event of the Page is not executed on PostBacks:
protected void Page_Load(object sender, EventArgs e)
{
    if(!IsPostBack)
    {
        // your page initialization code
    }
}

But as I said, the proper way to go is a Link.


text:
Q: Looping through Pandas column to derive values to be added to a different column I have code to be able to look up addresses and find their area names and cities using Geopy (Google V3). Currently it only works on static addresses, I want to be able to loop through the entire pandas column that contains addresses and output cities and area names each to a different column for each row.
from geopy.geocoders import GoogleV3

address = '1238 Davie St, Vancouver, BC'

geocoder = GoogleV3(api_key='xyzabc')

location = geocoder.geocode(address, language='en')

address_components = location.raw['address_components']

counties = [addr['long_name'] for addr in address_components if 'neighborhood' in addr['types']]
localities = [addr['long_name'] for addr in address_components if 'locality' in addr['types']]

Works well, but when I assign df['address_original'] to the address variable, I only get the result for the first row.
Would I need to build a loop for this, or are there other ways?
The output I am getting at the moment is
[] [u'Clearwater']

which is the result for the first address in the df['address_original'] column. I would like to get the results for all the addresses in the column


text:
Q: Calculating value of Q,when remainder is given. 3rd degree polynomial If $f(X) = 2x^3 + 4qx^2 - 3q^2x -2$ is divided by $x-q$ the remainder is $10$, then calculate the value of $q$.
Tried factoring the polynomial.
Obtain quotient by means of long division.
I am truly missing something here. Please help.

A: Asserting that the remainder of the division of $f(x)$ by $x-q$ is $10$ is the same thing as asserting that $f(q)=10$. So, solve the equation $f(q)=10$.

A: HINT:
\begin{equation}\begin{aligned}
f(x) &= 2x^3+4qx^2-3q^2x-2 \\
&= 2x^3-2qx^2+6qx^2-6q^2x+3q^2x-3q^3+3q^3-2 \\
&= 2x^2(x-q)+6qx(x-q)+3q^2(x-q)+3q^3-2 \\
&= (x-q)(2x^2+6qz+3q^2)+3q^3-2 \\
\end{aligned}\end{equation}


text:
Q: A smooth map of manifolds that preserves linear connections. Let $D$ and $D'$ be two linear connections on manifolds $M$ and $M'$ respectively. If $f:M\to M'$ is a smooth map from $M$ into $M'$, what is meant by "$f$ is a connection preserving" ?.
Thanks in advance.

A: There is a pullback connection $f^*D'$ on $f^*TM$ given by $(f^*D')_X(f^*Y) = D'_{f_*X}Y$ where $X \in \Gamma(M, TM)$ and $Y \in \Gamma(M', TM')$. If $f$ is such that $f^*TM \cong TM$ (e.g. a local diffeomorphism), then $f^*D'$ and $D$ are two connections on $TM$. In this case, $f$ is said to be connection-preserving if $f^*D' = D$.


text:
Q: syntax error: Expected end of line but found unknown token I am attempting to run some AppleScript in the terminal, just to learn how to do it, and I am running into some trouble with the & sign.  Even when the & is replaced with the "&", it still returns the same error..  I have narrowed it down to the problem with the & sign, and am wondering if anyone has any advice about it.  I am getting the following error:

syntax error: Expected expression but found unknown token.

My code that I type into the terminal:
osascript -e 'tell application "Finder"' -e  'set location to (path to home folder as string) & \"testing.plist\"' -e 'if (exists file location) then' -e 'say location' -e 'end if' -e 'end tell'

A: You don't need the backslashes to escape the double quotes for "testing.plist", removing those will fix that error.
Additionally, the word "location" is used by the Finder dictionary, so you'll want to use some other term for that variable, such as "myLocation" instead.


text:
Q: If statement in UNIX for loop not excluding the variables I want excluded Here is the UNIX code I wrote to join all sea ice extent files into one file. I tried to do this by joining the first two years then creating a for loop that then excludes those first two years so they do not get added twice. They are still being added twice.
#!/bin/bash
#this creates the file output_extent initially but then the if statement in the following loop does not work and there are two columns for 1979 and 1989
join polar_ice_extent_data.1979.txt polar_ice_extent_data.1980.txt > output_extent.txt

#for loop with an if statment to join all files that include extent except the first two into a new file.
#Have to create a temporary file because it will not append back onto output_extent directly
for file in *extent*.txt; do
    if [ $file != polar_ice_extent_data.1979.txt ] && [ $file != polar_ice_extent_data.1980.txt ]; then
        join output_extent.txt $file > tmp.txt; mv tmp.txt output_extent.txt;
    fi
done

File example: This is repeated for 1979-2015
#year   1979
jan 15.6
feb 16.38
mar 16.52
apr 15.56
may 14.08
jun 12.65
jul 10.52
aug 8.18
sep 7.22
oct 9.42
nov 11.18
dec 13.57

A: It needed single quotation marks around my file names in the if statement.


text:
Q: eucalyptus started but appear error I installed eucalyptus, but when i start eucalyptus , it's appear mistake. I check file eucanetd.log, it show following:
 2014-12-11 11:40:01 ERROR | command failed: exitcode='256' command='//usr/lib/eucalyptus/euca_rootwrap /usr/sbin/dhcpd -cf //var/run/eucalyptus/net/euca-dhcp.conf -lf //var/run/eucalyptus/net/euca-dhcp.leases -pf //var/run/eucalyptus/net/euca-dhcp.pid -tf //var/run/eucalyptus/net/euca-dhcp.trace'
2014-12-11 11:40:01 ERROR | unable to (re)configure local dhcpd server: check above log errors for details
2014-12-11 11:40:01 ERROR | could not complete update of private IPs: check above log errors for details
2014-12-11 11:40:01  INFO | new networking state (VM public network addresses): updated successfully
2014-12-11 11:40:01  INFO | new networking state (VM network isolation): updated successfully
2014-12-11 11:40:02  INFO | new networking state (VM security groups): updating system
2014-12-11 11:40:02  INFO | new networking state (VM security groups): updated successfully
2014-12-11 11:40:02  INFO | new networking state (VM public/private network addresses, VM network isolation): updating system
2014-12-11 11:40:02 ERROR | command failed: exitcode='256' command='//usr/lib/eucalyptus/euca_rootwrap /usr/sbin/dhcpd -cf //var/run/eucalyptus/net/euca-dhcp.conf -lf //var/run/eucalyptus/net/euca-dhcp.leases -pf //var/run/eucalyptus/net/euca-dhcp.pid -tf //var/run/eucalyptus/net/euca-dhcp.trace'
2014-12-11 11:40:02 ERROR | unable to (re)configure local dhcpd server: check above log errors for details
2014-12-11 11:40:02 ERROR | could not complete update of private IPs: check above log errors for details
2014-12-11 11:40:02  INFO | new networking state (VM public network addresses): updated successfully
2014-12-11 11:40:02  INFO | new networking state (VM network isolation): updated successfully
2014-12-11 11:40:03  INFO | new networking state (VM security groups): updating system
2014-12-11 11:40:03  INFO | new networking state (VM security groups): updated successfully
2014-12-11 11:40:03  INFO | new networking state (VM public/private network addresses, VM network isolation): updating system
2014-12-11 11:40:03 ERROR | command failed: exitcode='256' command='//usr/lib/eucalyptus/euca_rootwrap /usr/sbin/dhcpd -cf //var/run/eucalyptus/net/euca-dhcp.conf -lf //var/run/eucalyptus/net/euca-dhcp.leases -pf //var/run/eucalyptus/net/euca-dhcp.pid -tf //var/run/eucalyptus/net/euca-dhcp.trace'
2014-12-11 11:40:03 ERROR | unable to (re)configure local dhcpd server: check above log errors for details
2014-12-11 11:40:03 ERROR | could not complete update of private IPs: check above log errors for details
2014-12-11 11:40:04  INFO | new networking state (VM public network addresses): updated successfully
2014-12-11 11:40:04  INFO | new networking state (VM network isolation): updated successfully
2014-12-11 11:40:05  INFO | new networking state (VM security groups): updating system
2014-12-11 11:40:05  INFO | new networking state (VM security groups): updated successfully
2014-12-11 11:40:05  INFO | new networking state (VM public/private network addresses, VM network isolation): updating system

Any help?
Cheers,
Nghiep

A: Yes, I have /usr/sbin/dhcpd on the system. and this is file configure of eucalyptus.
EUCALYPTUS="/"
LOGLEVEL="INFO"
EUCA_USER="eucalyptus"
CLOUD_OPTS=""
NC_PORT="8775"
CC_PORT="8774"
SCHEDPOLICY="ROUNDROBIN"
NODES="10.10.2.11"
NC_SERVICE="axis2/services/EucalyptusNC"
HYPERVISOR="kvm"
MAX_CORES="0"
INSTANCE_PATH="/var/lib/eucalyptus/instances"
USE_VIRTIO_ROOT="1"
USE_VIRTIO_DISK="1"
USE_VIRTIO_NET="1"
VNET_MODE="EDGE"
VNET_PRIVINTERFACE="br0"
VNET_PUBINTERFACE="br0"
VNET_BRIDGE="br0"
VNET_DHCPDAEMON="/usr/sbin/dhcpd"
METADATA_USE_VM_PRIVATE="N"
DISABLE_TUNNELING="Y"

A: Do you have /usr/sbin/dhcpdon the system? If not, you either need to point Eucalyptus to the right location of your DHCP daemon using VNET_DHCPDAEMON parameter in the /etc/eucalyptus/eucalyptus.conf file or you need to install a DHCP daemon and ensure that the parameter above is pointing to it.

A: There may be a port conflict with dnsmasq preventing dhcpd from starting. Check if the "default" network is active on the node controller:
# virsh net-list

if it is then you can use:
# virsh net-destroy default

to destroy the default network and stop the associated dnsmasq process allowing dhcpd to run.


text:
Q: How do I set legend element titles? I am using code from this biostars post to get myself more acquainted with creating plots in ggplot. I am a bit stuck on setting the legend variables though
Is there a way to set the colour and control the number of breaks/dots in the legend (under numDEInCat)
term <-c("snoRNA binding", "preprophase band", "kinesin complex", "microtubule motor activity", "DNA replication")
fc <-runif(5, 1.00, 5.00)
padj_BH <-runif(5, 0.001, 0.05)
numDEInCat <-runif(5, 30, 300)

ggdata <- data.frame(term,fc,padj_BH,  numDEInCat)

gg1 <- ggplot(ggdata,
  aes(x = term, y = fc, size = numDEInCat, color = padj_BH)) +

  expand_limits(y = 1) +
  geom_point(shape = 16,inherit.aes = T) +
  scale_size(range = c(2.5,12.5)) +
  scale_color_gradient(low= "#ff0303",
                       high="#1e00b3")+  #colour for p value

  xlab('') + ylab('Fold Enrichment') + #lavel fold enrichment axis
  labs(
    title = "Gene Ontology all",
    subtitle = 'BH-adjusted',
    caption = '',
    color="Adjusted P-value", #label the aacolor
    size="count") +  #label dot size

  theme_bw(base_size = 24) +
  theme(
    legend.position = 'right',
    legend.background = element_rect(),
    plot.title = element_text(angle = 0, size = 16, face = 'bold', vjust = 1),
    plot.subtitle = element_text(angle = 0, size = 14, face = 'bold', vjust = 1),
    plot.caption = element_text(angle = 0, size = 12, face = 'bold', vjust = 1),

    axis.text.x = element_text(angle = 0, size = 12, face = 'bold', hjust = 1.10),
    axis.text.y = element_text(angle = 0, size = 12, face = 'bold', vjust = 0.5),
    axis.title = element_text(size = 12, face = 'bold'),
    axis.title.x = element_text(size = 12, face = 'bold'),
    axis.title.y = element_text(size = 12, face = 'bold'),
    axis.line = element_line(colour = 'black'),

    #Legend
    legend.key = element_blank(), # removes the border
    legend.key.size = unit(1, "cm"), # Sets overall area/size of the legend
    legend.text = element_text(size = 14, face = "bold"), # Text size
    title = element_text(size = 14, face = "bold")) +

  coord_flip()

gg1

A: I think what you're looking for are guides(size = guide_legend(override.aes(BLABLA))) and scale_size(breaks = c(BLABLA))
gg1 +
  guides(size = guide_legend(override.aes = list(colour = "red"))) +
  scale_size(limits = c(1, 1000), breaks = c(10, 500, 1000))

Created on 2021-11-18 by the reprex package (v2.0.1)


text:
Q: Regarding spring container eagerly singleton design pattern I have developed an utility class for spring which is a singleton which will provide the reference of container for the whole application , below is my class..
public class SpringUtility
{
    private static BeanFactory factory ;
    static
    {try
        {BeanFactory factory = new XmlBeanFactory(new FileSystemResource("Spring.xml"));
        }   catch(Exception e)
        {
            e.printStackTrace();
        }
    }

    private SpringUtility()
    {}

    public static BeanFactory getBeanFactory()
    {       return factory;
    }}

Now please advise I want to convert it into style of eager singleton, Please advise how this could be achieved. please advise how this same class could be converted it in eager singleton design pattern such as the normal eager design pattern is ..
public class SingletonEager {

    private final static SingletonEager INSTANCE = new SingletonEager();

    private SingletonEager() {
    }

    public static SingletonEager getInstance() {
        return SingletonEager.INSTANCE;
    }

    protected Object clone() throws CloneNotSupportedException {
        throw new CloneNotSupportedException();
    }
}

similar way I want for spring one too please advise

A: If you want BeanFactory to grab beans from Spring context, then I'd suggest you to implement BeanFactoryAware, It would stay singleton & eagerly loaded
public class BeanManager implements BeanFactoryAware {

  private BeanFactory beanFactory;

  public Person getPerson(){ beanFactory.getBean(Person.class) ;}

}

And mark this BeanManager class as spring bean


text:
Q: Almost-periodic functions In the interest of analytic solutions to functional equations I was considering the case where instead of $F(x+\omega) = F(x)$ we have $F(x+\omega) = G(F(x))$ for some $G,F$ analytical functions and $\omega \in \mathbb{C}$, or to simplify it just have $\omega \in \mathbb{R}$.
I was wondering if anyone has researched this topic and if there are any interesting results about it. If there would, how would you figure out solutions to such problems?
For example a solution to equations like $F(x+\omega) = F(x) + k$ for some constant k.
maybe a function similar to $\sin(x)$ or $\cos(x)$, but bent sideways, which would create some kind of wavy diagonal function.
Thanks!


text:
Q: How does the compactness property help us show a subset $A$ of a metric space $X$ is closed? We have a compact subset $A$ of a metric space $X$ and we want to show that this implies that $A$ is closed.
Let $y \in A$ and $y \in A^c$. For each $y \in A$, we can take open neighbourhoods $U_y$ of $y$ and $V_y$ of $x$ such that $U_y \bigcap V_y = \emptyset$. Because $A$ is compact we only need a finite number of the $U_y$s to cover $A$. So let $U = \bigcup_{i=1}^N U_i$ and $V = \bigcap_{i=1}^N V_i$. Then $U$ and $V$ are open and $U \bigcap V = \emptyset$.
Now $x \in V \subseteq A^c$ and as $x$ is arbitrary $A^c$ is open. Hence $A$ is closed.
What I don't get is how does the compactness assumption help us here? Why can't we just take an infinite number of $U_y$s that cover $A$? That is let $U = \bigcup_{i \in I} U_y$ and $V = \bigcap_{i \in I} V_y$ where $I$ is an infinite index set.
Then we can still say $x \in V \subseteq A^c$ and as $x$ is arbitrary $A^c$ is open. Hence $A$ is closed?

A: The following is not so much an answer to the question, as a commentary on the unnecessary use
of the axiom of choice in the proof given by the author of the question. I am doing this because
this kind of abuse of AC is typical.
We can avoid using AC in the following way.
Suppose we have a compact subset $A$ of a Hausdorff space $X$ (every metric space has a Hausdorff topology); we shall prove that $A$ is closed. Let $x\in X\setminus A$. We claim that some open neighborhood of $x$ is contained in $X\setminus A$; this will prove that $A$ is closed.
Let $I$ be the set of all pairs of open sets $(U,V)$ where $x\in U$ and $U\cap V=\varnothing$. For each $i=(U,V)\in I$ we let $N_i:=U$ and $W_i:=V$. If a point $y\in X$ is different from $x$, then
there exists $i=(U,V)\in I$ such that $y\in V=W_i$, because $X$ is a Hausdorff space.
Therefore $\bigcup_{i\in I}W_i=X\setminus\{x\}$. In particular, $A$ is contained in the union $\bigcup_{i\in I}W_i$.
Since $A$ is compact, it is contained in the union $\bigcup_{k\in K}W_k$ for some finite subset $K$ of $I$.
Then the point $x$ has an open neighborhood  $\bigcap_{k\in K}N_k$ that is disjoint with the open
neighborhood $\bigcup_{k\in K}W_k$ of the set $A$, and hence is disjoint with the set $A$ itself.
Our claim is proved.


text:
Q: Turn a recursive method into an iterative method I have to create two methods that do the same thing. The methods have to calculate the L(n) of the numbers from 0 - 30 where L(n) is defined as

L(0) = 1
L(1) = 1
L(n) = L(n - 1) + L(n - 2) + 1;
when  n > 1

The first method has to be written using recursion which I successfully did and the second one has to be made using iteration ( arrays and for loops )
First method)
public static int rec(int x) {
  if (x == 0) return 1;
  if (x == 1) return 1;
  else return rec(x - 1) + rec(x - 2) + 1;
}

and i added this in main for the first method
int x = 0;
    while (x <= 30) {
        System.out.println(rec(x));
        x++;
    }

and this is all i have been able to do with the second method , while i know it is wrong , bare in mind im a beginner , be gentle
Second method)
 public static long iter(long [] x){
    long result = 0  ;
    int length = x.length;
    for ( int i = 0 ; i < length ; i++){
        if ( i == 0 ) result = 1;
        if ( i == 1 ) result = 1;
        else  result += x[i-1]+x[i-2]+1;
    }
    return result ;
}

A: Think about what your code here is doing -
for ( int i = 0 ; i < x.length ; i++){
           long returnvalue = x[i-1]+x[i-2]+1; // every iteration you are resetting returnvalue.
    }

In every iteration you are creating a new variable and then losing what you have just computed.
You need to add this result from each iteration so you will have to do this -
 for ( int i = 0 ; i < x.length ; i++){
           returnvalue = returnvalue + x[i-1]+x[i-2]+1;
    }

Or you can also do this -
returnvalue +=  x[i-1]+x[i-2]+1;

Notice that in the iterative version returnValue is defined only once before your loop starts.

A: How about treating L as an array, then performing the following assignments:

L(0) = 1
L(1) = 1

For the 3rd step, you will have to write a loop calculating and storing the values of L[2] to L[30]. At each iteration of the loop, the previous 2 values will already be in L, so you can just use them.

A: You are very close - you need to hold a history in your iterating solution:
public static long iter(long x) {
    long result = 0;
    // Make a 2-length array for my history.
    long[] history = new long[2];
    for (int i = 0; i <= x; i++) {
        if (i < 2) {
            result = 1;
        } else {
            result = history[0] + history[1] + 1;
        }
        // Maintain my history.
        history[0] = history[1];
        history[1] = result;
    }
    return result;
}

A: So I was able to finally solve it : ( Thanks for all the help , really really appreciate it  )
public class Aufgabe1 {

// invokes iter as well as rec with all integers from 0 to 30 and prints the results
// (without empty lines or other output)
public static void main(String[] args) {
    // TODO: Implementation is your task
    int x = 0;
    while (x <= 30) {
        System.out.println(rec(x));
        x++;
    }
    long [] longArr = new long[31];
    iter(longArr);
}

public static int rec(int x) {
    if (x == 0) return 1;
    if (x == 1) return 1;
    else return rec(x - 1) + rec(x - 2) + 1;
}

    public static void iter(long[] n) {
        for (int i = 0; i < n.length; i++) {
            if (i == 0 || i == 1) {
                n[i] = 1;
            } else {
                n[i] = n[i - 1] + n[i - 2] + 1;
            }
            System.out.println(n[i]);
        }

    }
    }


text:
Q: My Android studio run menu is deactivated My android studio gives me a plugin error and loads project but the run button is deactivated. Below is the even log
8/5/2017
2:46 PM Platform and Plugin Updates: Android Studio is ready to update.

2:46 PM AbstractMethodError: null

2:46 PM AbstractMethodError: null

2:46 PM Plugin Error
                Problems found loading plugins:
                Plugin "Android Games" was not loaded: required plugin "Android Support" is disabled.
                Plugin "Android NDK Support" was not loaded: required plugin "Android Support" is disabled.
                Plugin "NDK WorkspaceManager Support" was not loaded: required plugin "Android Support" is disabled.
                Plugin "Firebase App Indexing" was not loaded: required plugin "Android Support" is disabled.
                Plugin "Google Developers Samples" was not loaded: required plugin "Android Support" is disabled.
                Plugin "Google Cloud Tools For Android Studio" was not loaded: required plugin "Android Support" is disabled.
                Plugin "Test Recorder" was not loaded: required plugin "Android Support" is disabled.
                Plugin "Firebase Testing" was not loaded: required plugin "Android Support" is disabled.
                Plugin "Google Services" was not loaded: required plugin "Android Support" is disabled.
                Plugin "Firebase Services" was not loaded: required plugin "Android Support" is disabled.
                P... (show balloon)

2:47 PM Plugins Suggestion
                Unknown feature (Run Configuration[AndroidRunConfigurationType]) covered by disabled plugin detected.
                Enable plugins...
                Ignore Unknown Features

A: This due to missing Plugins.Enable Android Studio Plugin to resolve the issue


text:
Q: UIimagePicker and application freezing ! I am trying to take a picture with camera , but after capture a picture or cancel imagePickerView , my application will be freeze without any bug report or BAD_ACCESS or crash ! jut freeze !!!! here is my code :
    -(IBAction)takePic {

    if ([UIImagePickerController isSourceTypeAvailable:CAMERASUPPROT]) {

        USImage.hidden = YES;
        ipc = [[UIImagePickerController alloc]init];

        ipc.delegate = self;
        ipc.sourceType = UIImagePickerControllerSourceTypeCamera;
        ipc.cameraOverlayView = maskImage;
        ipc.delegate = self;
        [self.view addSubview:MaskArea];
        [self presentModalViewController:ipc animated:YES];
        TAKENPHOTO.image = nil;
        [ipc release];

  } else {

        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Error" message:@"Your Device Doesn't Support Camera" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
        [alert release];
    }

}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {

    TAKENPHOTO.image = [info objectForKey:UIImagePickerControllerOriginalImage];
    [picker dismissModalViewControllerAnimated:YES];

}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {

    [picker dismissModalViewControllerAnimated:YES];
}

A: assuming [self.view addSubview:MaskArea]; it's an UIView so , I think the problem is this line , remove it then try again !


text:
Q: Angularjs two-way binding in index.html I am new to Angularjs. I am trying to build a simple system with a login page and it will redirect to another page after successfully logged in.
I am trying to show all the pages in index.html with ng-view (including login page). I try to use ng-if to decide when to show the navigation bar on top of the page.
The value of vm.page will not change after logged in
index.html

    <title></title>
    <link href="css/bootstrap.min.css" rel="stylesheet"/>
    <link href="css/custom.css" rel="stylesheet"/>

login-controller.js
angular.module('myApp').controller("LoginController", LoginController);

function LoginController($http, $location, $scope) {
    var vm = this;
    vm.page = "Login";

    vm.login = function(){
        vm.page = "Main";
        $location.path('/')
    }
}

It is working when the vm.page is initiate and set to "Login", but the page does not change when i set it to "Main".
Appretiate if anyone can help me, thank you :D

A: The problem is the $location.path('/') call in your Login-Function. This will navigate to /index.html and re-initialize the LoginController. Therefore the vm.page variable is reset to 'Login'.
Remove the location.path() or create a service which reatains the Page/Login-State.


text:
Q: Using list comprehension in Python to do something similar to zip()? I'm a Python newbie and one of the things I am trying to do is wrap my head around list comprehension.  I can see that it's a pretty powerful feature that's worth learning.
cities = ['Chicago', 'Detroit', 'Atlanta']
airports = ['ORD', 'DTW', 'ATL']

print zip(cities,airports)
[('Chicago', 'ORD'), ('Detroit', 'DTW'), ('Atlanta', 'ATL')]

How do I use list comprehension so I can get the results as a series of lists within a list, rather than a series of tuples within a list?
[['Chicago', 'ORD'], ['Detroit', 'DTW'], ['Atlanta', 'ATL']]

(I realize that dictionaries would probably be more appropriate in this situation, but I'm just trying to understand lists a bit better). Thanks!

A: If you wanted to do it without using zip at all, you would have to do something like this:
[ [cities[i],airports[i]] for i in xrange(min(len(cities), len(airports))) ]

but there is no reason to do that other than an intellectual exercise.
Using map(list, zip(cities, airports)) is shorter, simpler and will almost certainly run faster.

A: Something like this:
[[c, a] for c, a in zip(cities, airports)]

Alternately, the list constructor can convert tuples to lists:
[list(x) for x in zip(cities, airports)]

Or, the map function is slightly less verbose in this case:
map(list, zip(cities, airports))

A: A list comprehension, without some help from zip, map, or itertools, cannot institute a "parallel loop" on multiple sequences -- only simple loops on one sequence, or "nested" loops on multiple ones.

A: This takes zip's output and converts all tuples to lists:
map(list, zip(cities, airports))

As for the performance of each:
$ python -m timeit -c '[ [a, b] for a, b in zip(xrange(100), xrange(100)) ]'
10000 loops, best of 3: 68.3 usec per loop

$ python -m timeit -c 'map(list, zip(xrange(100), xrange(100)))'
10000 loops, best of 3: 75.4 usec per loop

$ python -m timeit -c '[ list(x) for x in zip(range(100), range(100)) ]'
10000 loops, best of 3: 99.9 usec per loop

A: Possible to use enumerate, as well:
[[y,airports[x]] for x,y in enumerate(cities)]

A: If you wanted to use list comprehension, and create a variable as a dictionary here is a decent way to do it:
newvariable = {key: value for key, value in zip(cities,airports)}


text:
Q: How to disable Bluetooth power saving? I've been using a Bluetooth keyboard with Ubuntu for years now. To begin with it was quite tricky to get it to pair, but for the last several releases it's been rock solid.
After updating to 20.04 (from 19.10) it still works great, but it has acquired a new feature in which the keyboard goes to sleep if I don't type anything for a while. I presume this is deliberate and meant to be an improvement, and it reconnects just fine when I do press a key, but it takes a few seconds and drops any key presses in the meantime, so it's annoying.
How can I go back to the old always-connected mode, please?

A: Maybe try this...
The comment in /etc/bluetooth/input.conf says it should already default to '0' so this shouldn't be needed, but explicitly setting IdleTimeout to 0 like this seems to have worked for me, I am using Ubuntu 20.04
sudo sed -i 's/#IdleTimeout=30/IdleTimeout=0/g' /etc/bluetooth/input.conf

A: just go on settings power and disable the button in which comp. can save power by disabling bluetooth
.
in my case it is on just disable it youcan take help from above


text:
Q: create lag variable of xts object using $ vs. [] notation I am trying to create a lagged vector within an xts object using the lag function. It works when defining the new vector within the xts object using $ notation (e.g. x.ts$r1_lag), but it does when defining the new variable using square brackets, i.e. xts[,"r1_lag"]. See code below:
library(xts)
x <- data.frame(date=seq(as.Date('2015-01-01'), by='days', length=100),
                runif(1e2), runif(1e2), runif(1e2))
colnames(x) <- c("date", "r1", "r2", "r3")

#the following command works
x.ts <- xts(x, order.by=x$date)
x.ts$r1_lag <- lag(x.ts$r1)
# but the following does not (says subscript is out of bounds)
x.ts <- xts(x, order.by=x$date)
x.ts[,"r1_lag"] <- lag(x.ts[,"r1"])

I need to use [] notation rather than $ notation to reference the vectors because if I want to run the lag transformation on vectors in more than one xts object (vectors within a list of multiple xts objects), I can't define the new vectors within the objects using $ notation, i.e. I cant define the new vectors using the notation in the below stylized loop:
for (i in letters) {
  for (j in variables) {
    macro.set.ts$i$paste(j,"_L1",sep="") <- lag(macro.set.ts[[i]][,j])
    macro.set.ts$i$paste(j,"_L2",sep="") <- lag(macro.set.ts[[i]][,j], 2)
    macro.set.ts$i$paste(j,"_L4",sep="") <- lag(macro.set.ts[[i]][,j], 4)
  }
}

Thanks!

A: You don't need to use [<-.xts. You can use merge instead:
for (i in letters) {
  for (j in variables) {
    # create all lags
    mst_ij <- macro.set.ts[[i]][,j]
    jL <- merge(lag(mst_ij), lag(mst_ij, 2), lag(mst_ij, 4))
    colnames(jL) <- paste(j, c("L1","L2","L4"), sep="_")
    # merge back with original data
    macro.set.ts[[i]] <- merge(macro.set.ts[[i]], jL)
  }
}

A: The error is not related to lag function. You get an error because you try assign an xts object with another xts object. This example reproduces the error :
x.date= seq(as.Date('2015-01-01'),
                        by = 'days' , length = 5)
x1 <- xts(data.frame(c1=runif(5)), order.by=x.date)
x2 <- xts(data.frame(c2=runif(5)), order.by=x.date)
x1[,'r2'] <- x2

## Error in `[<-.default`(`*tmp*`, , "r2",
##   subscript out of bounds

I find this is coherent within xts logic,  because xts are indexed objects. So it is better here to merge objects or join and conserve the indexed nature of your time series.
merge(x1,x2)

This will cbind the 2 times series and fix any index problem. in fact, cbind is just a merge:
identical(cbind(x1,x2),merge(x1,x2)

That's said I think it is a kind of bug that this works for $<- operator and not with [<- operator.

A: I got the same output with:
x.ts <- cbind(x.ts,lag(x.ts[,"r1"]))

And
x.ts <- transform(x.ts, r1_lag = lag(x.ts[,'r1']))

But, be careful with the output. It may look the same but with an altered structure.

A: This should work:
x.ts <- merge(x.ts,lag(x.ts[,"r1"]))

You will then probably want to rename the last column that was added:
dimnames(x.ts)[[2]][5] <- "r1_lag"

This is the result:
> head(x.ts)
           date         r1           r2           r3             r1_lag
2015-01-01 "2015-01-01" "0.23171030" "0.44174424" "0.3396816640" NA
2015-01-02 "2015-01-02" "0.97292220" "0.74909452" "0.2793033421" "0.23171030"
2015-01-03 "2015-01-03" "0.52320743" "0.49288463" "0.0193637393" "0.97292220"
2015-01-04 "2015-01-04" "0.36574297" "0.69571803" "0.6411834760" "0.52320743"
2015-01-05 "2015-01-05" "0.37563137" "0.13841216" "0.3087215754" "0.36574297"
2015-01-06 "2015-01-06" "0.48089356" "0.32702759" "0.3967609401" "0.37563137"

> class(x.ts)
[1] "xts" "zoo"

Hope this helps.


text:
Q: Trouble creating my own "zip" function in Python as a personal exercise I am trying to create my own little zip() function that takes two lists and puts the items into a list of tuples. In other words if these are  my list:
fr = [6,5,4]
tr = [7,8,9]

I would expect this:
[(6,7), (5,8), (4,9)]

Here is my code:
def zippy(x, y):
    zipper = []
    for i in x :
        for g in y:
            t = (i,g)
        zipper.append(t)

What I get is: [(6, 9), (5, 9), (4, 9)],
but when I define the lists inside of the function, it works as intended. Any help is appreciated.

A: Use indexes to access same-indexes items:
def zippy(x, y):
    zipper = []
    for i in range(len(x)):
        zipper.append((x[i], y[i]))
    return zipper

using list comprehension:
def zippy(x, y):
    return [(x[i], y[i]) for i in range(len(x))]

>>> fr = [6,5,4]
>>> tr = [7,8,9]
>>> zippy(fr, tr)
[(6, 7), (5, 8), (4, 9)]

A: Please consider that if you have two lists of different length your zip should stop when the shortest sequence ends. Here is an example of how to do it:
def zippy(x, y):
    iter1 = iter(x)
    iter2 = iter(y)
    while True:
        try:
            yield next(iter1), next(iter2)
        except StopIteration:
            return

or
def zippy(x, y):
    iter1 = iter(x)
    iter2 = iter(y)
    for _ in range(min(len(x), len(y))):
        yield next(iter1), next(iter2)

Also notice that standard zip function returns  (generator) and not a list of data! That means if you need to get data from your result you have to convert your zip result to list:
result = zippy(fr, tr)
print(list(result))

or call iterator on it
next(result)

A: I would suggest using range() to cycle through each index of the array.  Then, put them in a tuple and append them to the array.
def zippy(x, y):
    zipper = []
    for i in range(len(x)) :
        zipper.append((x[i],y[i]))
    return zipper

For more info on range(), go here.

A: You need to iterate both arrays at the same time to get the same indexes from both arrays
 def zippy(x, y):
        zipper = []
        for i,g in zip(x,y):
            t = (i,g)
            zipper.append(t)
        print(zipper)

Output
[(6, 7), (5, 8), (4, 9)]

A: # A zip() is a kind of map()!
def zippy(a, b):
  return map(lambda (i, a): (a, b[i]), enumerate(a))


text:
Q: With Julia Symbolics, how can I do a mathematical summation? I am using Symbolics.jl and I want to make a mathematical summation, equivalent to the function Sum from Sympy (https://docs.sympy.org/latest/modules/concrete.html)
The documentation of Symbolics.jl suggests that it is possible:

*

*Discrete math (representations of summations, products, binomial coefficients, etc.)

However, in the frequently asked questions, the opposite is suggested:

Loops are allowed, but the amount of loop iterations should not require that you know the value of the symbol x.

A: You can use +(x...) for a summation for a vector of symbols.
julia> @variables x[1:5]
1-element Vector{Symbolics.Arr{Num, 1}}:
 x[1:5]

julia> +(x...)
x[1] + x[2] + x[3] + x[4] + x[5]

julia> Symbolics.derivative(+(x...), x[2])
1

Beware of sum(x) as it seems to be not expanded and yields incorrect results:
julia> sum(x)
Symbolics._mapreduce(identity, +, x, Colon(), (:init => false,))

julia> Symbolics.derivative(sum(x), x[2])
0

Last but not least, make another step and define the summation symbol to get a nice experience:
julia> ∑(v) = +(v...)
∑ (generic function with 1 method)

julia> ∑(x)
x[1] + x[2] + x[3] + x[4] + x[5]

julia> Symbolics.derivative(100∑(x), x[2])
100

A: It extends Julia itself, so there really isn't much to document: just use Julia on the symbolic values. Thus here, just use sum, which is part of Base Julia.
julia> using Symbolics

julia> @variables x[1:5]
1-element Vector{Symbolics.Arr{Num, 1}}:
 x[1:5]

julia> x = collect(x)
5-element Vector{Num}:
 x[1]
 x[2]
 x[3]
 x[4]
 x[5]

julia> sum(x)
x[1] + x[2] + x[3] + x[4] + x[5]

"Loops are allowed, but the amount of loop iterations should not require that you know the value of the symbol x."

That's also a limitation of SymPy, or any other symbolic tracing system because  that restricts to symbolically-reprsentable (quasi-static) codes. This is discussed in more depth in this blog post.


text:
Q: Send Email with Intent: Allow only email programs that support attachments I'm trying to limit the program list presented to the user when sending an email with Intents in Android to ones that support sending an email with an attachment.
This is setup as follows; (sending an email with a pic attached)
   Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
   emailIntent.setType("message/rfc822");
   emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[] { "" });
   emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, EMAIL_SUBJECT);
   emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, Html.fromHtml(EMAIL_BODY));

   setupImageForSharing();
   Uri uri = Uri.fromFile(casted_image);
   emailIntent.putExtra(Intent.EXTRA_STREAM, uri);

   try {
      startActivity(Intent.createChooser(emailIntent, "Send Email."));
      if (mListner != null) {
         mListner.shared(true);
         mListner = null;
      }
   } catch (Exception ex) {

   }

This unfortunately still throws up programs such as Google Drive and ES File Explorer which do not support what is expected. How could we limit this list to programs that support sending an email with an attachment?
There are similar questions I've found listed below, but they do not quite answer my issue of filtering out programs which allow attachments:

*

*How to open Email program via Intents (but only an Email program)

*Send Email Intent


text:
Q: AngularJS class toggle on buttons I'm trying to toggle a class when a button is clicked. IE: if button 'rndTotal' is selected, class "selected" is added, and the other buttons have class "selected" removed. I also need this approach to work with my controller, as in, I will have stuff happen based on what is selected.
So far I have:

          <button ng-class="{selected:option=='exact'}">Exact</button>

          <button ng-class="{selected:option=='rndTip'}">Round Tip</button>

          <button ng-class="{selected:option=='rndTotal'}">Round Total</button>

It defaults to 'exact' but doesn't function other than that.

A: This feels like a hack, but to accomplish what you're after you could do this:

        <button ng-class="{selected:option=='exact'}" ng-click="option='exact'">Exact</button>

        <button ng-class="{selected:option=='rndTip'}" ng-click="option='rndTip'">Round Tip</button>

        <button ng-class="{selected:option=='rndTotal'}" ng-click="option='rndTotal'">Round Total</button>

Update
Instead of setting model values directly in the markup like this, I would move to using a controller. In order to do that I would make the following changes:
Controller
.controller('myController', function() {
    var vm = this;
    vm.selectedOption = 'exact';
    vm.selectOption = function(option) {
        vm.selectedOption = option;
        // do anything else you may need to do when the selected option changes
    };
});

Markup:

            <button ng-class="{selected:vm.selectedOption==='exact'}" ng-click="vm.selectOption('exact')">Exact</button>

            <button ng-class="{selected:vm.selectedOption==='rndTip'}" ng-click="vm.selectOption('rndTip')">Round Tip</button>

            <button ng-class="{selected:vm.selectedOption==='rndTotal'}" ng-click="vm.selectOption('rndTotal')">Round Total</button>


text:
Q: jQuery: JSON value not displaying correctly I'm building a 'Name That Tune' web app using the iTunes API. I submit a search request to iTunes and get back a JSON object. I then store the previewURL (the song snippet) and trackName (song name). I use the trackName to check if the user submitted the correct guess and I use it to display the song name on the UI when the guess is wrong so user knows what the correct answer was.
Issues:
1. When displaying the song name on the UI it displays as [object object]. However, it displays on the console correctly - i.e. it shows the song name. In my example, the song is 'backroads'.
2. The function that checks if the guess was correct is not working. Every guess, even the correct ones, are shown as incorrect..which I guess I would expect given issue #1.
See attachment.
Things I tried:
1. Searching for other similiar issues but didn't find anything that was right.
2. Used a toSTring on the variable. Same bad results.
3. Passed the songName into the 2nd function as a parameter.
Below is JS code in question.
// when user clicks Play get song preview from iTunes and play, show songguess and hide genresection
$("button#playSong").click(function(){

    $('.genreSection').hide();
    $('#guessFields').show();

    // get genre user selected
    var genreSelected = $('input[type="radio"]:checked').val();
    console.log("Genre selected is: "+genreSelected);

    // get song for genre selected
    $.post("https://itunes.apple.com/search?kind=song&limit=1&term="+genreSelected,

    // Get song preview url and define to audio source 'src' to play the song preview
    function(data){
        console.log(data);

        // get song name
        var songName = data.results[0].trackName;
        console.log("Song name is: "+songName);

        $("#songAudio").attr("src",data.results[0].previewUrl);
        $("#audioCtrl")[0].load();
        $("#audioCtrl")[0].play();
        },
    'json');  // identifies the format of the data returned
});

// when user submits guess
$("button#guessSong").click(function(songName){

        // get countdown seconds remaining

        // if countdown is less than 1, hid submit button and display message "too late"

        // get value of song guess
        var songGuess = $("#songGuess").val();
        console.log("Song guess is: "+songGuess);

    // hide input field and button
        $('#guessFields').hide();

        // check if guess is correct
        if(songGuess === songName) {

            // increment correct guess counter
            correctGuessCounter++;
            console.log("Correct guess counter is "+correctGuessCounter);

            // display you are correct message
            $("#results").html("Correct! Your points for that guess are "+correctGuessCounter);

        }else {

            //convert songname to string
            songName = songName.toString();

            // display you are correct message
            $("#results").html("Sorry, wrong answer. The correct song name is "+songName+".");
        }

A: songName in your second click function is a parameter to the function. Since it's a click event, the value of songName will be an event object, not a song name.
I'm not sure how you intend to store the song name, but you might want to store it in a variable or something, outside the scope of the click functions so that both of them can see it.
Declare songName up above both functions:
var songName;

// when user clicks Play get song preview from iTunes and play, show
// songguess and hide genresection
$("button#playSong").click(function(){

Make sure to remove var from songName on the assignment line, or else it will hide the songName from above.
   // Get song preview url and define to audio source 'src' to play the song preview
   function(data){
      console.log(data);

      // get song name
      songName = data.results[0].trackName;
      console.log("Song name is: "+songName);

Make sure to remove songName from the parameter list, or else it too will hide the outer one.
// when user submits guess
$("button#guessSong").click(function(){

   ...

   // check if guess is correct
    if(songGuess === songName) {

      ...


text:
Q: how to integrate oauth 1.0 with laravel 8 I am trying to integrate Oauth 1.0 with laravel 8, I am new to oauth integration. I have taken this site for reference. https://github.com/jenssegers/laravel-oauth
on adding the providers  I am getting an error as

Call to undefined method bindShared().

below is my code.
'providers' => [
        'Jenssegers\OAuth\OAuthServiceProvider',
    ],

    'aliases' => [
        'OAuth' => 'Jenssegers\OAuth\Facades\OAuth',
    ],

Anyone, please help me how to integrate oauth 1.0 with laravel. Anyone please tell me the process how to integrate, I am unable to find any other references to complete my task.

A: please update your package from composer json to the latest version
"jenssegers/oauth":"2.0.2"

and update the composer with
composer update

the issue is that the package not updated from long time and it used bindShared but the laravel framework renamed it with $app->singleton()
try an alternative package because the maintainer don't update it for long time


text:
Q: Use iterrows in pandas to find mismatches between strings, bug I have the following pandas Dataframe in Python3.5:
import pandas as pd
df = pd.Dataframe(...)
print(df)

which outputs
string1        string2
'abcdefg...'   'abcSefg...'
'Iknowhow...'  'Eknowhow...'
'Thecatis...'  'Thekatis...'
...

I first wanted to find the location of mismatches between string1 and string2 and append this to the Dataframe df. I use this code:
df["different_positions"] = [[i for i in range(len(row.string2))
    if row.string1[i] != row.string2[i]] for _, row in df.iterrows()]

That will give me all the positions were mismatches occur. Now, I would like a separate column which outputs each letter of the mismatch. For example, in string2, there is an S instead of a d in the first row, an E instead of I in the second row, etc.
I thought the code would be
df["different_letters"] = [[i for i in row.string2
    if row.string1[i] != row.string2[i]] for _, row in df.iterrows()]

However, it appears this isn't correct. I get a NameError at for _, row, i.e.
NameError: name 'i' is not defined

How do I output the mismatched letter to correspond to the mismatched position?

A: String iteration returns characters, not indices. In other words, i for i in row.string2 will go through the characters of row.string2, not the corresponding indices.
So
df["different_letters"] = [[i for i in row.string2
if row.string1[i] != row.string2[i]] for _, row in df.iterrows()]

is incorrect because you're effectively asking what row.string1['a'] is if row.string1 contains an a. String indices must be integers.
Instead, you want to do
df["different_letters"] = [[j for i, j in enumerate(row.string2)
if row.string1[i] != row.string2[i]] for _, row in df.iterrows()]

enumerate lets you iterate through both the index and the corresponding element in an iterable. Here, j is the corresponding character, i is its index, and you can now compare by index but only return the corresponding character.


text:
Q: what does the "()" do within an rank statement Just curious what the "()"'s do in "rank ()" statements and how I can apply them.
for example the following is a standard rank query but I have never populated "()" just the brackets after "OVER" keyword and am curious what it's purpose is?
SELECT RANK() OVER (ORDER BY col1 DESC)
FROM DUAL;

A: RANK() is a function that takes no arguments.
Calling a function (generally) requires the parentheses.  They simply indicate that it is a function call.  In this case, the function requires the rest of the window frame, so OVER is required.


text:
Q: How to do Low Level Format (Hard Format) for a Laptop HardDrive I have 2 questions

*

*Can we know weather a Hard Drive has
done Low Level format or not.
Somehow using a tool ?

*How to do Low Level Format (Hard Format) for a        Laptop HardDrive

A: You can't really do a 'proper' oldschool low level format with modern drives - they require specialised software, and it only really needs to be done once, at the place its made.
You can however wipe the drive with dban - with modern drives a single pass is often enough, DOD recommends 7 passes, and the guttmann method basically runs every possible wiping algorithm for pretty much every sort of drive ever made.
Depends on how much time you're willing to spend.
more info here if you are into the science of it.

A: With Low-Level you mean to overwrite the drive with zeros or random data?
For Question 2: You can do this with every Linux Live CD and the dd command. Something like

$ dd if=/dev/zero of=/dev/sdX

should do the trick. Alternatively you can use a specialised distribution like DBAN.

A: You can check content of the hard drive with hexdump. Actual destroying data with dd mentioned above or with shred.

A: If you want data security, buy an industrial shredder.  All sorts of interesting forensic techniques can be applied to hard drives of all types to retrieve data you "thought" was gone.


text:
Q: Qt Application crashes X session (QDialog) under Gnome/Fedora I wrote a tiny little Qt4 (C++) application, that doesn't really do much except display a list.
It's a QDialog, so pressing escape will close it.
Now, if I do this (run, then close) for about 3 - 8 times in a row, my X session crashes and I get my login screen.
This does not happen if I kill my program instead of closing it gracefully.
Naturally, I looked through my code, especially the code that's executed when exiting. However, that's only one tiny little destructor, which deletes some variables that have been previously allocated. Commenting those lines out (-> no more code to be executed when exiting) doesn't change anything. Calling QApplication::exit() will crash as well.
I'm currently using Gnome on this dev system, if that matters.
I don't really know what to look for.
Any ideas?
Edit:
Trying to find the culprit, I've commented out code, piece by piece. However, I've now basically deleted EVERYTHING except for the code that shows the QDialog and the crashes still happen.
Here's the code:
main.cpp
#include <iostream>

#include <QApplication>
#include <QDialog>

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    return QDialog().exec();
}

As you can see, this program does NOTHING (except show a QDialog, but that's Qt, not my program). I don't get how 2 lines of code (+ the Qt code, which should work, since millions of people use it everyday) can crash my X session. So far, I've tested it on Fedora 16 with Gnome 3 only.
Edit2: Tested it (same binary) on the same system with KDE and LXDE, no crash. Also on Ubuntu with Gnome, KDE and LXDE, no crash. Has to have something to do with Gnome3/Fedora...


text:
Q: Delegate Command - WPF Button Binding Not Working I am doing a simple test and can't seem to get the button binding to work correctly. I am trying to simply disable a button based on the value of a textbox. In this example, if the value of the textbox = 1 the button needs to be disabled. Although I have Prism installed for this example, I still couldn't get it to work correctly by directly implementing IPropertyNotifyChanged.
public class LoginModel : BindableBase
{
    private string _username;

    public string Username
    {
        get { return _username; }
        set { _username = value; RaisePropertyChanged(); }
    }

}

public class LoginViewModel : BindableBase
{
    private LoginModel _model;

    public LoginModel Model
    {
        get { return _model; }
        set { _model = value; RaisePropertyChanged(); }
    }

    public DelegateCommand ButtonTest { get; private set; }

    public LoginViewModel()
    {
        _model = new LoginModel { Username = "test" };
        ButtonTest = new DelegateCommand(Click, CanClick);
    }

    private void Click()
    {
        MessageBox.Show(_model.Username);
    }

    private bool CanClick()
    {
        if (_model.Username == "1")
        {
            return false;
        }
        return true;
    }

LoginView.xaml
    <Grid>
        <StackPanel>
            <TextBox Height="25" Width="100" Text="{Binding Path=Model.Username, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
            <Button Height="25" Width="100" Content="Click Me" Command="{Binding Path=ButtonTest}"/>
        </StackPanel>
    </Grid>

The textbox binding is correctly working and the CanClick() method correctly returns false if _model.Username == "1" however how can I get the UI to update to correctly disable the button?


text:
Q: Using alias to simplify clone I want to create an alias that looks something like this:
alias getres="git clone https://github.com/user/"

The goal is that i can type "getres repository name" and get the the repository.
However as it stands now,
typing "getres repository name"
Gives me an error saying the repostiory can't be found.

A: This happens because getres repository name gets translated to:
git clone https://github.com/user/ repository name

which means you have a space character between https://github.com/user/ and repository name which completely mess with your URL.
The solution for your problem is to create a bash script which accepts 1 parameter (the repository name) then use that script in your alias.
see Make a Bash alias that takes a parameter?

A: What you're after is just a bit beyond the reach of aliases, which are good only for the simplest cases. You want a shell function for this, getres() { git clone https://github.com/user/$*; }

A: I have just had this same problem.
For users using zsh / oh-my-zsh / iterm2 (1,2,3)
I updated my .zshrc file with the following:
function getrep(){
    git clone https://github.com/USERNAME/$1.git
}

I added the ".git" at the end because I'm lazy.
Use case is just "getrep REPNAME" from the terminal to clone into whatever current folder you are using.
(1) https://www.zsh.org/
(2) https://ohmyz.sh/
(3) https://iterm2.com/


text:
Q: bad file descriptor in posix mqueue Anybody could please help me to resolve the issue of bad file descriptor in posix mqueue. I am trying to read RAW socket packets and to place them in mqueue.
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<mqueue.h>
#include<netinet/ip_icmp.h>
#include<netinet/udp.h>
#include<netinet/tcp.h>
#include<netinet/ip.h>
#include<netinet/if_ether.h>
#include<net/ethernet.h>

#define QUEUE_NAME  "/test_queue"
#define MAX_SIZE    71680

#define CHECK(x) \
    do { \
        if (!(x)) { \
            fprintf(stderr, "%s:%d: ", __func__, __LINE__); \
            perror(#x); \
            exit(-1); \
        } \
    } while (0) \

int main(int argc, char **argv)
{
    mqd_t mq;
    struct mq_attr attr;
    char buff[MAX_SIZE + 1];
    unsigned char* buffer = (unsigned char*) malloc(sizeof(65536));
    int saddr_size , data_size,sock_raw;
    struct sockaddr saddr;

    /* initialize the queue attributes */
    attr.mq_flags = 0;
    attr.mq_maxmsg = 10;
    attr.mq_msgsize = MAX_SIZE;
    attr.mq_curmsgs = 0;

    /* create the message queue */
    mq = mq_open(QUEUE_NAME, O_CREAT | O_RDONLY, 0644, &attr);
    CHECK((mqd_t)-1 != mq);

    sock_raw = socket( AF_PACKET , SOCK_RAW , htons(ETH_P_ALL)) ;
    if(sock_raw < 0)
    {
       perror("Socket Error\n");
       return 1;
    }
    saddr_size = sizeof saddr;
    data_size = recvfrom(sock_raw , buffer ,65536 , 0 , &saddr , (socklen_t*)&saddr_size);

    if(data_size <0 )
    {
       printf("Recvfrom error , failed to get packets\n");
       return 1;
    }

    memcpy(buff,buffer,65536);

    CHECK(0 <= mq_send(mq, buffer, MAX_SIZE, 0));

    printf("Msg sent");

    CHECK((mqd_t)-1 != mq_close(mq));

    return 0;
}

Output which I got is
main:64: 0 <= mq_send(mq, buffer, MAX_SIZE, 0): Bad file descriptor

A: You are attempting to write (mq_send) to a message queue descriptor you opened read-only (O_RDONLY).
Change your oflags argument to O_CREAT | O_RDWR and the send will work.
The Linux man page doesn't call this out, but others do:  EBADF can mean the fd or fd-like handle is wholly invalid, or that it is invalid for the requested operation.


text:
Q: IOS app crashes after launch with testflight I have seen a few similar questions but nothing to help me resolve my issue.
My app works when built in debug mode. It works via testflight on devices running iOS 11+. We support iOS 9 and above, so when i get the app via testflight on an app running iOS 9 the app instantly crashes. I find it unusual that this would run fine on a newer version of the OS but fail on the older version.
I understand that this is a pretty broad question. I presumed it would be an issue with certificates but if that was the case i would expect to see the same issue on each OS version. I have compiled the app for release and ran it on a device to replicate the issue which it does. In the device logs i can see the error.

Attempt to add an app with insufficient id, info

Again i understand i haven't been able to give much information on this error, but i am hoping someone has been in a similar situation and can give me some pointers.


text:
Q: Program name in argv[0] I read that argv[0] holds the program name i.e. the name by which we save the project....
but when I execute the following statement in my objective C command line program
const char *proName=argv[0];

i see the following in the console:
/Users/apple/Library/Developer/Xcode/DerivedData/testaehcfzilirskhjbifrwresgppvbp/Build/Products/Debug/test

here test is the name of my program....
so what does it give...full path or program name?
Thanks

A: As you've noticed, argv[0] can (but doesn't always) contain the full path of your executable. If you want the file name only, one solution is:
#include <libgen.h>

const char *proName = basename(argv[0]);

As noted by Mat, argv[0] is not always reliable — although it should usually be. It depends on what exactly you're trying to accomplish.
That said, there's an alternative way of obtaining the name of the executable on Mac OS X:
#include <mach-o/dyld.h>
#include <libgen.h>

uint32_t bufsize = 0;

// Ask _NSGetExecutablePath() to return the buffer size
// needed to hold the string containing the executable path
_NSGetExecutablePath(NULL, &bufsize);

// Allocate the string buffer and ask _NSGetExecutablePath()
// to fill it with the executable path
char exepath[bufsize];
_NSGetExecutablePath(exepath, &bufsize);

const char *proName = basename(exepath);

A: You can't depend on argv[0] containing something specific. Sometimes you'll get the full path, sometimes only the program name, sometimes something else entirely.
It depends on how the code was invoked.


text:
Q: Sum only certain rows in a given column of pandas dataframe I can sum the first 310 rows in a 5 column pandas dataframe and get a tidy summary by using:
df.[0:310].sum

Is there an easy way whereby I can sum the first 310 rows in a certain column of my choosing?  I just can't figure out how to combine a column selection and row slice selection in the expression.  It would be ideal to specify the column by column name, but column index is fine too.
In an attempt to sum the 1st 310 rows of the 5th column, I tried
df.iloc[0:310, 4].sum

but just got a printout of 310 rows from that column. Thank you.

A: I think need DataFrame.iloc for select rows by positions with get_indexer for positions of columns by names:
#data borrowed from Akshay Nevrekar answer, but changed index values
data = {'x':[1,2,3,4,5],
        'y':[2,5,7,9,11],
        'z':[2,6,7,3,4]}
df=pd.DataFrame(data, index=list('abcde'))
print (df)
   x   y  z
a  1   2  2
b  2   5  6
c  3   7  7
d  4   9  3
e  5  11  4

a = df.iloc[:3, df.columns.get_indexer(['x','z'])].sum()

What is same as:
a = df.iloc[:3, [0,2]].sum()

print (a)
x     6
z    15
dtype: int64

Detail:
print (df.iloc[:3, df.columns.get_indexer(['x','z'])])
   x  z
a  1  2
b  2  6
c  3  7

If want only one column use get_loc for position:
b = df.iloc[:3, df.columns.get_loc('x')].sum()

What is same as:
b = df.iloc[:3, 0].sum()

print (b)
6

Detail:
print (df.iloc[:3, df.columns.get_loc('x')])
a    1
b    2
c    3
Name: x, dtype: int64

A: You need something like this:
import pandas as pd
data = {'x':[1,2,3,4,5], 'y':[2,5,7,9,11], 'z':[2,6,7,3,4]}
df=pd.DataFrame(data)

Use list of columns along with rows:
df.loc[0:310][['x','z']].sum()

output:
x    15
z    22
dtype: int64


text:
Q: Converting Raster to Vector? I'm currently in the process of writing a code snippet that converts a raster image to a vector image without using any tracing method by using fill. It works but the size of the out put can become quite large(160 MB) for 960px * 800px image. Looking for someone who may be able to give me an idea how we can build some sort of an array of positions that contains the same colors within each corresponding fill blocks. I've checked google with no luck. Here is what the code snippet looks like.
public static unsafe void SaveVector(this Image @this, Stream outputStream)
{

  int PixelSize = 4;
  Rectangle rect = new Rectangle(new Point(0,0), @this.Size);
  using(StreamWriter SvgWriter = new StreamWriter(outputStream))
  {
    using(Bitmap bitmap = new Bitmap(@this))
    {
      BitmapData bitmapData = bitmap.LockBits(rect, ImageLockMode.ReadOnly,PixelFormat.Format32bppArgb);
      SvgWriter.WriteLine("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>");
      SvgWriter.WriteLine("<svg");
      SvgWriter.WriteLine("   xmlns:svg=\"http://www.w3.org/2000/svg\"");
      SvgWriter.WriteLine("   xmlns=\"http://www.w3.org/2000/svg\"");
      SvgWriter.WriteLine(string.Format("   width=\"{0}\"", @this.Width));
      SvgWriter.WriteLine(string.Format("   height=\"{0}\"", @this.Height));
      SvgWriter.WriteLine("   id=\"svg2\"");
      SvgWriter.WriteLine("   version=\"1.1\">");
      SvgWriter.WriteLine("  <defs");
      SvgWriter.WriteLine("     id=\"defs4\" />");
      SvgWriter.WriteLine("  <metadata");
      SvgWriter.WriteLine("     id=\"metadata7\" />");
      SvgWriter.WriteLine("  <g");
      SvgWriter.WriteLine("     id=\"layer1\">");
      int num = 0;
      for(int y = 0; y < bitmapData.Height; y++)
      {
        byte* row=(byte *)bitmapData.Scan0+(y*bitmapData.Stride);
        for(int x = 0; x < bitmapData.Width; x++)
        {
          SvgWriter.WriteLine("    <rect");
          SvgWriter.WriteLine(string.Format("       style=\"fill:{0};fill-opacity:1;stroke-width:0.43599999000000000;stroke-miterlimit:4;stroke-dasharray:none\"",
            ColorTranslator.ToHtml(Color.FromArgb(
              row[(x * PixelSize) + 3],
              row[(x * PixelSize) + 2],
              row[(x * PixelSize) + 1],
              row[x * PixelSize]))));
          SvgWriter.WriteLine(string.Format("       id=\"rect{0}\"", num));
          SvgWriter.WriteLine("       width=\"1\"");
          SvgWriter.WriteLine("       height=\"1\"");
          SvgWriter.WriteLine(string.Format("       x=\"{0}\"", x));
          SvgWriter.WriteLine(string.Format("       y=\"{0}\" />", y));
          num++;
        }
      }
      bitmap.UnlockBits(bitmapData);
    }
    SvgWriter.WriteLine("  </g>");
    SvgWriter.WriteLine("</svg>");
  }
}


text:
Q: dyld: Library not loaded: /usr/local/opt/gcc/lib/gcc/9/libquadmath.0.dylib I am trying to solve a dynamic programming problem using GEKKO. The gekko object uses a solve method which references an executable /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/gekko/bin/apm_mac
This executable in turns wants to access a library /usr/local/opt/gcc/lib/gcc/9/libquadmath.0.dylib and apparently it's not able to find the library, thus the error:
Error: dyld: Library not loaded: /usr/local/opt/gcc/lib/gcc/9/libquadmath.0.dylib
Referenced from: /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/gekko/bin/apm_mac
Reason: image not found

When I go to the path: /usr/local/opt/, there is no gcc folder there which explains the error. But how should I fix this?


text:
Q: How to prevent pandas pivot from discarding other columns that are not in the pivot? I have a df that looks like this:
id   FieldTitle  Value  number
1     fname       aaa    12
2     lname       bbb    12

When I run this line of code:
pivoted_df = pd.pivot_table(df, index='Id', columns='FieldTitle', values='Value', aggfunc='first').reset_index()

The df that is left is:
fname    lname
aaa        bbb

Why is pivot causing the other columns to disappear and how do I fix it?
The df should look like this:
id   fname  lname  number
1     aaa    bbb    12

A: I've tried to reproduce your example here, I think adding static columns to the index will solve your issue
df = pd.DataFrame({"id":[1,2], "FieldTitle":["fname", "lname"], "Value":["aaa", "bbb"], "number":[12,12]})
pivoted_df = pd.pivot_table(df, index=["number"], columns='FieldTitle', values=['Value'], aggfunc='first').reset_index()

You may then need to rename the columns as you'll have a multi-index.
Alternatively consider pivoting, dropping duplicate columns from your original dataset and then merging back together with the result


text:
Q: Is the PK of a DB2 table a clustered index by default? This can be a silly question but I want to be sure 100%.
Is the PK of a DB2 table a clustered index by default?

A: From: DB2 docs - Clustering indexes

Although a table can have several indexes, only one index can be a clustering index. If you do not define a clustering index for a table, DB2 recognizes the first index that is created on the table as the implicit clustering index when it orders data rows.

So no, by default the Primary Key is NOT the clustered index of the table.
The first created index, unique or not, is the "implicit" clustering index and DB2 tries to insert the records as nearly as possible in the order of the values of this index.
If you later create another index and identify it as clustering, then DB2 identifies it as the clustering index but does not rearrange the data that is already in the table. This can be done with the REORG utility.

A: From the Publib (this assumes DB2 for z/OS, version 9)

When a table has a clustering index, an INSERT statement causes DB2 to
  insert the records as nearly as possible in the order of their index
  values. The first index that you define on the table serves implicitly
  as the clustering index unless you explicitly specify CLUSTER when you
  create or alter another index. For example, if you first define a
  unique index on the EMPNO column of the EMP table, DB2 inserts rows
  into the EMP table in the order of the employee identification number
  unless you explicitly define another index to be the clustering index.

You can see which index is the clustering index for a table (in this example, TEST.TABLE1) using the following query, if you're on z/OS:
SELECT NAME
FROM SYSIBM.SYSINDEXES
WHERE TBCREATOR  = 'TEST'
  AND TBNAME     = 'TABLE1'
  AND CLUSTERING = 'Y'

And this one for Linux/Unix/Windows (LUW):
SELECT *
FROM SYSCAT.INDEXES
WHERE TABSCHEMA = 'TEST'
  AND TABNAME   = 'TABLE1'
  AND INDEXTYPE = 'CLUS'

A: DB2 doesn't create clustered index for a PK by default.

Primary keys
A primary key is a special type of unique key and cannot contain null values. For example, the DEPTNO column in the DEPT table is a primary key.
A table can have no more than one primary key. Primary keys are optional and can be defined in CREATE TABLE or ALTER TABLE statements.
The unique index on a primary key is called a primary index. When a primary key is defined in a CREATE TABLE statement or ALTER TABLE statement, DB2 automatically creates the primary index if one of the following conditions is true:
DB2 is operating in new-function mode, and the table space is implicitly created.
DB2 is operating in new-function mode, the table space is explicitly created, and the schema processor is running.
DB2 is operating in conversion mode, and the schema processor is running.
If a unique index already exists on the columns of the primary key when it is defined in the ALTER TABLE statement, this unique index is designated as the primary index when DB2 is operating in new-function mode and implicitly created the table space.

See at: Keys DB2


text:
Q: Mule Batch application throws org.mule.module.launcher.DeploymentInitException: ClassNotFoundException: org.mule.api.process.ProcessAdapter I am trying to run Mule Batch Code and getting below error when mule is trying to start an application:

org.mule.module.launcher.DeploymentInitException: ClassNotFoundException: org.mule.api.process.ProcessAdapter.

Which jars or mule module I am missing for org.mule.api.process.ProcessAdapter?
Is this enterprise license issue?
I am tried my mule code in both in mule studio and mule standalone but getting the same error.
Please provide input.

A: After backtracking to various versions (and actually downloading jar from each iteration from this https://repository.mulesoft.org/nexus/content/repositories/releases/org/mule/tools/devkit/mule-devkit-annotations/) I could find the class(actually an abstract interface) you are referring to in the mule-devkit-annotations but the last iteration that included the org.mule.api.process was 3.3.2 and it was dropped after 3.4.0
In mule-devkit-annotations-3.3.2:
public abstract interface ProcessAdapter<O>
{
  public abstract <T> ProcessTemplate<T, O> getProcessTemplate();
}
However, I could find the same Interface in mule-module-devkit-support.jar (I was using 3.6.1)
In mule-module-devkit-support-3.6.1.jar:
public interface ProcessAdapter<O>
{
    <T> ProcessTemplate<T, O> getProcessTemplate();
}


text:
Q: Add empty header or footer on ListView programmatically I am trying to add empty header or footer on ListView to create a space between top and bottom ListView. I could create another empty layout and add into it. But I'm try to find alternative in coding, create for example linear/frame layout with width (fill_parent) and height (say, 50dp) and add header into ListView.

A: you may do it in this way:
LinearLayout viewHeader = new LinearLayout(context);
viewHeader.setOrientation(LinearLayout.HORIZONTAL);
LayoutParams lp = new LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, 50);
viewHeader.setLayoutParams(lp);

yourListView.addHeaderView(viewHeader, null, false);


text:
Q: Firebase Grouping of Users I am making an Android app in which I am authenticating the users with their phone numbers in Firebase. I want to make the app work like this: If a user wants to make a group (like in Whatsapp) with the existing users, he/she can select the users (by entering the phone number) and create a group.
I need to know how can I map the relation between users and groups in Firebase?

A: Simply like this:
Firebase-root
   |
   --- users
   |     |
   |     --- uid
   |          |
   |          --- userName: "John"
   |          |
   |          --- emailAddress: "John@email.com"
   |          |
   |          --- phoneNumber: 0123456789
   |          |
   |          --- groups
   |                |
   |                --- groupIdOne: true
   |                |
   |                --- groupITwo: true
   |
   --- groups
         |
         --- groupId
              |
              --- groupName: "My Group"
              |
              --- users
                   |
                   --- uidOne: true
                   |
                   --- uidTwo: true

Using this schema, you can query the database to display all users, all groups, all groups a user is apart and all users from a particular group.

A: It's Simple create a node group inside it create nodes for groups with user ids
for example
group
   user_1_group
         user_2
         user_3
         user_4
         ....

   user_2_group
         user_5
         user_6
         user_7
         ....

You just need to put user id's in that then you can access user info by their id's.


text:
Q: Modify the default website in IIS 6.0 I have IIS installed on a server.
It is currently on the intranet as http://mySite which has a few basic html pages that load when you go to that URL
I've made a virtual directory called MyWebApp, which sits at http://mySite/MyWebApp
How do I go about making MyWebApp the default site when you type mySite into the browser?
I don't want it to come up as mySite/MyWebApp when you visit the page either.. I just want it to always say mySite.

A: Wouldn't it just be simpler to build your app in your root directory?  However, you can change the root directory of your IIS6 website by:
To change the home directory of a Web site using IIS Manager

*

*In IIS Manager, expand the local computer, expand the Web Sites directory, right-click the Web site you wish to change, and click Stop.

*Use Windows Explorer, to rename the LocalDrive:\Inetpub\Wwwroot directory to the name of your choice. Alternatively, you can copy the entire \Wwwroot directory tree to a new location.


text:
Q: Maintaining the display of a dataframe in Streamlit I have a problem, I use buttons to make some computing and displaying dataframes, I press the first button to display my first dataframe and when I press the second button, my second dataframe is shown but my first disappears. I want to maintain the display of my first dataframe (and all those before)....
A code example :
import streamlit as st
import pandas as pd

st.subheader("Test")

df_first = pd.DataFrame({"col1": [1, 2, 3, 1, 2, 3], "col2": [4, 5, 6, 4, 5, 6]})
df_second = pd.DataFrame({"col1": [100, 200, 300], "col2": ["www.google.com", "www.facebook.com", "www.youtube.com"]})

button_first = st.button("Display first")
if button_first :
    st.write(df_first)

button_second = st.button("Display second")
if button_second:
    st.write(df_second)

Anybody know how to proceed  ?
Thanks !

A: The concept of streamlit is to run the script from top to bottom when there is a user interaction with widget. So when you first press the first button it will rerun from top to bottom and show the first frame. But when you press the second button, it will rerun from top to bottom again and will not show the first frame but will show the second frame.
You can use st.checkbox() to get your desired behavior because a checkbox once checked is always checked and the first frame will always be shown when you press the second button.
You can also use a session state and callback.
import streamlit as st
import pandas as pd

if 'button_1' not in st.session_state:
    st.session_state.button_1 = False
if 'button_2' not in st.session_state:
    st.session_state.button_2 = False

def cb1():
    st.session_state.button_1 = True
def cb2():
    st.session_state.button_2 = True

st.subheader("Test")

df_first = pd.DataFrame({"col1": [1, 2, 3, 1, 2, 3], "col2": [4, 5, 6, 4, 5, 6]})
df_second = pd.DataFrame({"col1": [100, 200, 300], "col2": ["www.google.com", "www.facebook.com", "www.youtube.com"]})

st.button("Display first", on_click=cb1)
if st.session_state.button_1:
    st.write(df_first)

st.button("Display second", on_click=cb2)
if st.session_state.button_2:
    st.write(df_second)


text:
Q: Solve this Diophantine equation $(2^x-1)(3^y-1)=2z^2$
Find the positive integers $(2^x-1)(3^y-1)=2z^2$ have three solutions
$$(1,1,1),(1,2,2),(1,5,11)$$I already know $(2^x-1)(3^y-1)=z^2$ has no solution. See: P.G.Walsh December 2006 [On Diophantine equations of the form] paper but there is a factor of $2$ that seems complicated, and I didn't know anyone had studied this before. If so, please help me with the article or link, thanks.

A: I don't have a solution but since we're facing a narrow margins situation I'll answer. I followed the approach I guessed Gerhard Paseman's comment was talking about but there was an unforeseen complication.
If $\gcd(2^x-1,3^y-1)=1$ we have
$$2^x-1=p^2$$
$$3^y-1=2q^2$$
for integers $p,q$. We can factor the first one in $\mathbb{Z}[i]$
$$(-i)^x(1+i)^{2x}=(p+i)(p-i)$$
the two factors on the right hand side have the same modulus so they both must be a unit times $1+i$
$$p+i=u_1(1+i)^x$$
$$p-i=u_2(1+i)^x.$$
Then
$$2i=(u_1-u_2)(1+i)^x$$
we have unique factorization so the power of $1+i$ on the right hand side has to match the one on the LHS so $x\leq 2$. $x=2$ doesn't work mod 3 so we have $x=1$.
Now splitting into three cases for each residue of $y\mod 3$:

*

*$y=3w$
Then
$$w^3=2z^2+1$$
and to transform into an elliptic curve $w=w_1/2$ and $z=z_1/4$
$$z_1^2=w_1^3-8.$$
This is a Mordell curve so we can just look up the results. Bennet and Ghadermarzi have a table with all these solutions and looking up this and the other two cases, which turn out to have coefficients $-72$ and $-648$, we find that the three are the only solutions.
Now if $\gcd(2^x-1,3^y-1)\neq1$. I couldn't solve this case, but when $\gcd(x,y)=1$ I found some really weird behavior which made me think solving it in general might be harder than expected because it involves a relationship between $\text{ord}_p(2)$ and $\text{ord}_p(3)$. If a prime $p$ divides both sides of the gcd we have
$$2^x\equiv 3^y\equiv 1\mod p$$
$$\gcd(\text{ord}_p(2),\text{ord}_p(3)) = 1$$
This is relatively fast to calculate on a computer so I was able to find that $p=683,599479$ are the only possibilities under $10^9$. This is now OEIS sequence A344202, where you'll find 6 more terms which means mathematica has a faster way of calculating these than I do.
I feel like the $\gcd(x,y)\neq 1$ case might simplify to the previous one, but ruling out the few primes that satisfy the condition about the multiplicative orders of two and three will be difficult. For both of the primes I found we have $\text{ord}_p(2)\text{ord}_p(3)=p-1$ and there exists an unique element $r$ in $\mathbb{Z}_p$ so that $r^{\text{ord}_p(2)}\equiv 3$ and $r^{\text{ord}_p(3)}\equiv 2$. For $p=683$ it was $r\equiv 218$ and for $p=599479$, $r\equiv 45077$.


text:
Q: How to open an android device on Ubuntu 19.04? I am trying to connect a Samsung Galaxy A8 on my Ubuntu laptop. Despite, after several attempts, I managed to open the files on the device, the interface us extremely slow.
Do you have any advice on it? Can it be the brand of the cable (not the Samsung original one)
Best
Giulio

A: The cable might make a difference but don't quote me on it. I have a Samsung J5 and I too find it slow when connecting so I think it's more to do with the phone than any issue with your operating system.  Mine is just as slow when I'm connected to a Windows PC or laptop.
One thing that can be quicker is if you have the files you want to view or edit on a micro SD card. Just unmount it from the phone, slot it into a suitable adapter and plug it straight into your laptop.


text:
Q: jQuery interfering with CSS Background Image Position? I am having problems positioning my background images to the "bottom". When I try to set its position to bottom, it actually moves my image even further up the top so that the upper portion is cut off. I was searching for what might be causing this and saw someone mentioned that "jQuery was setting bottom to 0". (Found here actually)
This is occurring even on this simple test editor and has left me at a loss as to what to do.
Is anyone familiar with this and how to fix it?

A: It is an optical illusion because the height of the body is too small to observe the change properly. Add this to the body CSS and you will see the actual placement, try it with different variations of the body background image position
border: solid red 2px;
margin:0px;
height:500px;


text:
Q: Understanding the "Computational Cost" of a Derivative When it comes to optimizing objective functions belonging to Statistical and Machine Learning Models, there seems to be a general rule:
High dimensional objective functions with many parameters are "computationally expensive" to optimize.
As such, there tends to be two general types of algorithms that are used to optimize objective functions:

*

*Gradient Descent: Gradient Descent tries to find the minimum point (i.e. "optimize") of these objective functions by repeatedly calculating the derivatives of these objective functions, and moving in the direction of these derivatives.

*Evolutionary Algorithms: Evolutionary Algorithms (e.g. Genetic Algorithm) also try to find the minimum point of these objective functions, but instead of repeatedly evaluating the derivatives of the function, they work by "randomly moving in many directions at the same time, and probabilistically moving more in those directions that are producing lesser values of the function". This is called "mutation and crossover" (I have greatly simplified the process).
My Question: As the number of dimensions in the objective function increases, it becomes more and more computationally expensive to repeatedly evaluate the derivatives of the objective function- since Evolutionary Algorithms do not need to repeatedly evaluate these derivatives, they are said to be "computationally cheaper" compared to Gradient Based Methods. (I am not sure if this is always true, I have just informally heard this)
Although there have been no major results established on the convergence of Evolutionary Algorithms (whereas many theoretical results have been established on the convergence of Gradient Based Methods) : For the exact same objective function - do we know precisely how much cheaper "Crossover and Mutation" costs us compared to "Evaluating Second Derivatives"?
There still seems to be some costs associated with "Crossover and Mutation" (e.g. randomly storing, sorting and permuting well-performing "chromosomes" i.e. past solutions) - but do we know how much cheaper this costs us compared to evaluating derivatives (e.g. can we bound this using some Big-O Landau Notation or using Linear vs. Polynomial Time)?
Thanks!
Extra: Comparison of Gradient Descent and Genetic Algorithm for Optimizing the Rastrign Function using the R Programming language
1) Genetic Algorithm
library(GA)

start.time <- Sys.time()

  #define function to be optimized
Rastrigin <- function(x1, x2)
{
  20 + x1^2 + x2^2 - 10*(cos(2*pi*x1) + cos(2*pi*x2))
}

x1 <- x2 <- seq(-5.12, 5.12, by = 0.1)

#run optimization through the genetic algorithm (with constraints)
GA <- ga(type = "real-valued",
         fitness =  function(x) -Rastrigin(x[1], x[2]),
         lower = c(-5.12, -5.12), upper = c(5.12, 5.12),
         popSize = 50, maxiter = 1000, run = 100)

end.time <- Sys.time()
time.taken <- end.time - start.time

Results:
 time.taken

Time difference of 1.266233 secs

GA@solution
                x1          x2
[1,] -4.947186e-06 3.72529e-07

2) Gradient Descent
library(pracma)

start.time <- Sys.time()

Rastrigin <- function(x)
    {
        return(20 + x[1]^2 + x[2]^2 - 10*(cos(2*pi*x[1]) + cos(2*pi*x[2])))
    }

 steep_descent(c(1, 1), Rastrigin)

end.time <- Sys.time()
    time.taken <- end.time - start.time

    time.taken

Results:
time.taken
Time difference of 0.01959896 secs

$xmin
[1] 0.9949586 0.9949586

$fmin
[1] 1.989918

$niter
[1] 3

*

*In the above case, Gradient Descent took less time compared to the Evolutionary Algorithm - but the function being optimized was a simple function, had the function been a higher dimension function, evaluating all the derivatives required in Gradient Descent would have likely taken more time.

*Also, the Rastrign Function has its true minimum at (0,0) : https://www.cs.unm.edu/~neal.holts/dga/benchmarkFunction/rastrigin.html.  Gradient Descent incorrectly returned the minimum at (1,1) whereas the Evolutionary Algorithm was able to find the correct minimum at (0,0).
References:

*

*https://cran.r-project.org/web/packages/GA/vignettes/GA.html

*https://rdrr.io/rforge/pracma/man/steep_descent.html


text:
Q: Pass Remote object in method to RMI server? I have an RMI client that connects to some RMI server just to let it know it can use this new client.
Can I pass directly some Remote object so that:
serverRemoteObject.registerClient(theClientRemoteObjectTheServerShouldUse);

will actually give the server some object he can use without connecting to my client?
The following question says it is possible, but no real example was given:
Is it possible to use RMI bidirectional between two classes?
Andrew

A: Yes, you can. This is how exactly callbacks work in case of RMI. You send across an object to the server and when the server invokes a method on your object, it would be executed in the "client" JVM as opposed to on the server. Look into UnicastRemoteObject.export method for export any object which implements the Remote interface as a remote object which can be passed to your server.
interface UpdateListener extends Remote {

  public void handleUpdate(Object update) throws RemoteException;

}

class UpdateListenerImpl implements UpdateListener {

  public void handleUpdate(Object update) throws RemoteException {
  // do something
  }

}

//somewhere in your client code
final UpdateListener listener = new UpdateListenerImpl();
UnicastRemoteObject.export(listener);


text:
Q: How would I play input from the mic through speaker while a key is pressed? I like to play games with my headphones on, and it feels really weird to not hear myself when I speak. The V key is what I use to transmit, so is there an AutoHotkey script or other program to listen to the microphone while a key is pressed?
I'm on Windows 7.


text:
Q: coldfusion + xml get node according to date XML trickiness. I'm trying to isolate the node with a sports "Match" that is currently in progress or is the next upcoming Match.
thisScheduleXML:
<Data>
        <Sport type="Union">
            <Schedules>
                <Competition id="48" name="SR" type="Union" group="">
                    <Match id="1684" round="Week 1" previewArticleID="" matchReportArticleID="" status="Upcoming" alternateId="1">
                        <MatchDate startDateLocal="2011-02-18 19:35:00" dayName="Fri" shortDate="18-Feb">2011-02-18 19:35:00</MatchDate>
                        <Venue id="30" timeZoneID="NZDT" gmtMinutes="780" venue="Westpac Stadium" location="Wellington">Westpac Stadium, Wellington</Venue>
                        <HomeTeam id="8" alternateId="428">Hurricanes</HomeTeam>
                        <AwayTeam id="7" alternateId="427">Highlanders</AwayTeam>
                    </Match>
                    <Match id="1685" round="Week 1" previewArticleID="" matchReportArticleID="" status="Upcoming" alternateId="2">
                        <MatchDate startDateLocal="2011-02-11 19:40:00" dayName="Fri" shortDate="18-Feb">2011-02-11 19:40:00</MatchDate>
                        <Venue id="160" timeZoneID="AEDT" gmtMinutes="660" venue="AAMI Park" location="Melbourne">AAMI Park, Melbourne</Venue>
                        <HomeTeam id="76" alternateId="0">Rebels</HomeTeam>
                        <AwayTeam id="12" alternateId="422">Waratahs</AwayTeam>
                    </Match>
                    .. more matches
                </Competition>
                ... more competitions
            </Schedules>
        </Sport>
    </Data>

Any help in the right direction would be greatly appreciated.
I would have thought something along these line:
<cfset currentMatchNode = xmlSearch(thisScheduleXml,"/SportalData/Sport/Schedules/Match/MatchDate[@startLocalDate is current otherwise the next upcoming one]")>

A: I couldn't find a way to match on date in XPath. Maybe someone else can help with that. However, in the past we've dealt with this in CF, using a loop. For example:
<cfset nodes = xmlSearch(x, "/Data/Sport/Schedules/Competition/Match") />
<cfset found = false />

<cfloop array="#nodes#" index="match">

    <!--- Check to see if the match is on now or in the future --->
    <cfif match["MatchDate"].xmlText gte now()>
        <cfdump var="#match#" />
        <cfset found = true />
    </cfif>

    <!--- Only output the first --->
    <cfif found>
        <cfbreak />
    </cfif>

</cfloop>

That will print the Match node of the first match coming up. Hope it helps you in the right direction.


text:
Q: rsync - file is 8 bytes larger on recipient I have a file that I have tried transferring across the wired LAN via both scp and rsync, and both have yielded the same result. When I run du file on the file after the transfer, the file is 8 bytes larger on the recipient host.
I have also checked head file | hexdump -C on both hosts, and they are identical. Same story for tail...
Any ideas why this might be happening? If it matters, the file is a gzip.

A: du file is not a suitable way to measure file size. Even the very first line of the man page says « du - estimate file space usage » (my italics).
Instead, use one or more of the following methods (others will also exist):
ls -l file       # byte size should be the same on both sides
cksum file       # checksum should be same result on both sides
md5sum file      # checksum should be same result on both sides
stat -c %s file  # byte size should be same result on both sides


text:
Q: Authentication fails in Zend for account confirmation I am stuck with this problem. When the login credentials are authenticated in my zend application , I also want to check if the account has been confirmed or not. Confirmed is a boolean column in my account table and is set to False by default. I am trying to achieve this through following code..but it is not working
    $db = Zend_Db_Table::getDefaultAdapter();
    $authAdapter = new Zend_Auth_Adapter_DbTable($db);
    $authAdapter->setTableName('Account');
    $authAdapter->setIdentityColumn('Email');
    $authAdapter->setCredentialColumn('Password');
    $authAdapter->setCredentialTreatment('Confirmed = 1');
    $authAdapter->setIdentity($data['email']);
    $authAdapter->setCredential($data['password']);
    $auth = Zend_Auth::getInstance();
    $result = $auth->authenticate($authAdapter);

    if ($result->isValid()) {
        if ($data['public'] == "1") {
            Zend_Session::rememberMe(Zend_Registry::getInstance()->constants->sessiontime);
        } else {
            Zend_Session::forgetMe();
        }
        return TRUE;
    } else {
        return FALSE;
    }

Despite the account not confirmed the authentication passes. Please tell me where am I wrong

A: The credential treatment parameter specifies how the password should be checked. You can override this to add additional clauses, but you still need to include the password bit. Really I wouldn't have expected your method to authenticate any users, so this may not be the main issue, but try:
$authAdapter->setCredentialTreatment('MD5(?) AND Confirmed = 1');

Changing the MD5 bit for however your passwords are encrypted. That should generate a query along the lines of:
... WHERE Email = 'xxx' AND Password = MD5(?) AND Confirmed = 1