text:
Q: Get links from a site's homepage using python I want to write a script to get a home page's links to social media (twitter / facebook mostly), and I'm completely stuck since I am fairly new to Python.
The task I want to accomplish is to parse the website, find the social media links, and save it in a new data frame where each column would contain the original URL, the twitter link, and the facebook link. Here's what I have so far of this code for the new york times website:
from bs4 import BeautifulSoup
import requests

url = "http://www.nytimes.com"
r = requests.get(url)
sm_sites = ['twitter.com','facebook.com']

soup = BeautifulSoup(r.content, 'html5lib')
all_links = soup.find_all('a', href = True)

for site in sm_sites:
    if all(site in sm_sites for link in all_links):
        print(site)
    else:
        print('no link')

I'm having some problems understanding what the loop is doing, or how to make it work for what I need it to. I also had tried to store the site instead of doing print(site) but that was not working... So I figured I'd ask for help. Before asking, I went through a bunch of responses here but none could get me to do what I needed to do.

A: the way this code works, you already have your links. Your homepage link is the starting url, so http://www.nytimes.com.
And you have the social media urls sm_sites = ['twitter.com','facebook.com'], all you're doing is confirming they exist on the main page. If you want to save the list of confirmed social media urls, then append them to a list
Here is one way to get the social media links off a page
import requests
from bs4 import BeautifulSoup

url = "https://stackoverflow.com/questions/tagged/python"
r = requests.get(url)
sm_sites = ['twitter.com','facebook.com']
sm_sites_present = []

soup = BeautifulSoup(r.content, 'html5lib')
all_links = soup.find_all('a', href = True)

for sm_site in sm_sites:
    for link in all_links:
        if sm_site in link.attrs['href']:
            sm_sites_present.append(link.attrs['href'])

print(sm_sites_present)

output:
['https://twitter.com/stackoverflow', 'https://www.facebook.com/officialstackoverflow/']

Update
for a df of urls
import requests
import pandas as pd
from bs4 import BeautifulSoup
from IPython.display import display

urls = [
    "https://stackoverflow.com/questions/tagged/python",
    "https://www.nytimes.com/",
    "https://en.wikipedia.org/"
]

sm_sites = ['twitter.com','facebook.com']
sm_sites_present = []
columns = ['url'] + sm_sites
df = pd.DataFrame(data={'url' : urls}, columns=columns)

def get_sm(row):
    r = requests.get(row['url'])
    output = pd.Series()

    soup = BeautifulSoup(r.content, 'html5lib')
    all_links = soup.find_all('a', href = True)
    for sm_site in sm_sites:
        for link in all_links:
            if sm_site in link.attrs['href']:
                output[sm_site] = link.attrs['href']
    return output

sm_columns = df.apply(get_sm, axis=1)
df.update(sm_columns)
df.fillna(value='no link')

output

A: This will do what you want with regards to adding it to a DataFrame. You can iterate through a list of websites (urlsToSearch), adding a row to the dataframe for each one containing the base website, all facebook links, and all twitter links.
from bs4 import BeautifulSoup
import requests
import pandas as pd

df = pd.DataFrame(columns=["Website", "Facebook", "Twitter"])

urlsToSearch = ["http://www.nytimes.com","http://www.businessinsider.com/"]

for url in urlsToSearch:
    r = requests.get(url)

    tw_links = []
    fb_links = []

    soup = BeautifulSoup(r.text, 'html.parser')
    all_links = [link['href'] for link in soup.find_all('a', href = True)] #only get href

    for link in all_links:
        if "twitter.com" in link:
            tw_links.append(link)
        elif "facebook.com" in link:
            fb_links.append(link)

   df.loc[df.shape[0]] = [url,fb_links,tw_links] #Add row to end of df


text:
Q: Vagrant Puppet Provisioning - Pear Packages I'm using this Laravel Vagrant: https://github.com/bryannielsen/Laravel4-Vagrant and I want to add PHPUNIT and some other PEAR packages.
I added this line on manifests/phpbase.pp
include pearpackages

I created this file puppet/modules/pearpackages/manifests/init.pp:
class pearpackages {
exec {"pear upgrade":
  command => "/usr/bin/pear upgrade",
  require => Package['php-pear'],
  returns => [ 0, '', ' ']
}

# set channels to auto discover
exec { "pear auto_discover" :
  command => "/usr/bin/pear config-set auto_discover 1",
  require => [Package['php-pear']]
}

exec { "pear update-channels" :
  command => "/usr/bin/pear update-channels",
  require => [Package['php-pear']]
}

exec {"pear install phpunit":
  command => "/usr/bin/pear install --alldeps pear.phpunit.de/PHPUnit",
  creates => '/usr/bin/phpunit',
  require => Exec['pear update-channels']
}

# install phploc
exec {"pear install phploc":
  command => "/usr/bin/pear install --alldeps pear.phpunit.de/phploc",
  creates => '/usr/bin/phploc',
  require => Exec['pear update-channels']
}

# install phpcpd
exec {"pear install phpcpd":
  command => "/usr/bin/pear install --alldeps pear.phpunit.de/phpcpd",
  creates => '/usr/bin/phpcpd',
  require => Exec['pear update-channels']
}

# install phpdcd
exec {"pear install phpdcd":
  command => "/usr/bin/pear install --alldeps pear.phpunit.de/phpdcd-beta",
  creates => '/usr/bin/phpdcd',
  require => Exec['pear update-channels']
}

# install phpcs
exec {"pear install phpcs":
  command => "/usr/bin/pear install --alldeps PHP_CodeSniffer",
  creates => '/usr/bin/phpcs',
  require => Exec['pear update-channels']
}

# install phpdepend
exec {"pear install pdepend":
  command => "/usr/bin/pear install --alldeps pear.pdepend.org/PHP_Depend-beta",
  creates => '/usr/bin/pdepend',
  require => Exec['pear update-channels']
}

# install phpmd
exec {"pear install phpmd":
  command => "/usr/bin/pear install --alldeps pear.phpmd.org/PHP_PMD",
  creates => '/usr/bin/phpmd',
  require => Exec['pear update-channels']
}

# install PHP_CodeBrowser
exec {"pear install PHP_CodeBrowser":
  command => "/usr/bin/pear install --alldeps pear.phpqatools.org/PHP_CodeBrowser",
  creates => '/usr/bin/phpcb',
  require => Exec['pear update-channels']
}
}

After, I make a vagrant provision
It seems that is all well configured, but when I go to localhost:8888 the page is always loading and not show me the content.
I don't know what I'm doing bad, but I need your help please, the system configuration is not my specialty

A: Have you tried using PuPHPet to generate your Puppet manifests? You can enter PEAR modules under the Languages section.

A: I´ve found the solution.
There are some incompatibility with Vagrant and VirtualBox in some versions. I don´t know if the issue is for the Guests Aditions.
With vagrant 1.6.2 and VirtualBox 4.3.12 works fine.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Clarity on Vagrant usage and provisioning tool Ok, so I'm a bit late jumping onto the Vagrant band-wagon, but figured it's about time I did.
Brief background: I've been a freelance developer for quite some time now developing solutions based on Magento and Drupal, and have finally gathered enough demand to warrant the need to build up a team. Previously, whenever I started development on any new project, I use to clone a preconfigured base VM in Virtualbox, and use that. Of course there were still configurations to do on it until I could start with actual development. Every project's web files therefore all resided inside /var/www/projectname on an Ubuntu VM.
Now I've read up on why I should be Vagrant, especially considering that I now have a team of 4 developers working with me, but I would appreciate any feedback on the following questions I have:
Moderator note: I know this isn't exactly asking a programming question, so please advise if this could be turned into a wiki, as I'm sure that feedback into this will help someone just like me.
I am still reading through the Vagrant docs, so please be kind...noob questions ahead!

*

*I now work on a Mac. Does it matter if I use Parallels, and another developer uses VirtualBox on Windows if we need to share or collaborate on projects?

*When I issue the command, vagrant up for an existing project, will it start the VM up as I would in VirtualBox or will it recreate the VM?

*Is the command vagrant halt the same issuing sudo poweroff in Ubuntu, for example?

*I currently use PhpStorm and its SFTP feature for project files synchronization with the option to exclude certain files on the remote server (VM) from being imported and sync'ed...will I be able to specify the same using Vagrant folder sharing?

*Could I easily zip or archive a Vagrant VM, move it to a file server, and then "re-import" when and if needed? (example bug fixes, or new feature enhancements)

*What do we use to easily provision VMs for common projects? Should we being using Puppet, Chef, Puphpet or Salt? I've seen that Puphpet provides a nice GUI to create a vagrantfile which I'm sure once generated, we could customize for future projects. At a very basic level, we need to ensure that certain applications are installed onto the server (zip, phpmyadmin, OpenSSL, etc.), certain PHP settings, PHP and PEAR modules, and Apache settings. I already have base VMs set up as I'd like them for both Magento projects as well as Drupal projects.

EDIT: I should also add that I use to enable Host Adapter in VirtualBox (on Windows), configure the VHost inside Ubuntu, and then update my host machine's hosts file with something like 192.168.56.3   drupalsite1.dev. So I'm unsure if Port Forwarding would be better to use? I'm not very clued up on that I must admit.
Like i said - noob questions! However, I would really appreciate any feedback on these questions. My deepest thanks!

A: Most of what you are asking is subjective so common sense and experience are the best tools.

*

*I recommend all team members use the same provider (parallels isn't officially supported) and virtualbox is readily available. The base boxes, by provider, could have slight variances, you never know.

*Vagrant will start the vm similarly but vagrant also does other things like configuration the network, hostname, shared folders, etc. Not quite the same. The big power lies in the capability to be able to teardown the environment and bring it back in a cleanly provisioned state.

*Basically, yes.

*Yes, your vagrant VMs are just like your own mini cloud. You would interact the servers similar to the way you'd interact with external boxes.

*Yes, the simple answer is that it's called packaging and you can share the resultant .box. However, it's good practice to keep the base box and provisioning scripts under CM so you can rebuild and modify as needed.

*For provisioners, I think it is dependent upon your experience and your familiarity with the provisioner language and how much you want to invest in learning them. Look through the provisioner support and see what fits your need and budget. Chef has a very steep learning curve, in my experience, but also has a lot of thought built in. Most provisioners have wide libraries of available installation "scripts".
The host adapter can be handled identically in vagrant.
Learn by doing, I recommend going down the table of contents (navbar) of the vagrant docs and trying each step where it makes sense. Then make your decisions.
That is my 2 cents. Hope this helps!


text:
Q: XPath, select two consecutive elements and transform them into one data frame I am really new to Path and R in general and am trying to convert an XML file using XPath into a data frame in R. With some help I managed to transform most of the information in the XML already . However, now I am trying to take two consecutive elements and merge them into one data frame. Somehow I can't seem to get it right.
This is an excerpt of the xml data:
</customer-bootstrap-data>
  <customer-bootstrap-data id="970911" customerName="HighIncome-1_4" powerType="ELECTRIC_VEHICLE">
<netUsage>0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.1124173640233721,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,-0.0,-0.0,-0.37606842556525066,-0.0,-0.0,-0.038684343289247636,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.8490012729862713,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0</netUsage>
  </customer-bootstrap-data>
  <customer-bootstrap-data id="970912" customerName="HighIncome-2_17" powerType="ELECTRIC_VEHICLE">
<netUsage>0.0,0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.21395291779884928,-0.0,-0.0,-1.3581716633726693,-0.0,-0.0,-2.8140822306420716,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-3.0221045637055397,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-3.3,-3.3,-3.223543705462774,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.153329511039221,-0.0,-0.0,-0.0,-0.0,-0.0,-0.820425411761537,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.7054631085029754,-0.0,-0.7130641168720118,-0.0,-0.0,-0.0,-0.0,-0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-2.5003661751788435,-0.0,-0.0,-3.3,-3.3,-0.6606989045692728,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.20818145620010853,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0493154269844851,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-3.3,-0.0,-1.041919182358086,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-3.3,-0.5334016276259916,-0.0,-0.0,-0.0</netUsage>
  </customer-bootstrap-data>

I am able to generate a table with the first element using the following code:
customerBoot <- xpathSApply(doc=xml, path=("//customer-bootstrap-data"), xmlAttrs)
customerBoot <- data.frame(t(customerBoot))

containing id, customerName and powerType. But I want the net usage to be also included for each customer id.
The following code selects all the information I want it just doesn't allow me to transform it into a data frame.
customerBoot <- getNodeSet(xml,"//customer-bootstrap-data")

Any ideas going either way? I am looking for a fast solution.
Thank you!

A: Let me know if this has speed issues (iterating over a huge XML doc in this manner can sometimes be slow):
library(XML)
library(purrr)

fil <- '<dat><customer-bootstrap-data id="970911" customerName="HighIncome-1_4" powerType="ELECTRIC_VEHICLE">
<netUsage>0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.1124173640233721,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,-0.0,-0.0,-0.37606842556525066,-0.0,-0.0,-0.038684343289247636,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.8490012729862713,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0</netUsage>
  </customer-bootstrap-data>
  <customer-bootstrap-data id="970912" customerName="HighIncome-2_17" powerType="ELECTRIC_VEHICLE">
<netUsage>0.0,0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.21395291779884928,-0.0,-0.0,-1.3581716633726693,-0.0,-0.0,-2.8140822306420716,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-3.0221045637055397,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-3.3,-3.3,-3.223543705462774,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.153329511039221,-0.0,-0.0,-0.0,-0.0,-0.0,-0.820425411761537,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.7054631085029754,-0.0,-0.7130641168720118,-0.0,-0.0,-0.0,-0.0,-0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-2.5003661751788435,-0.0,-0.0,-3.3,-3.3,-0.6606989045692728,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.20818145620010853,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0493154269844851,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-3.3,-0.0,-1.041919182358086,-0.0,-0.0,-0.0,-0.0,-0.0,-0.0,-3.3,-0.5334016276259916,-0.0,-0.0,-0.0</netUsage>
  </customer-bootstrap-data></dat>'

doc <- xmlParse(fil)

customerBoot <- xpathSApply(doc=doc, path="//customer-bootstrap-data", xmlAttrs)
customerBoot <- data.frame(t(customerBoot), stringsAsFactors=FALSE)

# go by row using the id, grab the desired data node, convert it to a wide data.frame

customerBoot <- purrr::by_row(customerBoot, function(x) {

  path <- sprintf("//customer-bootstrap-data[@id='%s']/netUsage", x$id)
  vals <- strsplit(xpathSApply(doc=doc, path=path, xmlValue), ",")[[1]]
  as.numeric(vals)

}, .to="X", .collate="cols")

# limiting the "str()" equivalent "glimpse()" to 15 columns since there are >300 of them:

dplyr::glimpse(customerBoot[, 1:15])

## Observations: 2
## Variables: 15
## $ id           (chr) "970911", "970912"
## $ customerName (chr) "HighIncome-1_4", "HighIncome-2_17"
## $ powerType    (chr) "ELECTRIC_VEHICLE", "ELECTRIC_VEHICLE"
## $ X1           (dbl) 0, 0
## $ X2           (dbl) 0, 0
## $ X3           (dbl) 0, 0
## $ X4           (dbl) 0, 0
## $ X5           (dbl) 0, 0
## $ X6           (dbl) 0, 0
## $ X7           (dbl) 0, 0
## $ X8           (dbl) 0.0000000, -0.2139529
## $ X9           (dbl) 0, 0
## $ X10          (dbl) 0, 0
## $ X11          (dbl) 0.000000, -1.358172
## $ X12          (dbl) 0, 0

Alternate way with xml2:
library(purrr)
library(xml2)

doc <- read_xml(fil)

xml_find_all(doc, "//customer-bootstrap-data") %>%
  xml_attrs() %>%
  map_df(function(x) {
    path <- sprintf("//customer-bootstrap-data[@id='%s']/netUsage", x["id"])
    vals <- strsplit(xml_text(xml_find_one(doc, path)), ",")[[1]]
    vals <- setNames(as.numeric(vals), sprintf("X%d", 1:length(vals)))
    rbind.data.frame((c(as.list(x), as.list(vals))), stringsAsFactors=FALSE)
  })

UPDATE:
Here's one way to do it when netUsage is not of uniform length:
data.table::rbindlist(apply(customerBoot, 1, function(x) {

  path <- sprintf("//customer-bootstrap-data[@id='%s']/netUsage", x["id"])
  vals <- strsplit(xpathSApply(doc=doc, path=path, xmlValue), ",")[[1]]
  c(as.list(x), as.list(setNames(as.numeric(vals), sprintf("X%d", 1:length(vals)))))

}), fill=TRUE)


text:
Q: Posting an Intent from Python scripts using Monkey/Monkey Runner I am trying to test my apps using python and monkey runner.
I want to send an intent during start activity.
I tried using extras and this doesnt help.
Can some one help me with this? If possible can some one provide me a sample AndroidManifest.xml and test.py on how to do this.
Thank you all for the help
blr p sh

A: There are some bugs in monkeyrunner avoiding correct handling of extras. This question also mentions the case passing booleans, but it's not restricted to them.
The workaround, as monkeyrunner does not do much that invoking ADB in this cases is to use
device.shell('am start -a android.intent.action.MAIN -n my.pkg/.MyActivity -e key val')


text:
Q: Java Socket issue, buffer receives two packets at same time. I am using Java Socket API for communication. But sometime I am getting, packet attached in single packet. How can I avoid the same. Is there any method to resolve same in Java NIO or java NIO 2. I am sure that packets are coming separately. But both stored in single buffer.
Please note that here Packet is nothing but logical separation of data. The data is send by third party system. They send one by one. But I am receiving two packet at same time.

A: This is the way it's supposed to work. TCP uses packets to transfer data, but it's not visible from the high-level socket API : you open a output stream and send as much data as you want. This data is split into packets by the TCP/IP protocol stack. And at the receiving side, you open an input stream and receive the data, without knowing it has been split into packets.
If you want two application-level packets, then design a transfer protocol using separators between your packets, or fixed-size chunks of data, or anything else allwoing to distinguish what is part of a logical packet and what is part of the next one.


text:
Q: How can I calculate the monthly average of a column in a CSV, given that the CSV file has a column for dates as well This is what the CSV/Excel file looks like:
`2008-09-19 461 462.07  443.28  449.15  10006000    449.15
2008-09-18  422.64  439.18  410.5   439.08  8589400 439.08
2008-09-17  438.48  439.14  413.44  414.49  9126900 414.49
2008-09-16  425.96  449.28  425.49  442.93  6990700 442.93
2008-09-15  424 441.97  423.71  433.86  6567400 433.86
2008-09-12  430.21  441.99  429 437.66  6028000 437.66
2008-09-11  408.35  435.09  406.38  433.75  6471400 433.75
2008-09-10  424.47  424.48  409.68  414.16  6226800 414.16
2008-09-09  423.17  432.38  415 418.66  7229600 418.66
2008-09-08  452.02  452.94  417.55  419.95  9017900 419.95
2008-09-05  445.49  452.46  440.08  444.25  4534300 444.25
2008-09-04  460 463.24  449.4   450.26  4848500 450.26
2008-09-03  468.73  474.29  459.58  464.41  4314600 464.41
2008-09-02  476.77  482.18  461.42  465.25  6111500 465.25
2008-08-29  469.75  471.01  462.33  463.29  3848200 463.29
2008-08-28  472.49  476.45  470.33  473.78  3029700 473.78
`

I need to calculate the monthly average of the final column and store it in a list.
What I have so far is truly awful as I've been scrabbling crap-code together for a few days now struggling to get it right and I know for a fact there are far more efficient (and functional) ways to do it. For anyone who's interested, here's my current dysfunctional code:
def get_monthly_averages (data_list):
    date_list = []
    monthly_average_list = []
    current_date = ''
    nums = []
    count = 0
    total = 0
    average = 0
    for index, row in enumerate(data_list):
        data_list[index] = row.split(",")
    for index, row in enumerate(data_list):
        if index > 0:
            date_list.append(row[0])
            data_list[index] = [float(i) for i in row if row.index(i) > 0]
    for index, row in enumerate(data_list):
        if index == 1:
            current_date = str(date_list[index-1])
            current_date = current_date[:-3]
            count += 1
            nums = row[5:6]

        elif index > 1 and current_date in date_list[index - 1]:
            nums = row[5:6]

            monthly_average_list.append(average)

        elif index > 1 and current_date not in date_list[index - 1]:
            current_date = str(date_list[index-1])
            current_date = current_date[:-3]
            nums = row[5:6]
            total = 0

    print(monthly_average_list[0])
    print(current_date)
    print(date_list[0])
    print(data_list[1])

    return monthly_average_list

A: If I correctly understand the result you're going for, yes, I think you've overthought the solution. If you want the month-wise average of a column, all you need to do is find all the cells in that column, group them up by month, and average them:
from collections import defaultdict

def get_col_avg_by_month(data, colnumber):
    result = defaultdict(lambda: [])
    for row in (row.split() for row in data):
        date = year, month = row[0].split('-')[:2]
        result[tuple(date)].append(float(row[colnumber]))
    return {date: avg(data) for date, data in result.items()}

Here, for each row we grab the month (which we pair with the year to differentiate between September of 2017 and September of 2016) and append the cell of the target column to that month's result list (we use a defaultdict so that the first time we put in a new month, we start with an empty list). Finally, right before we return, we recompute the result dict to hold the average of the data set, rather than the data set itself (avg = lambda lst: sum(lst) / len(lst)).
demo


text:
Q: "Linearizing" the factorization problem? Background & Question
I have a different way of approaching the factorization problem: Given $c$ such that $a<b$ and $ab =c$, find $a$ and $b$ where $a$ and $b$ are distinct primes.
$$ \underbrace{-\text{Res}( \frac{(\text{cot}(\pi c! c^{-s})- \text{cot}(\pi c^{-s}))}{s^w},0)}_{f(c,w)}  = \underbrace{\sum_{1\leq r \leq  a}  \frac{1}{r^w}}_{g(a,w)} + \underbrace{\sum_{\kappa | c!}\frac{1}{\ln_c(\kappa)^w}}_{k(c,w)}$$
where $w>1$.
Does this "linearize the problem" in the sense one gets $f(c,w) = g(a,w) + k(c,w)$ where $f$,$g$ and $k$ are functions in the above equations? Are there other functions which accomplish the same $ f(c,w) = g(a,w) + k(c,w)$ without the variable $b$? While calculating the exact value of $c!$ is hard will Stirling's approximation provide a range of the value of $a$?
Rough Sketch of Idea
Consider the following fact:
$$ \frac{c!}{c^a} = \text{Integer} $$
$$ \frac{c!}{c^{a+1}} \neq \text{Integer} $$
Now consider the following contour integral around the origin of radius $R \to \infty$:
$$ \frac{1}{2 \pi i}\oint \frac{(\text{cot}(\pi c! c^{-s})- \text{cot}(\pi c^{-s}))ds}{s^w} = \sum_{s}\text{Res}( \frac{(\text{cot}(\pi c! c^{-s})- \text{cot}(\pi c^{-s}))}{s^w},s)$$
For $w >1 $ the contour vanishes. Note the residues with the exception of $0$ are all single poles can be expressed as:
$$ -\text{Res}( \frac{(\text{cot}(\pi c! c^{-s})- \text{cot}(\pi c^{-s}))}{s^w},0)  = \sum_{1\leq r \leq  a}  \frac{1}{r^w} + \sum_{\kappa | c!}\frac{1}{\ln_c(\kappa)^w}$$


text:
Q: JAVA - Run external jar file at start I want to create an application that runs, and it has a folder which will contain jar files with minigames. I would like to create these minigames seperately as that will be easier to swap the games in and out. I just don't know how to load these jar files into my other already running application, so that I can just access the classes in the jar files and invoke the right methods with my annotations.
So, TL;DR, how do I add classes to my classpath on runtime?
With kind regards,
Stan

A: What you're doing is probably not the best way to go, in my opinion.
With that said, here's an explanation that will help you achieve what you want:
Java works with ClassLoader which is a Java object that loads classes from a specific path, usually that would be the Java class_path. In order to dynamically load a jar, you can simply create a URLClassLoader with a URL referencing your jar, or alternatively add the jar URL to the current ClassLoader or to the system ClassLoader, depending on your use case. Once you loaded the jar, you'll be able to instantiate an instance of your Java class.
Following is an example of creating a new Classloader with a specific jar:
URL url = new File(jarPath).toURI().toURL();
URLClassLoader classLoader = new URLClassLoader(url);
Object yourObject = Class.forName(className, true, classLoader).newInstance();

Of course, you should adapt the new instance creation to your class etc.


text:
Q: Single Post Template with Dropdown Option? I'd like users of my theme to be able to select a single post template via a dropdown menu on the post screen.
I know of a plugin that achieves this but I would like to be able to achieve the same thing without the plugin.  Anybody have a solution?

A: `

        if (is_singular()) {
            $zifana_captain_hook = get_page_template();

            if ($zifana_captain_hook && !preg_match('/page.php$/', $zifana_captain_hook)) {
                include($zifana_captain_hook);
                die();
            }

        }

    }

    // -- Function Name : save_post
    // -- Params : $post_id, $post
    // -- Purpose :
    function save_post($post_id, $post) {
        $zifana_captain_hook = isset($_POST['zifana_theme_styling'])? $_POST['zifana_theme_styling'] :
        '';

        if ( !empty($zifana_captain_hook) ) {
            $zifana_captain_hooks = get_page_templates();
            $post->page_template = $zifana_captain_hook;

            if ( 'default' != $zifana_captain_hook && !in_array($zifana_captain_hook, $zifana_captain_hooks) ) {
                return;
            }

            update_post_meta($post_id, '_wp_page_template', $zifana_captain_hook);
        }

    }

    // -- Function Name : zifana_hook_theme_metabox
    // -- Params : $post
    // -- Purpose :
    function zifana_hook_theme_metabox($post) {
        $zifana_captain_hook = get_post_meta( $post->ID, '_wp_page_template', true );
        ?>

    // -- Function Name : add_dropdown
    // -- Params :
    // -- Purpose :
    function add_dropdown() {

        if ( 0 != count( get_page_templates() ) ) {
            add_meta_box('themezifanastyle',__( 'What template huh..', 'zifana'),array(&$this, 'zifana_hook_theme_metabox'),'post');
        }

    }

};
$__zifana_theme_stylings = & new zifanaTemplate;

if (is_admin()) {
    add_action('admin_menu', array(&$__zifana_theme_stylings, 'add_dropdown'));
}

add_action('zifana_page_hook', array(&$__zifana_theme_stylings, 'zifana_page_hook'));
add_action('save_post', array(&$__zifana_theme_stylings, 'save_post'), 10, 2);

`
i hope helpfull.. :)


text:
Q: How to create plugins in swift I found article describing how to create plugin using Swift and Cocoa. It uses NSBundle to load plugin, but that, as far as I know, is not available in pure swift (no Cocoa). Is there way how to achieve same result without using Cocoa?
More info:
In case it's relevant, here is what I want to achieve. I create app in swift that runs on linux server. User can connect to it using their browser. I want to be able to have other people write "plugins" that will implement functionality itself (what user can see and do once they connect), from printing out hello world, through chat programs to games without having to worry about low level stuff provided by my app. Some sort of dll, that my server application loads and runs.

A: Solution to this is not trivial, but it's not impossible to do either. I prefer to use swift package manager to manage dependencies and Xcode as IDE. This combination is not perfect as it needs a lot of tinkering but there is not any other useable free swift IDE as of now.
You will need to set up two projects, let's call them Plugin (3rd party library) and PluginConsumer (app that uses other people plugins). You will also need to decide on API, for now we will use simple
TestPluginFunc()

Create Plugin.swift file with TestPluginFunc implementation in your Plugin project:
public func TestPluginFunc() {
    print("Hooray!")
}

Set the project to build framework, not executable and build[1]. You will get Plugin.framework file which contains your plugin.
Now switch to your PluginConsumer project
Copy Plugin.framework from your Plugin project somewhere where you can easily find it. To actually load the framework and use it:
// we need to define how our plugin function looks like
typealias TestPluginFunc = @convention(c) ()->()
// and what is its name
let pluginFuncName = "TestPluginFunc"

func loadPlugin() {
    let pluginName = "Plugin"
    let openRes = dlopen("./\(pluginName).framework/\(pluginName)", RTLD_NOW|RTLD_LOCAL)
    if openRes != nil {
        // this is fragile
        let symbolName = "_TF\(pluginName.utf8.count)\(pluginName)\(initFuncName.utf8.count)\(initFuncName)FT_T_"
        let sym = dlsym(openRes, symbolName)
        if sym != nil {
            // here we load func from framework based on the name we constructed in "symbolName" variable
            let f: TestPluginFunc = unsafeBitCast(sym, to: TestPluginFunc.self)

            // and now all we need to do is execute our plugin function
            f()

        } else {
            print("Error loading \(realPath). Symbol \(symbolName) not found.")
            dlclose(openRes)
        }
    } else {
        print("error opening lib")
    }
}

If done correctly, you should see "Hooray!" being printed to your log.
There is a lot of room for improvement, first thing you should do is replace Plugin.framework string with parameter, preferably using some file library (I am using PerfectLib). Another thing to look at is defining plugin API in your PluginConsumer project as a protocol or base class, creating framework out of that, importing that framework in your plugin project and basing your implementation on that protocol/base class. I am trying to figure out exactly how to do that. I will update this post if I mange to do it properly.
[1]: I usually do this by creating Package.swift file and creating xcode project out of it using swift package generate-xcodeproj. If your project doesn't contain main.swift, xcode will create framework instead of executable

A: What you will want to do is create a folder your program will look in.  Let's say it's called 'plugins'.  It should make a list of names from the files in there, and then iterate through using them, passing parameters to the files and getting the output and making use of that in some way.
Activating a program and getting output:
func runCommand(cmd : String, args : String...) -> (output: [String], error: [String], exitCode: Int32) {

    var output : [String] = []
    var error : [String] = []

    let task = Process()
    task.launchPath = cmd
    task.arguments = args

    let outpipe = Pipe()
    task.standardOutput = outpipe
    let errpipe = Pipe()
    task.standardError = errpipe

    task.launch()

    let outdata = outpipe.fileHandleForReading.readDataToEndOfFile()
    if var string = String(data: outdata, encoding: .utf8) {
        string = string.trimmingCharacters(in: .newlines)
        output = string.components(separatedBy: "\n")
    }

    let errdata = errpipe.fileHandleForReading.readDataToEndOfFile()
    if var string = String(data: errdata, encoding: .utf8) {
        string = string.trimmingCharacters(in: .newlines)
        error = string.components(separatedBy: "\n")
    }

    task.waitUntilExit()
    let status = task.terminationStatus

    return (output, error, status)
}

`
Here is how a swift plugin would accept arguments:
    for i in 1..C_ARGC {
    let index = Int(i);

    let arg = String.fromCString(C_ARGV[index])
       switch arg {
        case 1:
            println("1");

        case 2:
            println("2")

        default:
            println("3)
       }
    }

So once you have the program and plugin communicating you just have to add handling in your program based on the output so the plugins output can do something meaningful.  Without cocoa libraries this seems the way to go, though if you use C there are a couple of other options available there as well.  Hope this helps.


text:
Q: Detect list of homogeneous elements in a webpage I need to detect a sequence of consecutive identical elements in the DOM of a page. These elements could be div's or li's or span's and could contain other elements. The elements have in common the fact that they appear consecutively and have the same inner structure.
The problem i am trying to solve is automatically parsing search results. The solution i am trying to find would produce a list of all lists of such elements (for example a page might contain a list with the search results and other irrelevant lists of elements); this solution would have to be generic enough that i do not need to know the structure of the page beforehand.
Thank you.

A: The problem in general is too complex to apply some kind of regular expressions. It probably implies context grammar.
You have to implement an algoritm by yourself to solve this. The simplest one that I keep in mind is:

*

*Follow DOM tree recursively

*In any recursion step:

*

*Remember  first subelement in a node.

*Go to the next subelement and compare with the one kept in memory.

*Remember last visited subelement.

*Repeat steps 2 and 3 until you finish processing all subelements in a node

A: Assumption: you're building a configurable html web crawler using python that is intended for data mining
Steps to retrieve data:

*

*Downloaded the html page

*build a query capable DOM; try: http://thehtmldom.sourceforge.net/

*query for the appropriate data according to the web crawler configuration

Good luck!


text:
Q: Parsing VP8/OPUS frames I am developing a webrtc simulator in Linux environment using C language. Here I need to send media from one webrtc simulator to other webrtc simulator. I need to work with VP8 and Opus codec. Now I am starting with VP8 codec. As I am new to VP8, kindly help me to understand more as well .

*

*Since it is simulator, I do not want to capture / play media real time. I need to read audio / video data from a file and send it to remote. At remote get the media data extracted, save it to a file.

*Which file format contains encoded VP8 data? Is it webm file format or something else?

*Assuming webm file contains VP8 and OPUS codec data (which I am not sure), how can I parse frame by frame. For example if I read Extract audio frames from AMR-NB file I can parse amr frames from a file. Similarly is there any help page, where I learn parse logic for VP frame.

*Or is there any open source using that I can parse VP8/OPUS frames from  a webm file.

A: Q2:
I'll start with question number 2, VP8 corresponds with WebM format.
Q3:
If you want to parse frame by frame, you need to know the structure of VP8 and OPUS.
I don't know what simulation means in your scenario, but in WebRTC environment media data is transfered via RTP. If you are doing simulation without RTP, please start from step 2, otherwise start from No. 1.

*

*Depacketize RTP payload from RTP packet. RTP payload contains VP8 packet info like sequence number, timestamp, etc.

*Note, that VP8 frame may consist of multiple VP8 packets, so basically you need to extract the frame content and concatenate it together. There are multiple ways to find out if frame consists of multiple packets, not all of them being fully standardized, but for now I would recommend you to use sequence number, as packets of one frame share the same SEQ.

*Write the frame into file. If you want to create a valid WebM file, use function such as av_write_frame() from LibAV (which I personally use).

I can recommend you a piece of code that actually converts raw RTP VP8 packets to VP8 frames: https://github.com/meetecho/janus-gateway/blob/master/postprocessing/pp-webm.c .
Packet header reading is used in functions (preprocess and process).
Q4:
I use LibAV for such purposes (alternatively FFMPEG).
I'll gladly answer any other question.


text:
Q: Android Camera Surface View I am trying to create a surface view for a camera so it renders on the surface whenever is in the view of the camera. At the moment all I can see on my camera view is a black screen view. I have tried to look on Google and here but so far I haven't found what I am looking for. Anyone can suggest me some idea.

A: I have written a class that can help you.
    public class Preview_can_work extends Activity {
        private SurfaceView surface_view;
        private Camera mCamera;
        SurfaceHolder.Callback sh_ob = null;
        SurfaceHolder surface_holder        = null;
        SurfaceHolder.Callback sh_callback  = null;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            getWindow().setFormat(PixelFormat.TRANSLUCENT);

            surface_view = new SurfaceView(getApplicationContext());
            addContentView(surface_view, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));

            if (surface_holder == null) {
                surface_holder = surface_view.getHolder();
            }

            sh_callback = my_callback();
            surface_holder.addCallback(sh_callback);
        }

            SurfaceHolder.Callback my_callback() {
                SurfaceHolder.Callback ob1 = new SurfaceHolder.Callback() {

                    @Override
                    public void surfaceDestroyed(SurfaceHolder holder) {
                          mCamera.stopPreview();
                          mCamera.release();
                          mCamera = null;
                    }

                    @Override
                    public void surfaceCreated(SurfaceHolder holder) {
                        mCamera = Camera.open();

                          try {
                               mCamera.setPreviewDisplay(holder);
                          } catch (IOException exception) {
                                mCamera.release();
                                mCamera = null;
                          }
                    }

                    @Override
                    public void surfaceChanged(SurfaceHolder holder, int format, int width,
                            int height) {
                        mCamera.startPreview();
                    }
                };
                return ob1;
        }
    }

in your manifest file copy this code for camera permission
<uses-permission android:name="android.permission.CAMERA"/>

Explanation:
SurfaceView is a type of View which contains a SurfaceHolder. SurfaceHolder holds the surface on which we can display our media (generally frames).
mCamera is a Camera object which will contains the camera instance.
When you want to hold default Camera instance then you can simply call Camera.open();
Camera mCamera = Camera.open();

Now you have an open camera or you are having default camera instance. Now you need to capture frames from the camera and display it on a surface. But you cannot display it without any
surface. Here the surfaceView provides surfaceHolder and surfaceHolder provides surface to display camera frames. Now when surface will be created three callback functions will be
called.
1. public void surfaceCreated(SurfaceHolder holder)
2. public void surfaceChanged(SurfaceHolder holder, int format, int width, int height)
3. public void surfaceDestroyed(SurfaceHolder holder)

Note:- Surface will be destroyed when your application will go on pause.
surfaceCreated:
     surfaceCreated is a callback function which will be called when your surface will be created. In this, you can open your camera and set other attributes.
surfaceChanged:
     This will be called atleast one time when your surface will be created. After that it will be called whenever your surface will change(In device rotation). Here you can
start your preview because your surface have already created.
surfaceDestroyed:
     This will be called every time when your surface will destroy. Now if you dont have surface then where you can display you camera frames so I have released camera by using
mCamera.release(). This is very important because if your activity will be on pause and any other activity tries to open camera then it will not able to open it as you have
already open camera. Camera is a shared resource so one time only one application can use it. So remember one thing whenever you open a camera then always release it.
stopPreview:
     When you start preview then your camera starts capturing your frames and display it on a surface. Now if your surface have destroyed then you need to stop capturing frames
from camera so you have to call mCamera.stopPreview.

A: Make shure you added the permission :

<uses-permission android:name="android.permission.CAMERA"/>

Also these window properties:
getWindow().setFormat(PixelFormat.TRANSLUCENT);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
                 WindowManager.LayoutParams.FLAG_FULLSCREEN | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

Post some code if that doesn't work in order to help you


text:
Q: Calculate multiple values with sql with if expression I have a booking table with 6 columns called booked_start, booked_stop, used_start, used_stop, invoice_start, invoice_stop. The values are floats. I want to get a sum of the rows that has values above 0 but i also want it to calculate say used_stop - used_start.
Currently im working with this:
SELECT
    room,
    IF( booked_stop_time > 0, sum(booked_stop_time - booked_start_time), 0 ) as booked,
    IF( used_stop_time > 0, sum(used_stop_time - used_start_time), 0 ) as used,
    IF( invoice_stop_time > 0, sum(invoice_stop_time - invoice_start_time), 0 ) as invoice
FROM bookings

The problem is that if expr1 returns false it'll reset the sum. I only want to add the rows value to the sum if its above 0.
I also tried using a case but that didnt really work. Maybe i should do the calculation in php instead?

A: This should work:
SELECT
  room,
  SUM(
    CASE WHEN booked_stop_time - booked_start_time > 0
      THEN booked_stop_time - booked_start_time
      END
  ) AS booked,
  SUM(
    CASE WHEN used_stop_time - used_start_time > 0
      THEN used_stop_time - used_start_time
      END
  ) AS used,
  SUM(
    CASE WHEN invoice_stop_time - invoice_start_time > 0
      THEN invoice_stop_time - invoice_start_time
      END
  ) AS invoice
FROM bookings

Focusing on the booked value:

*

*If booked_stop_time - booked_start_time is greater than zero the CASE returns booked_stop_time - booked_start_time, so it's included in the sum.

*The CASE doesn't have any other conditions, so if booked_stop_time - booked_start_time is not greater than zero, the CASE returns NULL, which means the row is not included in the sum.

A: You can do it like this:
SELECT
    room,
    SUM(IF( booked_stop_time > 0, booked_stop_time - booked_start_time, 0 )) as booked,
    SUM(IF( used_stop_time > 0, used_stop_time - used_start_time, 0 )) as used,
    SUM(IF( invoice_stop_time > 0, invoice_stop_time - invoice_start_time, 0 )) as invoice
FROM bookings
It return 0 because when your IF condition not satisfy then it set to 0 as final value, so just wrap the IF with SUM.

A: You can try this
SELECT
    room,

    SUM(
          IF( booked_stop_time > 0 and booked_start_time IS NOT NULL,
                       (booked_stop_time - booked_start_time), 0 )
      ) AS booked,

   SUM(
       IF(used_stop_time > 0 AND used_start_time IS NOT NULL,
                            (used_stop_time - used_start_time) , 0 )
      ) AS used,

   SUM(
        IF(invoice_stop_time > 0 AND invoice_start_time IS NOT NULL,
                            (invoice_stop_time - invoice_start_time) , 0)
       ) AS invoice

WHERE booked_stop_time > 0
OR  used_stop_time > 0
OR invoice_stop_time > 0


text:
Q: Access Anonymous to spSite.RootWeb.Folder["xx"] in sharepoint 2010 I wrote that method to download file from document library. But When I enter site as annonymous and try to download file,  "site.RootWeb.Folders["Dokumanlar"];" this code wants authentication.
In web.config I changed trust level like this:
<trust level="Full" originUrl=""/>

What should I do? Thanks.
 private void DownloadFile() {
var docid = HttpContext.Current.Request.QueryString["id"];
int id;
int.TryParse(docid, out id);
if (id == 0) {
var response = HttpContext.Current.Response;
response.Write("Enter document id");
response.End();
return;
}
    using (SPSite site = new SPSite(SPContext.Current.Site.Url))
    {
        var dataContext = new KysDataContext(site.Url);
        var docs = dataContext.Dokumanlar;

        if (docs == null)
        {
            return;
        }

        var dokumanlar = docs.ToList();
        var dokuman = dokumanlar.FirstOrDefault(x => x.Id == id);
        if (dokuman == null)
        {
            var response = HttpContext.Current.Response;
            response.Write("check document id");
            response.End();
            return;
        }
        SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                var rootweb = site.RootWeb.Folders["Dokumanlar"];//this line it's want to authentication
                SPFile file = rootweb.Files[dokuman.Name];
                if (file != null)
                {

                    dokuman.Hits += 1;
                    dataContext.SubmitChanges();

                    var response = HttpContext.Current.Response;
                    response.ClearContent();
                    response.ContentEncoding = Encoding.GetEncoding("windows-1254");
                    response.Charset = "windows-1254";
                    response.ContentType = "application/content-stream";

                    response.AppendHeader("Content-Disposition",
                                          string.Format("attachment; filename={0}", file.Name));
                    response.BinaryWrite(file.OpenBinary());
                    response.End();
                    Page.ClientScript.RegisterOnSubmitStatement(typeof (Page), "closePage",
                                                                "window.onunload = CloseWindow();");

                }
            });
    }
}

A: You need to make new instance of SPSite and SPWeb inside RunWithElevatedPrivileges.
Example
SPSecurity.RunWithElevatedPrivileges(delegate()
{
    using (SPSite site = new SPSite(web.Site.ID))
    {
    // implementation details omitted
    }
});

Fine print from MSDN:
"An SPSite object created outside the delegate can be referenced inside the delegate, however, the methods and property assessors of the object run with the privileges of the user context in which the objects were created, not with the elevated privileges. The same point applies to SPWeb objects and any other objects. You must create new objects inside the delegate if you need to execute the members of the objects with elevated privileges. If the new object must represent the same persisted entity as an object created outside the delegate, then you must reference identification information from the externally created object and use it to create the new object within the delegate. For example, if web is a reference to an SPWeb object created before the call to RunWithElevatedPrivileges, then the following code shows you would use the ID of its parent SPSite object to construct a new SPSite object."


text:
Q: jayway jsonpath throwing an error when reading a json path that does not exist despite being configured to I have some json that is like this:
{
  "root": {
    "metadata": {
      "name": "Farmer John",
      "hasTractor": false
    },
    "plants": {
      "corn": 137.137,
      "soy": 0.45
    },
    "animals": {
      "cow": 4,
      "sheep": 12,
      "pig": 1
    },
    "family": {
      "isMarried": true
    }
  }
}

That I am parsing like this using JsonPath:
val document = Configuration.defaultConfiguration()
        .addOptions(Option.DEFAULT_PATH_LEAF_TO_NULL)
        .jsonProvider()
        .parse(jsonString): Object
val value = JsonPath.read(document, "$.root.family.hasChild"): Any

But I am getting the error:
No results for path: $['root']['family']['hasChild']
com.jayway.jsonpath.PathNotFoundException: No results for path: $['root']['family']['hasChild']
    at com.jayway.jsonpath.internal.path.EvaluationContextImpl.getValue(EvaluationContextImpl.java:133)
    at com.jayway.jsonpath.JsonPath.read(JsonPath.java:187)
    at com.jayway.jsonpath.internal.JsonContext.read(JsonContext.java:102)

I should be getting null because I have the config option Option.DEFAULT_PATH_LEAF_TO_NULL set in the document creation code right? But instead I am getting that error
Edit:
I was able to get it working by simply catching the error and returning null like this:
val value = try {
  JsonPath.read(document, "$.root.family.hasChild"): Any
} catch {
  case _: PathNotFoundException => null
}

However, I am still looking for how to do it the "right" way

A: Try it like this using the JsonPath.parse() method:
Configuration configuration = Configuration.builder().options(Option.DEFAULT_PATH_LEAF_TO_NULL).build();
val value = JsonPath.parse(document, configuration).read("$.root.family.hasChild"));

Whether this is more or less efficient than catching an exception might depend on the implementation. Looking at the Jayway code, if the option DEFAULT_PATH_LEAF_TO_NULL and a non-existing leaf is encountered then simply null is returned, otherwise, an exception is thrown. The difference is probably not noticeable when dealing with a low number of cases, but things could add up if this happens a lot.


text:
Q: How to solve it simply to get difference equation have three branches meet to give y(n), 2 are coming from delayed output one coming from input enter image description hererencve
In Figure.3 a block diagram of a certain system is shown with input () and output (). a. Find the difference equation that relates input to output. b. Find the system transfer function ().


text:
Q: What are some alternatives to a boxplot? I am working on creating a website, which displays the census data for a user selected Polygons & would like to graphically show the distribution of various parameters (one graph per parameter).
The data usually has the following properties:

*

*The sample size tend to be large (say around 10,000 data points)

*The range in values tends to be quire large (for example, the minimum population can be less than 100 & the maximum can be something like 500,000)

*q1 usually is close to the minimum (say 200) while q2 & q3 will be within 10,000

*It doesn't look anything like a normal distribution

I am not a statistician and hence my description might not be exactly clear.
I would like to show this distribution on a graph, which will be seen by citizens (the layman, if you like).
I would have best liked to use a histogram, but it is not possible due to the large range of values, due to which making bins is not really easy & straight forward.
From what little I know about statistics,  a box plot is what is often used to show this kind of data, but I feel that for a layperson, deciphering the Box plot is not easy.
What are my options to show this data in an easy to understand manner?

A: I'd suggest you persevere with histograms. They're much more widely understood than the alternatives. Use a log scale to cope with the large range of values. Here's an example I cooked up in a couple of minutes in Stata:
I admit that the x-axis numerical labels weren't entirely straightforward or automatic, but as you're building a website I'm sure your programming skills are up to the challenge!

A: Here is a matlab function for plotting multiple histograms side-by-side in 2D as an alternative to box-plot. See the picture on the top. And here is another one
The density strip is another alternative to box-plot. It is a shaded monochrome strip whose darkness at a point is proportional to the probability density of the quantity at that point. This is an R implementation of the density strip

A: I rather like violin plots myself, as this gives an idea of the shape of the distribution.  However if the large range of values is the issue, then maybe it would be best to plot the log of the data rather than the raw values, that would then make choosing the box sizes for histograms etc.  As the display is for laymen, don't mention logs and mark the axis 10, 100, 1000, 10000, 100000, 1000000 etc.

A: How about using quantiles? It is not necessary to present a graph then, only a table. For village census I think the users will be most interested how many there are villages of certain size, so giving for example deciles will tell them them information such as $x\%$ of all the villages are smaller than the certain number. For deciles $x=0,10,20,...,100$. You can graph this table with the percents on a x-axis and the deciles on the y-axis.

A: If you are targeting the general population (i.e. a non statistical-savvy audience) you should focus on eye-candy rather than statistical accuracy.
Forget about boxplots, let alone violin plots (I personally find them very difficult to read)! If you'd ask the average street man what a quantile is, you would mostly get some wide eyed silence...
You should use barplots, bubble charts, maybe some pie charts (brrrr). Forget about error bars (although I would put SD in text somewhere where applicable).
Use colors, shapes, thick lines, 3D. You should make each chart unique and immediately easy to understand, even without having to read all the legends/axes etc.
Make a smart use of maps by coloring them.
Information is beautiful is a very good resource to get ideas. Look at this chart for instance: Caffeine and Calories: anyone can understand it, and it's pleasing to the eye.
And, of course, have a look at Edward Tufte's work.

A: A boxplot isn't that complicated. After all, you just need to compute the three quartiles, and the min and max which define the range; a subtlety arises when we want to draw the whiskers and various methods have been proposed. For instance, in a Tukey boxplot values outside 1.5 times the inter-quartile from the first or third quartile would be considered as outliers and displayed as simple points. See also Methods for Presenting Statistical Information: The Box Plot for a good overview, by Kristin Potter. The R software implements a slightly different rule but the source code is available if you want to study it (see the boxplot() and boxplot.stats() functions). However, it is not very useful when the interest is in identifying outliers from a very skewed distribution (but see, An adjusted boxplot for skewed distributions, by Hubert and Vandervieren, CSDA 2008 52(12)).
As far as online visualization is concerned, I would suggest taking a look at Protovis which is a plugin-free js toolbox for interactive web displays. The examples page has very illustrations of what can be achieved with it, in very few lines.

A: You might also want to have a look at beanplots.

[Source]
Implemented in R package by Peter Kampstra.


text:
Q: Taking Suggestions For User Management Scheme I'm beginning work on a web application that will have several distinct user types, example being Registered User, Site Admin, User Admin..etc.  Users may have more than 1 role.
In previous projects, I've been able to manage different user schemas with 3 tables: User, UserRole, User_UserRole.  With this approach, it was relatively easy to manage the M-M relationship between User and UserRole (in User_UserRole table).
However, I don't think this approach will work so nicely in this project for the following reason.  I need to be able to track who (site admin or user admin) approves each user.
I haven't been able to come up with any elegant solution for this, and am looking for some suggestions.  The simpler the better.

A: Just include a granted_by column in the User_UserRole table that points to the User table.


text:
Q: WooCommerce auto restore stock on order cancel I'm looking for a solution to automatically restore stock when order is canceled. I'm using PayU gateway on my client's site and it works by setting all orders on hold when waiting for payment and cancels them after 24 hours if there's no valid payment made. However, this means that WooCommerce built-in mechanism for freezing stock and then restocking after given time doesn't work (as the payment gateway sets the status to on hold).
There was a plugin called WooCommerce Auto Restore Stock by Gerhard Potgieter but it's an oldie and I was unable to find a similar solution in WordPress plugin repository or on Codecanyon.
Perhaps someone stumbled upon a solution to auto restore stock for cancelled orders that works with WC 3.0+?

A: According to woocommerce github issue here, they say that (24 hours hold stock & cancel without restock) is correct behavior. Orders can be cancelled for a variety of reasons - incorrect stock levels, faulty products, user choice etc etc therefore the re-increment of stock should be an entirely (manual) admin decision.
So, i try to override the function in my child theme`s functions.php and it works!
Here's the code :
remove_filter( 'woocommerce_cancel_unpaid_orders', 'wc_cancel_unpaid_orders' );
add_filter( 'woocommerce_cancel_unpaid_orders', 'override_cancel_unpaid_orders' );

function override_cancel_unpaid_orders() {
    $held_duration = get_option( 'woocommerce_hold_stock_minutes' );

    if ( $held_duration < 1 || 'yes' !== get_option( 'woocommerce_manage_stock' ) ) {
        return;
    }

    $data_store    = WC_Data_Store::load( 'order' );
    $unpaid_orders = $data_store->get_unpaid_orders( strtotime( '-' . absint( $held_duration ) . ' MINUTES', current_time( 'timestamp' ) ) );

    if ( $unpaid_orders ) {
        foreach ( $unpaid_orders as $unpaid_order ) {
            $order = wc_get_order( $unpaid_order );

            if ( apply_filters( 'woocommerce_cancel_unpaid_order', 'checkout' === $order->get_created_via(), $order ) ) {
                //Cancel Order
                $order->update_status( 'cancelled', __( 'Unpaid order cancelled - time limit reached.', 'woocommerce' ) );

                //Restock
                foreach ($order->get_items() as $item_id => $item) {
                    // Get an instance of corresponding the WC_Product object
                    $product = $item->get_product();
                    $qty = $item->get_quantity(); // Get the item quantity
                    wc_update_product_stock($product, $qty, 'increase');
                }
            }
        }
    }
    wp_clear_scheduled_hook( 'woocommerce_cancel_unpaid_orders' );
    wp_schedule_single_event( time() + ( absint( $held_duration ) * 60 ), 'woocommerce_cancel_unpaid_orders' );
}

Hope it helps.


text:
Q: What's wrong with using algebra on infinite series? I've recently found an article (referred somewhere on this site) criticizing the use of common rules of algebra on infinite series. To be honest, the video referred is one of the videos of Numberphile I liked the most. I mean, informally, to say a rule doesn't hold, I think one should find an example (in modern logic, a $\forall$ statement is true by default, and a $\exists$ false); say, associativity of addition for infinite series:
$$
S_1=(1-1)+(1-1)+(1-1)+(1-1)\cdots=0\\
S_2=1+(-1+1)+(-1+1)+(-1+1)+\cdots=1\\
\therefore S_1\neq S_2
$$
But what inconsistency does:
$$
\begin{align}
S=1&-1+1-1+\cdots\\
S+S=1&-1+1-1+\cdots+\\
&+1-1+1-1+\cdots=1\iff\\
\iff2S=1&\iff S=\frac12
\end{align}
$$
create? I'm not even getting into Cesàro summation. Why does the limit of a sum have to equal the sum itself?
Why can't we have
$$
\frac12=\sum_{n=0}^\infty\ (-1)^n\neq
\lim_{x\to\infty}\sum_{n=0}^x\ (-1)^n=
\text{st}\sum_{n=0}^H\ (-1)^n=
\text{undefined}
$$
After all, in here $x$ is an arbitrarily big real number, $H$ is a positive infinite hyperinteger number and $\infty$ is NaN, not a number. Where is the inconsistency?
Edit:
There are already a lot of comments, and I feel I haven't made myself clear. Maybe the question is more philosophical than I thought. Here is an attempt to make my still developing points clearer:

*

*$\cdots$ means the continuation to infinity of a series that continues the most simple pattern.

*

*Example: $\displaystyle\sum_{n=0}^\infty\ (-1)^n$ means that for whatever number you have taken the partial sum, you are as far from the result as you were in the beginning. As by $6.$, such non-converging sum cannot be computed directly.

*In the first example, it is proven that associativity does not hold for all infinite series, at least for divergent series, the same way $\sqrt a \sqrt b=\sqrt{ab}$ does not hold in $\mathbb C$. However, non-contradicting laws for associativity can be found:

*

*Associativity may not work infinitely for numbers within the same series, as $S\neq S_1\neq S_2\neq S$ shows. However, it works pairwise between infinite series.
$$
\begin{align}
S+S=1&-1+1-1+\cdots+\\
&+1-1+1-1+\cdots
\end{align}
$$
is the same as
$$
S+S=1+(-1+1)+(+1-1)+(-1+1)+\cdots
$$
which is $1$, as we have seen. This rule is consistent. Other pairwise associations for this will either give the same, or $2-2+2-2+\cdots$, which is also $1$.

*In other words, for any numbers, associativity works. So it works pairwise (2 series, 2 numbers per application), an infinite number of times. But it doesn't work within the same series, as each set of numbers would be a finite series, infinity is not a number, so it can't have not-a-number of times per application. That is,
$$
S_1=(1-1)+(1-1)+(1-1)+\cdots
$$
is the same as
$$
\begin{align}
S_1=1+&1+1+\cdots\\
-1-&1-1+\cdots
\end{align}
$$
and not the same as
$$
\begin{align}
S=1-&1+\\
+1-&1+\\
+1-&1+\\
+\cdots
\end{align}
$$

*The limit of a sum equals the sum when the sum converges. Example:
$$
\sum_{n=0}^\infty 2^{-n}=\lim_{x\to\infty}\sum_{n=0}^x 2^{-n}=2
$$

*The limit of a non-converging sum does not exist or is infinity, not a number. All sums have a value, even thought their limits might not have one, or the value of the sum is infinity.

*

*If that is the case, infinity, as not a number, cannot be directly summed with another sum (eliminating problems as $\infty-\infty$ by reason of lack of information).

*If according to non-contradictory rules, a value can be assigned to a sum, that is the value of the sum. See the example above for $1-1+1-1+\cdots$

*To distinguish between the values of two non-convergent sums, they first must be computed according to non-contradictory rules. Then their values can be compared, by transitivity of equality.

*A divergent sum cannot be computed directly (the reason why $S\neq S_1\neq S_2\neq S$), as by definition of infinity, one cannot reach it. Again, use non-contradictory rules, making a finite number of changes that maintain the value of the divergent sum (see the examples' consistency).
Thank you for reading,

A: What's wrong is that it's gibberish. You haven't actually made any concrete claim at all, you've just written some symbols down.
$$S=1-1+1-1...$$
What the hell does that mean? You haven't told me what the symbols on the right hand side represent, so I have no idea what's being claimed when you say that $S$ "equals" the right hand side.
$$S+S=...$$
And now you want to take this meaningless, undefined object, and add it to itself?
When I say it's gibberish, I really mean it. You may as well have written down:
$$S=SDG\mathcal{RREG}20358!!!?++()))($$
When you write down an expression using symbols, you need to specify what those symbols mean. That sounds obvious, but sometimes we write down meaningless things without realizing it. You simply never gave a definition for what object the symbolic expression $1-1+1-1...$ refers to.
Now, you could provide such a definition. And if, after doing that, you could prove that, under that definition, we are indeed justified in adding $S+S$ and rearranging the terms in the way that you did, you would be fine. But you have to prove that.

A: I was asked to develop my comment into an answer. I haven't taken the time to read the somewhat lengthy discussion surrounding this post, but here is my take.
For a given sequence $\{a_n\}_{n \geq 1}$ of numbers one can associate many possible values. In the case that $\{a_n \}_{n \geq 1}$ is summable, a common value to associate to it is
$$
  S
= \lim_{n \to \infty} \sum_{i=1}^n a_i
$$
which the notations
$$
\sum_{i=1}^\infty a_i \quad \text{ and} \quad a_1 + a_2 + \ldots
$$
 are used to denote. It happens that for convergent series some nice properties hold, such as
$\sum_{i=1}^\infty a_i + \sum_{i=1}^\infty b_i = \sum_{i=1}^\infty (a_i+b_i)$.
Of course, there may be other value association rules one would wish to employ. One you mentioned is Cesaro summation, which it happens specifies a value for a strictly larger set of sequences than does the convergent series rule, as I'll term it, and which yields the same value for members of both sets. The series you mention is a prominent example of something for which the Cesaro rule produces a value, but the convergent series rule does not.
Now, a few points:

*

*I am not sure of any well studied rules which assign values to all possible sequences (though trivial rules like "the value is the magnitude of the $10^{th}$ term" could be chosen).

*Since the notation $a_1 + a_2 + \ldots$ is, as far as I am aware, only standard for sequences $\{a_n\}_{n \geq 1}$ yielding convergent series, I'd be careful with notation, or at least specify clearly what your notation means a priori.

*Your ultimate question about whether something like associativity of the terms holds will depend on your rule. Without precisely specifying an exact rule, no one can say whether a given property will hold.

I suspect that the sensation of the question is that many people, possibly including yourself, are unsure exactly which rule you are using, and this confusion is compounded by the fact that the notation you are using is standard notation for a rule which you clearly cannot be using (namely the convergent series rule).
I hope that was helpful!

A: You ask what inconsistency is there in
\begin{align}
S=1&-1+1-1+\cdots\\
S+S=1&-1+1-1+\cdots+\\
&+1-1+1-1+\cdots=1\iff\\
\iff2S=1&\iff S=\frac12
\end{align}
You said before that
$$S_1=(1-1)+(1-1)+(1-1)+(1-1)\cdots=0\\
S_2=1+(-1+1)+(-1+1)+(-1+1)+\cdots=1\\
$$
In the reasoning I copied first, you decided to use the "$S_2$" convention. But unless you believe that what you wrote for $S_1$ is wrong, you could have used that one too. So
$$
2S=0.
$$
And you have proven that $1=0$.


text:
Q: Disable Python return statement from printing object it returns I want to disable "return" from printing any object it is returning to python shell.
e.g A sample python script test.py looks like:
def func1():
    list = [1,2,3,4,5]
    print list
    return list

Now, If i do following:
python -i test.py
>>>func1()

This always give me two prints on python shell.
I just want to print and get returned object.

A: In general, printing from within a function, and then returning the value, isn't a great idea.
In fact, printing within a function is most often the wrong thing.  Most often functions get called several times in a program.  Sometimes you want to print the value, most often you just want to use that data for something.
Let the function just return it's value.  Let the code that called the function print it out, if that is the right thing to do.

A: There's no way to configure the Python shell suppress printing the return values of function calls.  However, if you assign the returned value to a variable, then it won't get printed.  For example, if you say
rv = func1()

instead of
func1()

then nothing will get printed.

A: The reason for the print is not the return statement, but the shell itself. The shell does print any object that is a result of an operation on the command line.
Thats the reason this happens:
>>> a = 'hallo'
>>> a
'hallo'

The last statement has the value of a as result (since it is not assigned to anything else). So it is printed by the shell.
The problem is not "return" but the shell itself. But that is not a problem, since working code normaly is not executed in the interactive shell (thus, nothing is printed). Thus, no problem.

A: If you don't want it to show the value, then assign the result of the function to a variable:
H:\test>copy con test.py
def func1():
  list = [1,2,3,4,5]
  print list
  return list
^Z
        1 file(s) copied.

H:\test>python -i test.py
>>> func1()
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
>>> x = func1()  # assign result to a variable to suppress auto printout
[1, 2, 3, 4, 5]
>>>

A: You can use something like this,
_ = my_func()

A: The simple solution is to remove the return.
def func1():
    list = [1,2,3,4,5]
    print list

Since the shell will not print out None values.
If you still need to return the value for calls from other functions, consider adding shell API on top.
def _func1():
    list = [1,2,3,4,5]
    print list
    return list

def func1():  # Shell version of _func1.
    _func1()  # Don't return the value.

Now your code can call _func1 while in the shell you use func1.
>>> func1()
[1, 2, 3, 4, 5]
>>>

Note: I know this is an old question but I came here from a google search so others will too.


text:
Q: i just want to add the name john to the end of the vertical list but i dont know how use basic function no imports please I want to add john to the list but i don't know how.
Note the spaces in between the names dont have a comma it only has value 0 unlike normal list.
here is a picture of the names list
I expect the output to include john at the end of the list.

A: There is a builtin list method in python exactly for doing what you want, called .append().
Let's say you have this:
a = ["maria", "jack", "dave"]
b = "john"

To insert john to the a list, all you have to do is:
a.append(b)

You might also call the appended value directly, as below:
a.append("john") #supposing your list is in a variable named a

The append will always include the variable/value at the end of the list.
You might have some good insights reading the docs also:
https://docs.python.org/3/tutorial/datastructures.html


text:
Q: Drupal 7 Pages Keep loading I'm having a problem with a Drupal 7 install where pages keep loading.
The page will load and then repeat itself over and over until Chrome suggests killing the page.
It seems to happen at random times and there are no JS errors being reported or errors retrieving the page.
Anyone else had similar issues?
Modules include:

*

*Panels

*Views

*Ctools

*etc

A: This is usually caused by url aliases and/or url redirects doing some sort of circular definition. I've also seen this caused by login tobogin module setting up a circular redirect with something in the url redirect module. Find out which page is doing it and check your alieses and redirects for circular definition. It will probably be tricky to catch as it is usually two steps a -> b then b-> a, or something like that.


text:
Q: How to login to website using webbrowser control I need to programmtically key in the username, password for a website using Webbrowser control in Visual Basic 6.0 application (please note it is not .Net application) and also click on Login button.
Also I am not trying to hack or spam. The requirement is part of interfacing that I am trying to create between multiple applications.
Please let me know how to go about this.
Thanks

A: You can use the Document property of the WebBrowser control to interact with the HTML page.  In your case, it would depend on the structure of the web site, but you should be able to do something like this (untested)
With webBrowser.Document.forms(1)
    .getElementByName("username").value = "username"
    .getElementByName("password").value = "password"
    .submit()
End With

A: I think you should use some HTTP request and store the returned cookie (there probably will be one). Observe the login process on the page if it's GET or POST method, and if it uses a cookie. I don't think you need webbrowser control for this.


text:
Q: What are the drawbacks to using a private local repository for Hudson jobs? Hudson provides the option to have a Maven build job utilize a private local repository, or use the common one from the Maven installation, i.e. one shared with other build jobs.  I have the sense that our builds should use private local repositories to ensure that they are clean builds.  However, this causes performance issues, particularly with respect to bandwith of downloading all dependencies for each job -- we also have the jobs configured to start with a clean "workspace", whcih seems to nuke the private maven repo along with the rest of the build space.
For daily, continuous integration builds, what are the pros and cons of choosing whether or not to use a private local maven repository for each build job?  Is it a big deal to share a local repo with other jobs?

A: Interpreting the jenkins documentation, you would use private Maven repository if

*

*You end up having builds incorrectly succeed, just because your have all the dependencies in your local repository, despite that fact that
  none of the repositories in POM might have them.

*You have problems regarding having concurrent Maven processes trying to use the same local repository.

Furthermore

When using this option, consider setting up a Maven artifact manager
  so that you don't have to hit remote Maven repositories too often.

Also you could explore your scm's clean option (rather than workspace clean) to avoid this repository getting nuked.

A: I believe Sonatype recommends using a local Nexus instance, even though their own research shows (State of the Software Supply Chain report 2015) that less then 5% of traffic to Maven Central comes from such repositories.
To get back to the question, assuming you have a local Nexus instance and high bandwidth connectivity (tens of Gbps at least) between your build server (e.g. Jenkins) and Nexus, then I can see few drawbacks to using a private local repo, in fact I would call the decrease in build performance a reasonable trade-off.
The above said, what exactly are we trading off? We are accepting a small performance penalty on the downside and on the upside we know with 100% certainty that independent, clean builds against with our local Nexus instance as proxy works.
The latter is important because consider the scenario where the local repo on the build server (probably in the jenkins' user home directory) has an artefact that is not cached in Nexus (this is not improbable if you started off your builds against Maven Central). This out-of-sync scenario is suboptimal because it is possible to get a scenario where your cache TTL settings in Nexus means that builds fail if Nexus' upstream connectivity to Central was down temporarily.
Finally, to add more to the benefits side of the trade-off, I spent hours today getting an artefact in the shared Jenkins user .m2/repository today. Earlier on in the day upstream connectivity to Central was locally up and down for hours (mysterious issue in enterprise context). In the end I deleted the entire shared jenkins user .m2/repository so it all be retrieved from the local Nexus.
It's worth considering having builds using a local .m2/repository (in jenkins user home directory) as well as builds using private local repositories (fast and less fast builds). In my case however I may opt for private local repositories only in the first instance - I may be able to accept the penalty if I optimise the build by focussing on low hanging fruit (e.g. split up multi module build).


text:
Q: OpenGL Output Window shrinks to 0 x 0 window immediately I have a problem with OpenGL programs using OpenGLUT that are compiled and run in Visual Studio 2012. The program compiles fine and when I press run an 800 x 600 window opens and displays the image that I want. However, the window immediately begins shrinking until it reaches 0 x 0 in about 2 seconds and then stays open. I'm not quite sure what the problem is and Google searches turned up no relevant information. Here are some screenshots of the problem:

The above screenshot was taken immediately after the program started. The below screenshot was taken about a second after the program started without any interaction from me.

The output window continues to shrink until it is 0 x 0 size. Here is my code and any suggestions would be helpful.
#ifdef __APPLE_CC__
#include <GLUT/glut.h>
#else
#include <OpenGlut.h>
#endif

// Clears the window and draws the tetrahedron.  The tetrahedron is  easily
// specified with a triangle strip, though the specification really isn't very
// easy to read.
void display() {
  glClear(GL_COLOR_BUFFER_BIT);

  // Draw a white grid "floor" for the tetrahedron to sit on.
  glColor3f(1.0, 1.0, 1.0);
  glBegin(GL_LINES);
  for (GLfloat i = -2.5; i <= 2.5; i += 0.25) {
    glVertex3f(i, 0, 2.5); glVertex3f(i, 0, -2.5);
    glVertex3f(2.5, 0, i); glVertex3f(-2.5, 0, i);
  }
  glEnd();

  // Draw the tetrahedron.  It is a four sided figure, so when defining it
  // with a triangle strip we have to repeat the last two vertices.
  glBegin(GL_TRIANGLE_STRIP);
    glColor3f(1, 1, 1); glVertex3f(0, 2, 0);
    glColor3f(1, 0, 0); glVertex3f(-1, 0, 1);
    glColor3f(0, 1, 0); glVertex3f(1, 0, 1);
    glColor3f(0, 0, 1); glVertex3f(0, 0, -1.4);
    glColor3f(1, 1, 1); glVertex3f(0, 2, 0);
    glColor3f(1, 0, 0); glVertex3f(-1, 0, 1);
  glEnd();

  glFlush();
}

// Sets up global attributes like clear color and drawing color, enables and
// initializes any needed modes (in this case we want backfaces culled), and
// sets up the desired projection and modelview matrices. It is cleaner to
// define these operations in a function separate from main().
void init() {

  // Set the current clear color to sky blue and the current drawing color to
  // white.
  glClearColor(0.1, 0.39, 0.88, 1.0);
  glColor3f(1.0, 1.0, 1.0);

  // Tell the rendering engine not to draw backfaces.  Without this code,
  // all four faces of the tetrahedron would be drawn and it is possible
  // that faces farther away could be drawn after nearer to the viewer.
  // Since there is only one closed polyhedron in the whole scene,
  // eliminating the drawing of backfaces gives us the realism we need.
  // THIS DOES NOT WORK IN GENERAL.
  glEnable(GL_CULL_FACE);
  glCullFace(GL_BACK);

  // Set the camera lens so that we have a perspective viewing volume whose
  // horizontal bounds at the near clipping plane are -2..2 and vertical
  // bounds are -1.5..1.5.  The near clipping plane is 1 unit from the camera
  // and the far clipping plane is 40 units away.
  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();
  glFrustum(-2, 2, -1.5, 1.5, 1, 40);

  // Set up transforms so that the tetrahedron which is defined right at
  // the origin will be rotated and moved into the view volume.  First we
  // rotate 70 degrees around y so we can see a lot of the left side.
  // Then we rotate 50 degrees around x to "drop" the top of the pyramid
  // down a bit.  Then we move the object back 3 units "into the screen".
  glMatrixMode(GL_MODELVIEW);
  glLoadIdentity();
  glTranslatef(0, 0, -3);
  glRotatef(50, 1, 0, 0);
  glRotatef(70, 0, 1, 0);
}

// Initializes GLUT, the display mode, and main window; registers callbacks;
// does application initialization; enters the main event loop.
int main(int argc, char** argv) {
  glutInit(&argc, argv);
  glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
  glutInitWindowPosition(80, 80);
  glutInitWindowSize(800, 600);
  glutCreateWindow("A Simple Tetrahedron");
  glutDisplayFunc(display);
  init();
  glutMainLoop();
}

A: Probably the best solution - abandon GLUT. I recommend you to use GLFW instead.
GLFW:

*

*Has more features.

*Is simpler.

*Has a better designed API.

*Is modern and is beign actively developed.

*Has a very good documentation.

*Just works.


text:
Q: Is there any JSON-RPC implementation in C++ that is transport-agnostic? I am currently looking for a JSON-RPC library that implements the 2.0 specification and is, or at least can be easily adapted to be, transport-agnostic, implemented in c++ and have as few dependencies as possible.
In my search for it, I already looked for on the obvious places and the more comprehensive collections below:

*

*http://json-rpc.org/wiki/implementations (outdated info)

*https://en.wikipedia.org/wiki/JSON-RPC
Header-only / standard c++11 implementation, for a quick drop in a new project, that can be used on different platforms is a plus!
Please note that I am not looking for a recommendation on which one is best or not, as I can most likely judge that myself. What I am asking is if anybody else know about a library that meet those technical requirements above, or at least already found a way to work around those requirements using an implementation that is public available.
Thank you.

A: After a lot of digging, the closest I could find that meet those requirement, specifically the one to be able to be adapted to be transport-agnostic was:
https://github.com/erijo/xsonrpc
It is still not a header-only implementation, and it has some external dependencies that makes it cumbersome to compile/use on different platforms and projects, but it was still the closest one I could find.
I might adapt this one to make it 100% in compliance with the original requirements of my question. Will update the question when I do so.

UPDATE
Using xsonrpc as a starting point, I put together an implementation that satisfy all those requirements and published as an opensource project:
https://github.com/uskr/jsonrpc-lean - include-only, transport-agnostic JSON-RPC 2.0 client/server implementation


text:
Q: Issue related to Database Backup and Restore in .Net I have C#.Net winform application having SQL Server Database in SQLExpress with Windows Authentication.
There is a Option related to Backup and restore batabase. In DBbackup i have provided user to select folder and database will be copy to that folder.
for restore database i have written following line:
System.IO.File.Copy(filePath, Application.StartupPath + "\\dbSTK.mdf",true);

it throws an exception saying dbSTK is already in use. How can i overwrite file that is already in use?

A: A .mdf file is not a backup file, but the actual data file. You cannot simply copy a running database (or overwrite a running database.) Typically you would have to use sp_detach_db to get the file in state that you can copy/archive and sp_attach_db (or create database for attach) to restore the db.
If you just made a copy of the running .mdf as a backup, then the odds are pretty good that you won't be able to attach that file.
While the above is the correct method to detach/attach a database, I would suggest actually performing a backup/restore. It doesn't require taking the database offline and is generally a better approach to managing backups.
How to attach a data file in SQL Server: http://msdn.microsoft.com/en-us/library/ms179877.aspx
How to detach a database in SQL Server: http://msdn.microsoft.com/en-us/library/ms188031.aspx
How to perform a backup on SQLEXpress: http://msdn.microsoft.com/en-us/ms186865.aspx
How to restore a backup on SQLExpress: http://msdn.microsoft.com/en-us/ms186858

A: Don't backup by just copy the database file. Use the SQL command BACKUP DATABASE. Using this, the server does not need to be stopped and the server can clean up internal stuff.

A: Do not copy the mdf file.
If you want to backup by code, check out this posting
Using Smo.Backup to backup SQL Server database to string
If you want to schedule a backup (to your backup folder) create a new maintenance plan using the maintenance plan wizard in sql management studio:
http://msdn.microsoft.com/en-us/library/ms189036.aspx


text:
Q: Retrieve all records if no record exist in the joining table I have these three tables,
PO_HEADER

po_number
vendor_name

10001
Xyz

100002
ABC

PO_LINEITEM

line_number
po_number
item_quantity
recieved_quantity

0001
10001
20
10

0002
10001
80
10

0002
10002
40
35

SHIPMENT_LINEITEM

line_number
po_number
shipping_quant

0001
10001
20

How to retrieve order_master based on these two conditions

*

*if any po_lineitem having item_quantity > recieved quantity.

*if po_lineitem having item_quantity > (sum of previously shippingquantity from asn_lineitem for same line_number & poNumber) .2(b) if there no items in the asn_lineitem this should return true.

I wrote this query but was not able to achieve 2(b)
select count(*) from erp_po_header
where po_number in
(select erlitms.po_number from erp_po_line_items erlitms
JOIN
   (select sum(shipping_quantity) as total_prev_shipped_items,po_number,item_number from
  asn_lineitem
  Group by po_number,item_number)
   asn_items
 ON erlitms.po_number = asn_items.po_number
and erlitms.item_number = asn_items.item_number
and erlitms.item_quantity > CAST (erlitms.received_quantity AS INTEGER)
and erlitms.item_quantity > asn_items.total_prev_shipped_items )


text:
Q: What does the signature of this bilinear form on the representation algebra k[G] tell about representations? Let $G$ be a finite group and $k$ a field. There is a symmetric bilinear form
$$
\langle f,h\rangle =\frac{1}{|G|}\sum_{g\in G}f(g)h(g^{-1})
$$
on the group algebra $k[G]$. If I am not mistaken, this form should be non-degenerate.
If $k=\mathbb{C}$ or $k=\mathbb{R}$, there is a signature $(p,q)$ for this form.
Is there a representation theoretic interpretation for the signature? (E.g. does it count some type of representation, etc.?)


text:
Q: Is there a way for an Android app to grant permission for another app to access it's storage? I have read the Android docs, and I am not hopeful, but I thought I would give it a go anyways.  Basically, the situation is that I have 2 apps.  App A is a content manager that checks on a secured server for content files and downloads them to its storage on the Android device.  App B (and any other apps that later may be needed) needs to view the content in App A's storage.  Usually FileProvider would be the way I go, but there's a problem with that.
Many of the content files are HTML documents with relative links.  FileProvider doesn't give access to every linked file to App B, so links are regularly broken.  I am not sure, as it is not my project, if App A can be directed to download to a shared location either.
Is there a way to:

*

*have App A grant what apps are allowed read access to its storage?

*have FileProvider grant general read access to a directory and all its sub-directories?

*anything else someone might think of to get App B to view the files App A downloads?
or is this, as I fear, currently not possible due to Android restrictions?
Thank you.

A: As long as both your apps (A and B) are signed with same certificate then you can share resources between each other. This is a common practice within a lot of apps available at play store.
https://developer.android.com/guide/topics/manifest/permission-element.html#plevel
https://developer.android.com/guide/topics/manifest/manifest-element.html#uid