dimanche 26 avril 2015

Loading remote XML data into Azure SQL Server DB


I have managed to load remote (via a URL) XML data directly into a SQL Server DB instance on a local machine. I can then select the XML from the table.

I am attempting to replicate this is an Azure SQL DB instance.

Can anyone provide assistance with this? OLE is not available in WASD.

Presumably an Azure Runbook script to download the file to an Azure VM and then attempt to load into WASD?

Windows Azure SQL Database - WASD


How to delete child node from xml using php


$xpath = new DOMXPATH($xml);

foreach($xpath->query("/root/info[name = '$c_name']") as $node)
{
    $node->parentNode->removeChild($node);
}

Am getting this error when executing this code on localhost. "Warning: DOMXPath::query(): Invalid expression " I guess there is an error in the foreach loop. How can i remedy for this!


How to generate xml description for each function using nusoap in php?


I have developed a soap api using nusoap in php. I have created some function for that. I have created a file service.php & when i hit this file on url i get a document for all functions. like this! My nusoap DOC

But i want to have a xml like description for my functions.Like this REQUIRED OUTPUT

Please tell me how to do it

This is my code for service.php

<?php
require_once "lib/nusoap.php";
require_once "functions.php";
$server=new nusoap_server();
$server->configureWSDL("SOAP", "urn:soapn");
$server->register("addRecord",
        array("fname"=>"xsd:string","lname"=>"xsd:string","buis_name"=>"xsd:string","phone_num"=>"xsd:int","city"=>"xsd:string","state"=>"xsd:string",           "zipcode"=>"xsd:int","email"=>"xsd:string"
        ,"w_store"=>"xsd:string","con_store"=>"xsd:string","ind_store"=>"xsd:string","gas_staion"=>"xsd:string","other"=>"xsd:string"),
        array("return" => "xsd:string"),
        "urn:soap",
       "urn:soap#addRecord",
       "rpc",
       "encoded",
      "Add user information to database");
 $server->register("checkLogin",
        array("email"=>"xsd:string","password"=>"xsd:string"),
        array("return" => "xsd:string"),
        "urn:soap",
       "urn:soapn#checkLogin",
       "rpc",
       "encoded",
      "Verify UserLogin"); 
$HTTP_RAW_POST_DATA=isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : '';
$server->service($HTTP_RAW_POST_DATA);


?> 

Please help me out.


What is the purpose of specifying a schema in a web xml?


Data Type Definition (DTD) and XML Schema Definition (XSD) - These are the two type of specifying a schema in a web xml. What is the purpose of a specifying this exactly?

I have specified this in my TestNG.xml file like this

<!DOCTYPE suite SYSTEM "http://ift.tt/19x2mI9" >

What is the purpose of testng-1.0.dtd here?

I got some information here on DTD but I really don't understand the purpose of adding this in the XML file? http://ift.tt/1FnyFxE

Any help in explaining this is much appreciated. I am building a test automation framework using Selenium WebDriver and using this in my TestNG.xml file


Calling text from XML to the manually created object in Activity's method in Android


I am trying to create a submit and clear button by a for loop in the onCreate() method by using programming instead of XML layout, and I have defined the label text of the button from the string.xml and assigned it. However, the application has been stopped when I run it.

I have tried to hide the button label setting and it can be work as useal(2 button displayed on the apps without error), thus I am wondering if it is not possible to call string label directly from XML?? or I missed something to do so. Pls give me some comment.

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

    TableLayout tableLayout = new TableLayout(this);
    tableLayout.setOrientation(TableLayout.VERTICAL);
    setContentView(tableLayout);

    Button[] buttons = new Button[2];

    //button label
    buttons[0].setText(R.string.label_calc);
    buttons[1].setText(R.string.label_clear);

    for(int i=0; i<2; i++) {
        buttons[i] = new Button(this);
        tableLayout.addView(buttons[i]);
    }

}

Here is the label setting in string.xml:

<!-- button label-->
<string name="label_calc">Calc</string>
<string name="label_clear">Clear</string>


SQL Server XQuery XML indexing


Using SQL Server 2008-

I have XML data stored in a column of my table which is the result of exporting some drawing info:

<layout>
    <config>
        <graphic_type>Box</graphic_type>
        <data_access>
        </data_access>
        <data>
            <dimension x="1" y="2" z="3" />
            <curve_info ir="-1.5" or="1.5" degree="0"/>
            <position x="4" y="5" z="6" />
            <rotation x="7" y="8" z="9" />
            <color>FFD3D3D3</color>
            <is_position_relative>false</is_position_relative>
        </data>
    </config>
    <config>
        ...
    </config>
</layout>

Where the number of to draw individual pieces is unknown. Currently if I wanted to do something like move the entire drawing 100 units along the X-axis, I have SQL code like:

SET @xTrans = 100
UPDATE TableName
SET xmlColumn.modify('replace value of (//data/position/@x)[1] with sql:variable("@xTrans")')
SET xmlColumn.modify('replace value of (//data/position/@x)[2] with sql:variable("@xTrans")')
SET xmlColumn.modify('replace value of (//data/position/@x)[3] with sql:variable("@xTrans")')
...
SET xmlColumn.modify('replace value of (//data/position/@x)[20] with sql:variable("@xTrans")')

And I essentially do that an arbitrary number of times because I don't know how many nodes actually exist in each drawing. I am fairly new to SQL, and even more so to XQuery, but is there a better way to go about this problem?

To be more extensible, the next problem I have is when Devices are drawn on top of this model, they were originally drawn in 2d before being exported to xml files, and so they take on the height value (happens to be the Y-axis in my case) of the first section of the drawing, when the devices X and Z coordinates potentially place it at the end of the entire drawing. This causes some devices to be floating either above or below the models. The only thing I could think to write for this problem is something like:

-- Determine if moving along X or Z axis by Y rotation
-- If its the Z-axis, find the range that section covers with position+dimension
    -- @range = (///position/@z)[1] + (///dimension/@z)[1]
-- See if the device falls in that range
    -- If (///position/@z)[1] < device position @z < @range
-- Then we need the rotation of that box in the Z-axis
-- to calculate the height change for the device

But this would involve having to copy and paste that code ~15 times (I'm not sure what the largest number of components a model could have, I have seen 6 on the current project) and changing the index [1] which seems extremely inefficient.

The device XML layout is exactly the same as the model, just with a different value for .


How to convert partial XML to hash in Ruby


I have a string which has plain text and extra spaces and carriage returns then XML-like tags followed by XML tags:

String = "hi there.

<SET-TOPIC> INITIATE </SET-TOPIC>

<SETPROFILE>
   <KEY>name</KEY>
   <VALUE>Joe</VALUE>
</SETPROFILE>

 <SETPROFILE>
   <KEY>email</KEY>
   <VALUE>Email@hi.com</VALUE>
</SETPROFILE>

<GET-RELATIONS>
  <COLLECTION>goals</COLLECTION>
  <VALUE>walk upstairs</VALUE>
</GET-RELATIONS>
So what do you think?

Is it true?
 "

I want to parse this similar to use Nori or Nokogiri or Ox where they convert XML to a hash.

My goal is to be able to easily pull out the top level tags as keys and then know all the elements, something like:

Keys = ['SETPROFILE', 'SETPROFILE', 'SET-TOPIC', 'GET-OBJECT']

Values[0] = [{name => Joe}, {email => email@hi.com}]
Values[3] = [{collection => goals}, {value => walk up}]

I have seen several functions like that for true XML but all of mine are partial.

I started going down this line of thinking:

parsed = doc.search('*').each_with_object({}) do |n, h| 
  (h[n.name] ||= []) << n.text 
end


How to use XML Auto to get the format obtained by XML Path in sql server


I am using sql server 2012.

This is my query:

CREATE TABLE #XmlTestTable 
(
    ID INT PRIMARY KEY IDENTITY(1,1),
    FirstName VARCHAR(20),
    LastName VARCHAR(20)
)
INSERT INTO #XmlTestTable (FirstName,LastName) VALUES
('John','Doe'),
('Jane','Doe'),
('Brian','Smith'),
('Your','Mom')

select  FirstName as "Name/@FN",LastName  as "Name/@LN" from #XmlTestTable for xml path('X'),root('Y')

It gives results like this:

<Y>
  <X>
    <Name FN="John" LN="Doe" />
  </X>
  <X>
    <Name FN="Jane" LN="Doe" />
  </X>
  <X>
    <Name FN="Brian" LN="Smith" />
  </X>
  <X>
    <Name FN="Your" LN="Mom" />
  </X>
</Y>

How can I obtain this format using XML AUTO

select  FirstName as "Name/@FN",LastName  as "Name/@LN" from #XmlTestTable for xml auto

generates this:

<_x0023_XmlTestTable Name_x002F__x0040_FN="John" Name_x002F__x0040_LN="Doe" />
<_x0023_XmlTestTable Name_x002F__x0040_FN="Jane" Name_x002F__x0040_LN="Doe" />
<_x0023_XmlTestTable Name_x002F__x0040_FN="Brian" Name_x002F__x0040_LN="Smith" />
<_x0023_XmlTestTable Name_x002F__x0040_FN="Your" Name_x002F__x0040_LN="Mom" />

And could anybody tell me why I get the sting like _x002F__x0040_FN in above format?


How to set data from xml parser into same list view (first i parsed 10 data on list view) .?


How to set data from XML parser into same list view (first i parsed 10 data on list view) .?? There is anyone know about this maybe i can use in adapter 'int position =arg 0;' and how to attach the second data in the last of first XML parsed. please help me is that any logic than please give me. Please its urgent.


samedi 25 avril 2015

Large XML file - wrap elements inside tags using XSLT or by manipulating the XML as String?


I have a fairly large XML file, around 3-4 MB and I need to wrap certain elements inside tags. My Xml has the following structure:

<body>
    <p></p>
    <p>
        <sectPr></sectPr>
    </p>
    <p></p>
    <p></p>
    <tbl></tbl>
    <p>
        <sectPr></sectPr>
    </p>
</body>

Of course, all the p and tbl elements will repeat themselves inside the body until the end of the file (also each of the elements presented above will have children - I just took them out for the sake of simplicity). As an estimate, I will have around 70 elements containing sectPr inside body, not necessarily in the order I described above.

What I would like to do, is to wrap all the elements that are starting from an element containing sectPr to the next element containing sectPr into another tag. As a result, my XML should look like this:

<body>
    <p></p>
    <myTag>
        <p>
            <sectPr></sectPr>
        </p>
        <p></p>
        <p></p>
        <tbl></tbl>
    </myTag>
    <myTag>
        <p>
            <sectPr></sectPr>
        </p>
    </myTag> 
</body>

Also, another requirement is that the operation must be performed under 40 seconds.

My question is: Do you think is possible to achieve this result using XSLT and if this is the case could please provide a short description on how can I do it, or do you think is better to read the XML file as String and then add the tags by manipulating the string?

Also, as programming language, I am using Visual Basic.

Thank you in advance.


Display PHP array or XML in a HTML table


I have to develop two web service from different languages and combined these two using PHP. Normally web services contain PHP and I managed to combine two web services and get the combined XML output. but now i have to display these XML inside a HTML table. I tried to create HTML table manually but it doesn't work

this is my PHP code that combine two web services and get XML output

$PHPserv = $PHPwebservice . "ID.php?id=" . $encodedval;
        // header('Content-type:  text/xml');
        error_reporting(E_ALL);
        foreach(file($PHPserv) as $node)
            {
            $str = $node;
            }

        if (strlen($str) > 13)
            {
            $PHPresult->loadXML($str);
            $result1 = true;
            }

        $parray = array(
            'id' => $geturlval
        );
        $ASMXserv = new SoapClient($ASMXwebservice);
        $str = $ASMXserv->Listbirdstringbldryid($parray)->ListbirdstringbldryidResult->any;
        if (strlen($str) > 140)
            {
            $ASMXresult->loadXML($str);
            $result2 = true;
            }

        if ($result1 == true && $result2 == true)
            {
            $xmlRoot = $PHPresult->documentElement;
            foreach($ASMXresult->documentElement->firstChild->childNodes as $node2)
                {
                $node = $PHPresult->importNode($node2, true);
                $xmlRoot->firstChild->appendChild($node);
                }

            echo $PHPresult->saveXML();


}

After I commented line header('Content-type: text/xml'); it will output a plain HTML array (i think) but how can I put inside a HTML table

I have only 1 day left to complete this. Someone please help me


Send a Map (internally converted to XML) to a Web Service


I have a Map in Java and I want to send it to a Web Service. The Web Service expects an XML.

Example

Map<String, String> dummyMap = new HashMap<String, String>();

dummyMap.put("A", "a");
dummyMap.put("B", "b");
dummyMap.put("C", "c");
dummyMap.put("D", "d");

Is there a tool where I can send this Map that will be internally converted to an XML and sent to the Web Service in Java?


VB.NET: Doc to XML tag


Need help.

I have make simple program convert doc file to xml file using vb.net.

Dim app As Word.Application = New Word.Application
Dim doc As Word.Document = app.Documents.Open(txtFileName.Text)

Dim writer As New XmlTextWriter("product.xml", System.Text.Encoding.UTF8)
writer.WriteStartDocument(True)
writer.WriteStartElement("JUDGEMENT")
writer.Formatting = Formatting.Indented

For Each paragraph As Word.Paragraph In doc.Paragraphs

paragraph.Next()
writer.WriteStartElement("p")

If (paragraph.Range.Font.Bold) Then
writer.WriteStartElement("b")
writer.WriteString(paragraph.Range.Text.Trim)
writer.WriteString(paragraph.Range.Text)
writer.WriteEndElement()
Else
writer.WriteString(paragraph.Range.Text)
End If

writer.WriteEndElement()

Next

writer.WriteEndElement()
writer.WriteEndDocument()
writer.Close()
app.Quit()

The result will be something like this. Problem is bold tag is not at the bold font, it put at the end of sentences.

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<JUDGEMENT>
  <p>
    <b>Lorem Ipsum is simply dummy text of the printing and typesetting industry.</b>
  </p>
  <p>
    <b>Lorem Ipsum is simply dummy text of the printing and typesetting industry.</b>
  </p>
</JUDGEMENT>

But I need a result like this

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<JUDGEMENT>
  <p>
    <b>Lorem Ipsum </b>is simply dummy text of the printing and typesetting industry.
  </p>
  <p>
    <b>Lorem Ipsum </b>is simply dummy text of the printing and typesetting industry.
  </p>
</JUDGEMENT>

What do I need to add or changes? Thanks guys.


Change text color inside PopUpMenu Android Studio


I am trying to change the text color inside the PopUpMenu for a Android App. Everything works, except "TextColor". What am I doing wrong? I am trying to do this with XML, but any suggestion is welcome.

    <style name="AppTheme" parent="@style/Theme.AppCompat.Light.DarkActionBar">
    <item name="actionBarStyle">@style/MyActionBar</item>
    <item name="dropDownListViewStyle">@style/PopupMenuListView</item>
</style>

<style name="MyActionBar" parent="@style/Widget.AppCompat.ActionBar.Solid">
    <item name="background">@drawable/actionbar_background</item>
</style>

<!-- OverFlow menu Styles -->
<style name="PopupMenuListView" parent="@style/Widget.AppCompat.Light.ListView.DropDown">
    <item name="android:divider">#ff26ff1a</item>
    <item name="android:dividerHeight">2dp</item>
    <item name="android:background">#33B5E5</item>
    <item name="android:textColor">#EE134A</item>
</style>


How to find given content of node and modify xml file using C++/CLI


LoginsAndPasswords.xml looks like this:

<?xml version="1.0" encoding="Windows-1250"?>
<AllUsers>
  <User>
    <id>2</id>
    <login>a</login>
    <password>a</password>
  </User>
  <User>
    <id>5</id>
    <login>b</login>
    <password>b</password>
  </User>
  <User>
    <id>7</id>
    <login>c</login>
    <password>c</password>
  </User>
</AllUsers>

At first I insert some login name into loginBox. Then before i add new user I want to check if that login already exists in my xml file. For example I would like to check if login named loginBox->Text=b already exists in xml file. If yes I want to show MessageBox("Given login already exists choose another"). If no I want to create new User in my xml file with given unique login(loginBox->Text), given password(passwordBox->Text) and id greater than max id value of all users.


How can I write to the root element?


When I use the following code I can write successfully to the XML file however it will write outside the root element.

        StreamWriter sw = File.AppendText(Environment.CurrentDirectory + "\\Settings.xml");
        XmlTextWriter xtw = new XmlTextWriter(sw);

        xtw.WriteStartElement("connection");
        xtw.WriteElementString("id", name);
        xtw.WriteElementString("Version", "2.3.1");
        xtw.WriteElementString("Server", ip_textBox.Text);
        xtw.WriteElementString("Port", port_textBox.Text);
        xtw.WriteElementString("Uid", user_textBox.Text);
        xtw.WriteElementString("Password", pass_textBox.Text);

        xtw.Close();

After the code runs the XML looks like this:

<?xml version='1.0' encoding='utf-8' ?>
<root>

</root>
<connection><id>test</id><Version>2.3.1</Version><Server>127.0.0.1</Server><Port>3306</Port><Uid>root</Uid><Password>root</Password>

When it should look like:

<?xml version='1.0' encoding='utf-8' ?>
<root>
  <connection>
     <id>Test</id>
     <Version>2.3.1</Version>
     <Server>127.0.0.1</Server>
     <Port>3306</Port>
     <Uid>root</Uid>
     <Password>root</Password>
  </connection>
</root>

Again my question is how can I write inside the root element?


xml not retrived by javascript


This may seem too trivial but I have tried all possible methods

  1. async=true (onreadystatechange)
  2. async=false (xmlhttp open)

source http://ift.tt/ZxhTtu

3.xmlhttp.open("GET","http://"+location.host+"/cd_catalog.xml",false)

source

Open XML and display data in div

basically what I want is for javascript and xml in the same folder and use javascript to return values.

The actual program I am working on:

var xmlSolver = function MakeXmlSolver(){};
xmlSolver.GetAllAuthorsInStock()=function()
{
var author=xmlDoc.getElementsByTagName   
    ("author").childNodes.nodeValue;

return author;
 };

   xmlSolver.GetAllBooksInStock()=function()
   {
var title=xmlDoc.getElementsByTagName
     ("title").childNodes.nodeValue;
     }

and the xml

<?xml version='1.0'?>
<!-- This file represents a fragment of a book store inventory database -->
<bookCollection>
  <book genre="philosophy" publicationdate="1991" ISBN="1-861001-57-6">
    <title>The Gorgias</title>
    <author>
      <name>Plato</name>
    </author>
    <price>9.99</price>
  </book>
  <book genre="autobiography" publicationdate="1981" ISBN="1-861003-11-0">
    <title>The Autobiography of Benjamin Franklin</title>
    <author>
      <firstName>Benjamin</firstName>
      <lastName>Franklin</lastName>
    </author>
    <price>8.99</price>
  </book>
  <book genre="novel" publicationdate="1967" ISBN="0-201-63361-2">
    <title>The Confidence Man</title>
    <author>
      <firstName>Herman</firstName>
      <lastName>Melville</lastName>
    </author>
    <price>11.99</price>
  </book>
  <book genre="novel" publicationdate="2002" ISBN="0-201-63361-2">
    <title>Oryx and Crake</title>
    <author>
      <firstName>Margaret</firstName>
      <lastName>Atwood</lastName>
    </author>
    <price>11.99</price>
  </book>
  <book genre="philosophy" publicationdate="1991" ISBN="1-861001-57-6">
    <title>The Republic</title>
    <author>
      <name>Plato</name>
    </author>
    <price>7.99</price>
  </book>
</bookCollection>

SimplerXMLGenerator has no attribute '_write'


When I use Pelican to create a static webpage.

CRITICAL: SimplerXMLGenerator instance has no attribute '_write'

someone says this function has been removed from django: http://ift.tt/1JG9Trx

really? And how to fix this?

Thanks!


Adding New Field In order line Odoo 8


There is a problem in Odoo 8 while trying to add a new field in sale order line, the form simply doesn't save, I don't if anything's wrong with my code. I am attaching my code here:

The sale_view.xml:

<?xml version="1.0" encoding="utf-8"?>
<openerp>
    <data>



    <record id="view_order_line_tree_inherited" model="ir.ui.view">
        <field name="name">sale.order.line.tree.inherited</field>
        <field name="model">sale.order.line</field>
        <field name="inherit_id" ref="sale.view_order_line_tree"/>
        <field name="arch" type="xml">
            <xpath expr="//field[@name='name']" position="after">
                <field name='no_end_product'/>
                <field name='length'/>
                <field name='width'/>
            </xpath>
        </field>
    </record>

</data>

The sale.py:

import logging
from openerp.osv import fields, osv
from openerp import tools
from openerp.tools.translate import _



class sale_order_line(osv.osv):

    _inherit='sale.order.line'
    _columns= {
        'length': fields.float("Length"),
        'width': fields.float("Width"),
        'no_end_product': fields.integer("End Product No."),
    }

sale_order_line()

However the same code works fine in Openerp 7, I wonder what's creating a problem in Odoo 8.Any quick fix would be greatly appreciated.

Thanks And Regards, Yaseen Shareef


Magento Dependency Custom Form


I am new to magento and am working in making some updates to a module. As far as I've seen all form configuration for admin is done through system.xml, I need to add some sort of dependency as I want my form to check for some api credentials if they are correct show some other inputs. I've tried with depends tag but am not being able to call a function from there.

So I have two questions: How do I manage to make dependency when it depends on a value I do not know unless i consult for example an api, can I do something like:

<usertoken translate="label">
    <label>User Token</label>
    <frontend_type>text</frontend_type>
    <sort_order>1</sort_order>
    <show_in_default>1</show_in_default>
    <show_in_website>1</show_in_website>
    <show_in_store>1</show_in_store>
</usertoken>
<new_value translate="label">
    <label>New Value</label>
    <frontend_type>text</frontend_type>
    <sort_order>1</sort_order>
    <show_in_default>1</show_in_default>
    <show_in_website>1</show_in_website>
    <show_in_store>1</show_in_store>
    <depends><usertoken><action>mymodule/system_config_source_token/retorno</action></usertoken></depends>
</new_value>

If so, what should I use instead of action.

My seccond question is, is there any other way to construct a form in admin panel than using system.xml, I would like to create my own custom forms, using ajax, tables with checkboxes.... but would like to understand how can I integrate that.


How to Updating XML File (C#/Linq) in Windows Form


4 down vote favorite 1

Hello Friend I'm trying to figure out how I can go about updating my XML file. I know how to read and write, but no idea how to update an existing record.

My XML file looks like:

<?xml version="1.0" standalone="yes"?>
      <Categories>
       <Category>
        <CategoryId>1</CategoryId>
        <CategoryName>Ayourvedic</CategoryName>
       </Category>
      <Category>
      <CategoryId>2</CategoryId>
      <CategoryName>Daily Needs</CategoryName>
     </Category>
     <Category>
      <CategoryId>3</CategoryId>
      <CategoryName>Clothes</CategoryName>
     </Category>
     <Category>
      <CategoryId>4</CategoryId>
      <CategoryName>Shops</CategoryName>
     </Category>
     <Category>
     <CategoryId>5</CategoryId>
     <CategoryName>daily use product</CategoryName>
     </Category>
   </Categories>

and This is how I'm writing the file:

   private void btnUpdate_Click(object sender, EventArgs e)
    {
        XmlDocument xdoc = new XmlDocument();
        string PATH = "xmldata.xml";
        XElement xElement;
        xElement = new XElement("Category");

        XElement element = new XElement(
            "Category",
            new XAttribute("CategoryId", CategoryId),
            new XAttribute("CategoryName", CategoryName)

            );
        xElement.Add(element);
        xElement.Save("PATH");
    }

but my code is not working please any one can give some idea or solution.

thanks


ValueError with xmltodict unparse() function - Python 3


I'm having trouble using xmltodict to convert json to xml. It works fine with a single root and a single object, however when I try to convert multiple objects it returns a ValueError "ValueError: document with multiple roots".

Here's my JSON data:

Here's my script thus far:

import json
import xmltodict

    y = """{  

"markers":[
{
"point":"new GLatLng(40.266044,-74.718479)", "awayTeam":"LUGip", "markerImage":"images/red.png", "fixture":"Wednesday 7pm", "information":"Linux users group meets second Wednesday of each month.", "previousScore":"", "capacity":"", "homeTeam":"Lawrence Library" }, {
"point":"new GLatLng(40.211600,-74.695702)", "awayTeam":"LUGip HW SIG", "tv":"", "markerImage":"images/white.png", "fixture":"Tuesday 7pm", "information":"Linux users can meet the first Tuesday of the month to work out harward and configuration issues.", "capacity":"", "homeTeam":"Hamilton Library" }, {
"point":"new GLatLng(40.294535,-74.682012)", "awayTeam":"After LUPip Mtg Spot", "tv":"", "markerImage":"images/newcastle.png", "fixture":"Wednesday whenever", "information":"Some of us go there after the main LUGip meeting, drink brews, and talk.", "capacity":"2 to 4 pints", "homeTeam":"Applebees" } ] }"""

y2 = json.loads(y)
print(xmltodict.unparse(y2, pretty = True))

Result:

Traceback (most recent call last):

  File "<ipython-input-89-8838ce8b0d7f>", line 1, in <module>
    print(xmltodict.unparse(y2,pretty=True))

  File "/Users/luzazul/anaconda/lib/python3.4/site-packages/xmltodict.py", line 323, in unparse
    raise ValueError('Document must have exactly one root.')

ValueError: Document must have exactly one root.

Any help would be greatly appreciated, thanks!


Airpush Ads Not Avaiable When ap:test_mode="false"


I try to use Airpush sdk1 for ads and I did some tests with sdk.

<com.bplxjxdpse.achmyqxdlf225456.AdView
        xmlns:ap="http://ift.tt/GEGVYd"
        android:id="@+id/myAdView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        ap:animation="fade"
        ap:banner_type="inappad"
        ap:placementType="interstitial"
        ap:test_mode="false"  <------------- PROBLEM IS HERE
        ap:canShowMR="false"
        />

If I change test mode to true everything is fine. But when I try to use real mode there is no ads on screen and logcat like below

04-26 04:50:51.673: I/BunSDK(28665): Status code: 200
04-26 04:50:51.678: I/BunMraid(28665): Ad json:{"status":204,"message":"ADS Not Available"}
04-26 04:50:51.678: I/BunMraid(28665): No banner type present in response.
04-26 04:51:35.143: I/System.out(28665): CONNECTED VIA WIFI

what is the problem here? where is my ads? :)

I think this is not related with my codes.


replace / substitute a tag value from one xml file to another xml using php


Need to replace / substitute a tag value from one xml file to another xml

Please note: that my xml is not structured. But the tag for which i am search for is unique.

I need to replace the tag value to another xml file using php


Looking for a decent tutorial on using libxml with PHP


I have searched and searched and searched --- if I am to parse XML with PHP, libxml is what I have to use (for better or for worse) because that is what the hosting service has installed - whether I like it or not.

Problem is --- my search for a tutorial turns up nothing that I can make any sense of. There's several copies around of the "manual" for libxml -- but they all seem to be a vague description of the functions that may help for someone who already understands LibXML --- but is not at all comprehensible to a LibXML novice.

Then there is this document http://ift.tt/1IY8yfP that actually gives an example --- but it is way too obfuscated for me, an XML beginner, to make any sense of it.

I know there exist a few better-documented XML parsers for PHP --- but I probably don't have the authority to re-compile my hosting-service's Apache module - so I'm stuck with what they offer.

The question is --- does anyone know of any documents online that can come to my rescue?

Much thanks in advance.



I am trying to run my app with my phone(Galaxy Nexus) but it constantly shows an error: Unfortunately, <app name> has stopped.

Here's my styles.xml file:

<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="android:Theme.Holo.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <itemname="android:actionBarStyle">@style/MyActionBar</item>
    </style>


    <style name="MyActionBar" parent="@android:style/Widget.Holo.Light.ActionBar">
        <item name="android:background">#872657</item>
        <item name="android:titleTextStyle">@style/AppTheme.ActionBar.TitleTextStyle</item>
        <item name="android:colorBackground">#872657</item>

    </style>

    <style name="AppTheme.ActionBar.TitleTextStyle" parent="@android:style/TextAppearance.StatusBar.Title">
        <item name="android:textColor">#dfe3ee</item>
        <item name="android:background">#872657</item>

    </style>



    <style name="MyTheme.ActionBar.TitleTextStyle" parent="@android:style/TextAppearance.Holo.Widget.ActionBar.Title">
        <item name="android:textColor">#dfe3ee</item></style>

</resources>

Here's my activity_main.xml:

<RelativeLayout xmlns:android="http://ift.tt/nIICcg"
    xmlns:tools="http://ift.tt/LrGmb4" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"
    android:background="#872657">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/SplashImageView"
        android:layout_gravity="center"
        >
    </ImageView>

    <TextView  android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/textView" />

    <Button
        android:id="@+id/dialer_button"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Next"
        android:background="#dfe3ee"
        android:onClick="onGetNameClick"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Enter Your Name"
        android:id="@+id/textView2"
        android:layout_alignParentTop="true"
        android:layout_toRightOf="@+id/textView"
        android:layout_alignRight="@+id/dialer_button"
        android:layout_alignEnd="@+id/dialer_button"
        android:textColor="#fefbf7"
        android:typeface="normal" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Enter Your Phone Number"
        android:id="@+id/textView3"
        android:layout_below="@+id/textView2"
        android:layout_toRightOf="@+id/textView"
        android:layout_marginTop="40dp"
        android:layout_alignRight="@+id/textView2"
        android:layout_alignEnd="@+id/textView2"
        android:textColor="#fefbf7"
        />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Enter E-Mail ID"
        android:id="@+id/textView4"
        android:layout_marginTop="47dp"
        android:layout_below="@+id/textView3"
        android:layout_toRightOf="@+id/textView"
        android:layout_alignRight="@+id/textView3"
        android:layout_alignEnd="@+id/textView3"
        android:textColor="#fefbf7"
        />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Enter Emergency Contact Number"
        android:id="@+id/textView5"
        android:layout_below="@+id/editText3"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignRight="@+id/editText3"
        android:layout_alignEnd="@+id/editText3"
        android:textColor="#fefbf7"/>

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="textPersonName"
        android:ems="10"
        android:id="@+id/editText"
        android:layout_toRightOf="@+id/textView"
        android:layout_alignRight="@+id/textView2"
        android:layout_alignEnd="@+id/textView2"
        android:layout_below="@+id/textView2" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="textEmailAddress"
        android:ems="10"
        android:id="@+id/editText3"
        android:layout_below="@+id/textView4"
        android:layout_toRightOf="@+id/textView"
        android:layout_alignRight="@+id/textView4"
        android:layout_alignEnd="@+id/textView4" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="phone"
        android:ems="10"
        android:id="@+id/editText2"
        android:layout_below="@+id/textView3"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignRight="@+id/textView3"
        android:layout_alignEnd="@+id/textView3" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="phone"
        android:ems="10"
        android:id="@+id/editText4"
        android:layout_below="@+id/textView5"
        android:layout_toRightOf="@+id/textView"
        android:layout_alignRight="@+id/textView5"
        android:layout_alignEnd="@+id/textView5" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="App Coded by ©Ananay Batra"
        android:id="@+id/textView6"
        android:layout_below="@+id/editText4"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="59dp"
        android:textColor="#fefbf7"/>

    <TextView android:id="@android:id/text1"
        style="?android:textAppearanceLarge"
        android:textStyle="bold"
        android:textColor="#fff"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"></TextView></RelativeLayout>

Here's my MainActivity.java:

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

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    } }

Here's my Second_layout1.xml file:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://ift.tt/nIICcg"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="left"
    android:padding="20dp"
    android:weightSum="1"
    android:background="#872657">

    <RadioButton
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Follow Me"
        android:id="@+id/radioButton"
        android:layout_weight="0.09"
        android:textSize="20dp"
        android:layout_toRightOf="@+id/linearLayout"
        android:layout_toEndOf="@+id/linearLayout"
        android:layout_below="@+id/linearLayout"
        android:textColor="#fefbf7"/>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:id="@+id/linearLayout">

    </LinearLayout>

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Post Location on Facebook"
        android:id="@+id/button2"
        android:layout_weight="0.09"
        android:background="#dfe3ee"
        android:padding="20dp"
        android:layout_below="@+id/radioButton"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginTop="47dp" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Send Message to Emergency Contact"
        android:id="@+id/button"
        android:background="#dfe3ee"
        android:layout_below="@+id/button2"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginTop="38dp"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" /></RelativeLayout>

I would really like someone to reply!!
And also please explain what I did wrong in my code

logcat:

4758-4758/com.example.ananaybatra.rape_freeindia D/AndroidRuntime﹕ Shutting down VM
04-24 01:39:13.014    4758-4758/com.example.ananaybatra.rape_freeindia W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x415ffba8)
04-24 01:39:13.030    4758-4758/com.example.ananaybatra.rape_freeindia E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.ananaybatra.rape_freeindia, PID: 4758
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.ananaybatra.rape_freeindia/com.example.ananaybatra.rape_freeindia.MainActivity}: java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2221)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2280)
        at android.app.ActivityThread.access$800(ActivityThread.java:141)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1202)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:136)
        at android.app.ActivityThread.main(ActivityThread.java:5059)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
        at dalvik.system.NativeStart.main(Native Method)
 Caused by: java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.
        at android.support.v7.app.ActionBarActivityDelegate.onCreate(ActionBarActivityDelegate.java:152)
        at android.support.v7.app.ActionBarActivityDelegateBase.onCreate(ActionBarActivityDelegateBase.java:149)
        at android.support.v7.app.ActionBarActivity.onCreate(ActionBarActivity.java:123)
        at com.example.ananaybatra.rape_freeindia.MainActivity.onCreate(MainActivity.java:15)
        at android.app.Activity.performCreate(Activity.java:5312)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2178)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2280)
        at android.app.ActivityThread.access$800(ActivityThread.java:141)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1202)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:136)
        at android.app.ActivityThread.main(ActivityThread.java:5059)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)


Scrapy creating XML feed wraps content in "value" tags


I've had a bit of help on here by my code pretty much works. The only issue is that in the process of generating an XML, it wraps the content in "value" tags when I don't want it to. According to the doc's this is due to this:

Unless overriden in the :meth:serialize_field method, multi-valued fields are exported by serializing each value inside a <value> element. This is for convenience, as multi-valued fields are very common.

This is my output:

<?xml version="1.0" encoding="UTF-8"?>
<items>
   <item>
      <body>
         <value>Don't forget me this weekend!</value>
      </body>
      <to>
         <value>Tove</value>
      </to>
      <who>
         <value>Jani</value>
      </who>
      <heading>
         <value>Reminder</value>
      </heading>
   </item>
</items>

What I send it to the XML exporter seems to be this, so I don't know why it think's it's multivalue?

{'body': [u"Don't forget me this weekend!"],
 'heading': [u'Reminder'],
 'to': [u'Tove'],
 'who': [u'Jani']}

pipeline.py

from scrapy import signals
from scrapy.contrib.exporter import XmlItemExporter

class XmlExportPipeline(object):

    def __init__(self):
        self.files = {}

    @classmethod
    def from_crawler(cls, crawler):
         pipeline = cls()
         crawler.signals.connect(pipeline.spider_opened, signals.spider_opened)
         crawler.signals.connect(pipeline.spider_closed, signals.spider_closed)
         return pipeline

    def spider_opened(self, spider):
        file = open('%s_products.xml' % spider.name, 'w+b')
        self.files[spider] = file
        self.exporter = XmlItemExporter(file)
        self.exporter.start_exporting()

    def spider_closed(self, spider):
        self.exporter.finish_exporting()
        file = self.files.pop(spider)
        file.close()

    def process_item(self, item, spider):
        self.exporter.export_item(item)
        return item

spider.py

from scrapy.contrib.spiders import XMLFeedSpider
from crawler.items import CrawlerItem

class SiteSpider(XMLFeedSpider):
    name = 'site'
    allowed_domains = ['www.w3schools.com']
    start_urls = ['http://ift.tt/1j1cMKy']
    itertag = 'note'

    def parse_node(self, response, selector):
        item = CrawlerItem()
        item['to'] = selector.xpath('//to/text()').extract()
        item['who'] = selector.xpath('//from/text()').extract()
        item['heading'] = selector.xpath('//heading/text()').extract()
        item['body'] = selector.xpath('//body/text()').extract()
        return item

Any help would be really appreciated. I just want the same output without the redundant tags.


Android's datepicker date shown


it's maybe very dumb and obvious question but i can't find any method or solution to set exact date shown on datepicker's spinners.

My problem is that i want to set date throught those spinners and then when user wants to edit that date, it would be great to start spinners from that day, not from maximum possible, how it's by default.

Thank you for your answers!


Extract Xml Element from a larger string


I have a string that starts with an xml element then proceeds with regular text after the Element has ended.

Like so:

<SomeElement SomeAtt="SomeValue><SomeChild/></SomeElement> More random text.

I want to parse the first part into an XElement and then separate out the following text into a string variable. I have considered just counting anglebrackets, but there is legal XML that would throw me off. I would prefer to use the out-of-the-box parsers. I have tried using XmlReader and XElement.Parse method. I would like them to stop after the element is read instead of throwing exceptions because of the unexpected text after the Xml element. I haven't been able to thus far. XmlReader has a ReadSubtree method, but I couldn't get it to work.

Any ideas?


how to make a difference on Imagebutton click


I design my button in round shape by using this below code and then i want to show some text on button so i used Frame Layout and then i put some text on my button. Now the Challange is that my button is still.it doesnot show any effect on click where the drawable and src both are used one for roundshape button and other for image on button (respectivitly).

Now my button doesnot make any effect on design on click how i make that effect.

<FrameLayout>
<ImageButton
android:id="@+id/btn_profile_view"
android:layout_width="70dp"
android:layout_height="67dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginTop="20dp"
android:layout_weight="1"
android:onClick="compareButtonClick"
android:background="@drawable/roundedbutton"
android:src="@drawable/ic_action_person" />
<TextView
android:layout_width="45dp"
android:layout_height="20dp"
android:layout_gravity="bottom"
android:layout_marginLeft="38dp"
android:clickable="false"
android:text="@string/profile"
android:textColor="@color/btn_txt" >
</TextView>
</FrameLayout>


<shape xmlns:android="http://ift.tt/nIICcg"
android:shape="rectangle" >

<solid android:color="#D3D3D3" />

<corners
    android:bottomLeftRadius="8dip"
    android:bottomRightRadius="8dip"
    android:topLeftRadius="8dip"
    android:topRightRadius="8dip" />


PHP and HTML behind AJAX poll does not work


I'll start by saying that I'm 16 and I don't have a huge amount of experience with PHP, XML, HTML and JavaScript. Having said this, I love learning! I'm very enthusiastic about programming and coding and that's why I'm here. Although this website is simple and in some ways "stupid" but this is my first website and project and I'd like to be able to complete it.

I have a small, simple site running on a Raspberry Pi 2 in my room. On the site, users vote yes or no. It's that simple. You can check it out at: http://ift.tt/1HEmsF2. My problem is, something isn't working.

The browser is not showing the correct values for the variables taken from the text file. When the yes or no button is pressed, PHP should add 1 to either the $yes variable or the $no variable depending on which button was clicked, obviously. This will be clearer when you see the code below. Sometimes however, the variable is not echoed correctly in the table at the bottom of the page. The variable in the text file is updated each time the button is pressed. This leads me to believe that it's to do with the echoing or the writing and reading speed. On refreshing the page, the table usually updates.

The code below is my HTML page. I think this is correct. Apologies if this shows my lack of experience; I'm open to all suggestions!

    <!DOCTYPE HTML>
<!--start of html. sets background image-->
<html style="background-image: url(confectionary.png); color:black; padding:20px;">
<head>
    <title>ischrisgay.co.uk | Vote</title>
        <!--sets up js funtion for buttons to call and start running it-->
        <script type="text/javascript" src="vote.js"></script>
            <!--calls css to position yes and no buttons-->
            <link rel="stylesheet" href="navbar.css">
</head>
<body>
<!--first header-->
<h1 align="center"><font size="7">Is Chris Gay?</h1>
    <!--div with class="menu" allow css above to center the yes and no buttons-->
    <div class="menu">
        <ul>
        <li name="vote" value="0" onclick="getVote(0)"><font size="6"><a href="yes.php">Yes</a></li>
        <li name="vote" value="1" onclick="getVote(1)"><font size="6"><a href="no.php">No</a></li>
        </ul>
    </div>

<!--image of chris-->
<div style="text-align: center;"><img style="width: 800px; height: 600px;" alt="" src="Chris.jpg"></div>

</body>
</html>

Below is the "vote.js" file.

function getVote(int) {
  if (window.XMLHttpRequest) {
    // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
  } else {  // code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.onreadystatechange=function() {
    if (xmlhttp.readyState==4 && xmlhttp.status==200) {
      document.getElementById("poll").innerHTML=xmlhttp.responseText;
    }
  }
  xmlhttp.open("GET","poll_vote.php?vote="+int,true);
  xmlhttp.send();
}

Below is the "poll_vote.php" file.

<?php
$vote = $_REQUEST['vote'];

//get content of textfile
$filename = "poll_result.txt";
$content = file($filename);

//put content in array
$array = explode("||", $content[0]);
$yes = $array[0];
$no = $array[1];

if ($vote == 0) {
  $yes = $yes + 1;
}
if ($vote == 1) {
  $no = $no + 1;
}

//insert votes to txt file
$insertvote = $yes."||".$no;
$fp = fopen($filename,"w");
fputs($fp,$insertvote);
fclose($fp);
?>

Below is the code for the "yes.php" page. This is almost identical no the "no.php" page apart from some text.

    <!DOCTYPE HTML>
<!--start of html. sets background image-->
<html style="background-image: url(confectionary.png); color:black; padding:20px;">
<head>
    <title>Thank You For Voting</title>
        <!--calls css to position yes and no buttons-->
        <link rel="stylesheet" href="navbar.css">
</head>
<body>
<!--first header-->
<h1 align="center"><font size="6">Thank You For Voting</h1>
    <div class="menu">
        <ul>
        <li><font size="6"><a href="index.html">Home</a></li>
        </ul>
    </div>
<hr>
<p align="center"><font size="5">You have voted that Chris is gay.</p>

<!--first part of php which declares variables for the table to use-->
<?php
$filename = "poll_result.txt";
$content = file($filename);
$array = explode("||", $content[0]);
$yes = $array[0];
$no = $array[1];
$total = $yes + $no;
?>

<!--table of results and graph-->
<h4>Result:</h4>
<table>
<tr>
<td>Yes:</td>
<td>
<img src="poll.gif"
width='<?php echo(100*round($yes/($no+$yes),2)); ?>'
height='20'>
<?php echo(100*round($yes/($no+$yes),2)); ?>%
</td>
</tr>
<tr>
<td>No:</td>
<td>
<img src="poll.gif"
width='<?php echo(100*round($no/($no+$yes),2)); ?>'
height='20'>
<?php echo(100*round($no/($no+$yes),2)); ?>%
</td>
</tr>
<tr>
<td>Total number of votes:</td>
<td><?php echo $total; ?></td>
</tr>
</table>

</body>
</html>

This is all the code behind the site apart form some CSS which I believe is irrelevant here.

My questions are:

1) Why does the $total variable not get shown properly in the table?

2) Are there any HTML improvements I can make?

3) How would I go about making one result page that loads different text based on which button was pressed?

To anyone who answers and contributes, thank you so much in advance! If anymore code, information or clarification is needed, I will happily comment.

Thank you!


Dynamically setting bar graph values from a XML source


I got some great help parsing some RSS into a menu yesterday using jQuery Parse RSS feed with JS, and inspired by this I would like to use something similar to control some chart bars on a website.

Some background:

We are aiming to use a floating score in our upcoming tech reviews on a webpage, meaning that you assign a product an absolute score (lets say 67) and then the maximum score would be able to move as new and better products hit the market. This way you would still be able to read a review from last year and use the score for something meaningful, as the score of 67 is now measured against this years max-score. Hope it makes sense.

Anyhow, our CMS only permits javascript to be embedded in news entries, so I can't store our review scores in SQL or use php, and I was thinking of using XML instead (not optimal, but it should work). Each review would then contain a certain number of results including the beforementioned final score (and some intermediate sub-scores as well). I need to be able to insert a piece of JS code that extracts the scores for a specific review from the XML file and inserts the HTML code needed to draw the bars.

I have a JSfiddle set up, that contains the XML, it has the chart (hardcoded though), and using the jQuery code from my previous question I can sort of extract the results, but the code loops through all the XML and I don't really have a clue how to pick out the specific review number I need nor how to get things measured against the max-score, so it just prints everything right now and calculates a score based on a max-score of 100. I haven't tied the values to my chart yet, so the test version just prints the results in a ul/li.

Link to JSFiddle

So basically I need some sort of code that I can invoke from my HTML that goes along the lines of

ShowScores(testno)

that would write everything inside the first

<div class="row">..</row> 

containing the bars, where the %-width of the bars would be calculated as the score assigned divided by the maxscore:

  • Each item has 3 assigned scores: scorePicture, scoreFeature, scoreUI, and 1 calculated total score (weighted average)
  • A global max score exists for each of the 3 scores: topscorePicture, topscoreFeature, topscoreUI

As I suck at JS, I have spent 5 hours getting to this point, and I have no clue how to make things load from e.g. a testscore.xml file instead and then extract what I need with jQuery - and I probably also need some help making my HTML load the script i.e. how to invoke it afterwards. The documentation on jQuery is concerned with loading all content in the XML and not just a specific node?

All help is appreciated.

My own thoughts on some pseudo code would be a script that, when envoked from my HTML document would do something like

function(reviewNo)
var max1 = load maxscore1 from XML
var max2 = load maxscore2 from XML
var max3 = load maxscore3 from XML

var score1 = load assignedscore1 for reviewNo from XML
var score2 = load assignedscore2 for reviewNo from XML
var score3 = load assignedscore2 for reviewNo from XML

Calculate % width of bar 1, bar 2 and bar 3 and save as variables as math.round()
write HTML DIV code and subsitute the width of the bars with the calculated values from above


How do i write Infinite Row-repeater in an Xml View in SAPUI5


I am trying to display the complex json data in SAPUI5.

Here is my Complex Data:

results:{
         "name" : "sample",
         "child" : [
                    "name" : "sample",
                    "child" : [
                        "name" : "sample",
                        "child" : [
                                    "name" : "sample",
                                    "child" : [

                                     ]
                                  ]
                     ]
                 ]
        }

Here the inner child is infinite. These are depending on my data.

So here is my question is how do i display this type of data in xml view.

Previously i displayed this type of data by using the Row repeater. There the data has only 3 levels. But Now it has infinite. So how can i use row repeater for displaying this type of data.

Here is a my 3-level Row Repeater.

<c:RowRepeater rows="{path: bindingpath}" id="rowRepeater" >
      <c:RowRepeater rows="{path: bindingpath/somePath}" >
            <c:RowRepeater rows="{path: bindingpath/somePath/anotherpath}">

            </c:RowRepeater>
      </c:RowRepeater>
</c:RowRepeater>


How to fetch the list of users from ParseUser table and show the it in list view in andorid


I am trying to get the list of first names of all the users from ParseUser table but its crashing with the error: doing much work on main thread. It works when I try fetch from other ParseObjects but it doesn't work with ParseUser table. The following is my code

MainActivity.java

public class MainActivity extends ActionBarActivity {
    // Declare Variables
      ListView listview;
      List<ParseUser> ob;
      ProgressDialog mProgressDialog;
      ArrayAdapter<String> adapter;
       @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Parse.initialize(this, "6qUFzAHfl9bXRzzDlBegiXZx0Tw5dc29m3jXmnHt","TS6OswWh6HwKQm2uCJxqfprlyrP2mfpkmwkx3Vg9");
       new RemoteDataTask().execute();
    }

        // RemoteDataTask AsyncTask
private class RemoteDataTask extends AsyncTask<Void, Void, Void> {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Create a progressdialog
        mProgressDialog = new ProgressDialog(MainActivity.this);
        // Set progressdialog title
        mProgressDialog.setTitle("loading all donors");
        // Set progressdialog message
        mProgressDialog.setMessage("Loading...");
        mProgressDialog.setIndeterminate(false);
        // Show progressdialog
        mProgressDialog.show();
    }

    // RemoteDataTask AsyncTask
    @Override
    protected Void doInBackground(Void... params) {

        // Locate the class table named "Country" in Parse.com
        ParseQuery<ParseUser> query = ParseUser.getQuery();

        try {
            ob = query.find();

        } catch (com.parse.ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        listview = (ListView) findViewById(R.id.listview);
        // Pass the results into an ArrayAdapter
        adapter = new ArrayAdapter<String>(MainActivity.this,
                R.layout.listview_item);
        // Retrieve object "name" from Parse.com database
        for (ParseObject User : ob) {
            adapter.add((String) User.get("firstName"));
        }
        // Binds the Adapter to the ListView
        listview.setAdapter(adapter);

        // Close the progressdialog
        mProgressDialog.dismiss();
        // Capture button clicks on ListView items

         }
      }
 }

activity_main.xml

    <LinearLayout xmlns:android="http://ift.tt/nIICcg"
     xmlns:tools="http://ift.tt/LrGmb4"
     android:layout_width="fill_parent"
     android:layout_height="match_parent"
     android:orientation="vertical"
     android:background="#de99ac"
     tools:context="com.nyu.blife_app.MainActivity">
   <ListView
    android:id="@+id/listview"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" />

   </LinearLayout>

listview_item.xml

  <?xml version="1.0" encoding="utf-8"?>
 <TextView xmlns:android="http://ift.tt/nIICcg"
  android:id="@+id/text"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
    android:padding="5sp"
   android:textSize="25sp" >
 </TextView>

I have added additional fields in ParseUser table (firstName, lastName) and some more.. I just need to get all the firstNames from ParseUser Table. it would be really helpful if someone guide me on this.


Android: switching from one layout activity to another


I am trying to display a splash screen for 3 seconds and then go to the main screen, both of them being in the same class. However, my problem is that, when I try calling the new layout.activity, before the original layout.acitity for the class Im in, the program crash. Why?

Here is a little example of what I am talkin about:

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_splash);//new activity 
    displaySplash();

    setContentView(R.layout.activity_visualizer);//original activity 

The only way that I can get this to run is if I comment out the splash activity completely, but I need it! I wont work if I comment out the other layout activity...

Here are my two activities if it helps:

<LinearLayout xmlns:android="http://ift.tt/nIICcg"
xmlns:tools="http://ift.tt/LrGmb4"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:background="#000000"
tools:context="comp380.musicvisualizer.Visualizer" >

<ListView
    android:id="@+id/song_list"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" >
</ListView>

<LinearLayout xmlns:android="http://ift.tt/nIICcg"
xmlns:tools="http://ift.tt/LrGmb4"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#000000"
tools:context="comp380.musicvisualizer.Visualizer" >

<ImageView
    android:id="@+id/splashscreen"
    android:layout_width="wrap_content"
    android:layout_height="fill_parent"
    android:src="@drawable/logo"
    android:layout_gravity="center"/>


How to parse XML without validation using JDOM2


I am trying to parse XML using JDOM2. I want to skip both XSD and DTD validation. I tried code bellow:

SAXBuilder jdomBuilder = new SAXBuilder(XMLReaders.NOVALIDATING);
jdomBuilder.build(stream);

I tested by trying to parse XML that has DTD reference, and by disconnecting from network. It still tries to fetch DTD. I'm getting

java.net.UnknownHostException: dtd.nlm.nih.gov

Does anyone know how can I force JDOM2 to skip validation completely?

Thanks in advance!


Nothing Happen when i send data to bluetooth device from android


I am making an android app when sending data to bluetooth nothing happen. I made two threads one for bluetooth connection one for sending data every thing works fine but not recieving the data on the target mobile plz help. Thnkx in adv

private class ConnectThread extends Thread {
             private final BluetoothSocket mmSocket;
             private BluetoothAdapter mybluetoothAdapter;
             private final BluetoothDevice mmDevice;
             private final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");
             public ConnectThread(BluetoothDevice device) {
                 BluetoothSocket tmp = null;
                 mmDevice = device;
                 try {
                     tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
                 } catch (IOException e) { }
                 mmSocket = tmp;
             }


             public void run() {
                 //mybluetoothAdapter.cancelDiscovery();
                 try {
                     mmSocket.connect();
                 } catch (IOException connectException) {
                     try {
                         mmSocket.close();
                     } catch (IOException closeException) { }
                     return;
                 }
                 ConnectedThread connected=new ConnectedThread(mmSocket);
                 connected.start();
             }
             public void cancel() {
                 try {
                     mmSocket.close();
                 } catch (IOException e) { }
             }
         }

    private class ConnectedThread extends Thread {
        private final BluetoothSocket mmSocket;
        private final InputStream mmInStream;
        private final OutputStream mmOutStream;
        public ConnectedThread(BluetoothSocket socket) {
            mmSocket = socket;
            InputStream tmpIn = null;
            OutputStream tmpOut = null;
            try {
                tmpIn = socket.getInputStream();
                tmpOut = socket.getOutputStream();
            } catch (IOException e) { }
            mmInStream = tmpIn;
            mmOutStream = tmpOut;
        }
        public void run() {
            byte[] buffer = new byte[1024];
            int begin = 0;
            int bytes = 0;
            while (true) {
                try {
                    bytes += mmInStream.read(buffer, bytes, buffer.length - bytes);
                    for(int i = begin; i < bytes; i++) {
                        if(buffer[i] == "#".getBytes()[0]) {
                            mHandler.obtainMessage(1, begin, i, buffer).sendToTarget();
                            begin = i + 1;
                            if(i == bytes - 1) {
                                bytes = 0;
                                begin = 0;
                            }
                        }
                    }
                } catch (IOException e) {
                    break;
                }
            }
        }
        public void write(byte[] bytes) {
            try {
                mmOutStream.write(bytes);
            } catch (IOException e) { }
        }
        public void cancel() {
            try {
                mmSocket.close();
            } catch (IOException e) { }
        }
    }


Soap API XML issue using nusoap?


I have created SOAP API using nusoap in php.Everything is working fine. I have one file service.php when i hit this file i get documentation like this. My Screenshot

If i hit this url:

Other Screenshot

i get a diffrent type of xml document.I want to know why this is so diffrent.Please tell me.


how correct configuration gridview


I was write small application for android which use gridview. This grid show image from sdcard. Fill images to grid I use Adapter. My problem is that where I scroll grid adapter automaticly load from sdcard images, and my application in small time freezes. How I can reconfigured my gridview or adapter or maybe other component for my application work fast. Thank you.enter image description here

<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://ift.tt/nIICcg"
    android:id="@+id/gridview"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:horizontalSpacing="10dp"
    android:numColumns="2"
    android:layout_marginTop="8dp"
    android:layout_marginBottom="8dp"
    android:layout_marginLeft="3dp"
    android:layout_marginRight="3dp"
    android:stretchMode="columnWidth"
    android:verticalSpacing="10dp" />

UPDATE

public class ImageAdapterFormGIF extends BaseAdapter {

    public static String file_path = "";

    public String[] p = getFileFromFolder();

    Tools t = new Tools();
    private Context mContext;

    public ImageAdapterFormGIF(Context c) {
        mContext = c;
    }

    Tools tools = new Tools();

    public int getCount() {
        return p.length;
    }


    public Object getItem(int position) {
        return null;
    }

    public long getItemId(int position) {
        return 0;
    }

    // create a new ImageView for each item referenced by the Adapter

    public View getView(int position,  View convertView, ViewGroup parent) {
        ImageView imageView;

        if (convertView == null) {  // if it's not recycled, initialize some attributes
            imageView = new ImageView(mContext);
            imageView.setLayoutParams(new GridView.LayoutParams((tools.getWidth(mContext)-48)/2, (tools.getWidth(mContext)-48)/2));
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
          //  imageView.setPadding(8, 8, 8, 8);
        } else {
            imageView = (ImageView) convertView;
        }

        imageView.setImageURI(Uri.parse(new File(p[position]).toString()));
        imageView.setTag(p[position]);

        return imageView;
    }


    private String[] getFileFromFolder() {
        Tools tools = new Tools();
        tools.checkSdcardFolders();
        String path = "/sdcard/xx/gif/";
        File f = new File(path);
        File file[] = f.listFiles();
        String[] s = new String[file.length];
        for (int i = 0; i < file.length; i++) {
            s[i] = "/sdcard/xx/gif/" + file[i].getName();
        }
        return s;
    }

}


simplexml_load_file() does not getting node content


I cannot get XML node contents and attributes at the same time with SimpleXML library:

I have the following XML, and want to get content@name attribute and node's contents:

<page id="id1">
    <content name="abc">def</content>
</page>

Method simplexml_load_string()

print_r(simplexml_load_string('<page id="id1"><content name="abc">def</content></page>'));

outputs this:

SimpleXMLElement Object
(
   [@attributes] => Array
        (
            [id] => id1
        )

    [content] => def
)

As you can see, contents of the content node is present, but attributes are missing. How can I receive the contents and attributes?

Thanks!


JQuery children loop XML


Using JQuery and AJAX, I am getting an XML document and then looping through the document in an attempt to do something at each level of the XML tags/nodes, from parent to children and then children of children respectively.

What i have currently works but is specifically written to a limit of children of children of children (Not ideal).

The final application may have an open ended number of children to do the action to.

How can i make this account for any number of children without the inefficiency?

I have tried making a function with the basis of what i wish to achieve at each child level. But this does not work as expected, essentially breaking the script.

The function

function childX() {
    $(this).children().each(function()
    {
       $("#output").append("<div id='"+(this).nodeName+"'>"+(this).nodeName+"</div><br />");
    });
}

The main script

  $(xml).find("RecentTutorials").children().each(function()
  {

    $("#output").append("<div id='"+(this).nodeName+"'>"+(this).nodeName+"</div><br />");


    $(this).children().each(function()
    {
       $("#output").append("<div id='"+(this).nodeName+"'>"+(this).nodeName+"</div><br />");

      $(this).children().each(function()
        {
           $("#output").append("<div id='"+(this).nodeName+"'>"+(this).nodeName+"</div><br />");

            $(this).children().each(function()
            {
               $("#output").append("<div id='"+(this).nodeName+"'>"+(this).nodeName+"</div><br />");

            });

        });

    });


  //alert((this).nodeName);
  }); 


retrieving data from a XML and storing into mysql table


I have a XML like the following:

<?xml version="1.0" encoding="UTF-8"?>
<items>
        <item>
            <id>1000416</id>
            <price>9990</price>
            <stock>1</stock>
            <name><![CDATA[Benbo Mk3 Trekker Kit Trépied avec Tête B&S et sac]]></name>
            <attributes>
                <attribute datatype="text">
                    <name><![CDATA[name]]></name>
                    <value><![CDATA[Benbo Mk3 Trekker Kit Trépied avec Tête B&amp;S et sac]]></value>
                </attribute>
                <attribute datatype="text">
                    <name><![CDATA[sku]]></name>
                    <value><![CDATA[BEN107C]]></value>
                </attribute>
                <attribute datatype="numeric">
                    <name><![CDATA[price]]></name>
                    <value>9900</value>
                </attribute>
                <attribute datatype="text">
                    <name><![CDATA[manufacturer]]></name>
                    <value><![CDATA[Benbo]]></value>
                </attribute>
                <attribute datatype="text">
                    <name><![CDATA[url_key]]></name>
                    <value><![CDATA[benbo-mk3-trekker-kit-trepied-avec-tete-b-s-et-sac]]></value>
                </attribute>
                <attribute datatype="text">
                    <name><![CDATA[photo_video]]></name>
                    <value><![CDATA[Photo ]]></value>
                </attribute>
                <attribute datatype="text">
                    <name><![CDATA[includes_tripodhead]]></name>
                    <value><![CDATA[Oui]]></value>
                </attribute>
                <attribute datatype="text">
                    <name><![CDATA[material]]></name>
                    <value><![CDATA[Aluminium]]></value>
                </attribute>
                <attribute datatype="numeric">
                    <name><![CDATA[stock_lc_kroezenhoek]]></name>
                    <value>1</value>
                </attribute>
                <attribute datatype="numeric">
                    <name><![CDATA[stock_total]]></name>
                    <value>1</value>
                </attribute>
                <attribute datatype="numeric">
                    <name><![CDATA[eancode]]></name>
                    <value>123456789</value>
                </attribute>
            </attributes>
            <categories>
                <categoryid>100042</categoryid>
                <categoryid>10004332</categoryid>
            </categories>
        </item>
        <item>
            <id>1000418</id>
            <price>4896</price>
            <stock>0</stock>
            <name><![CDATA[Benbo Trekker Monopod]]></name>
            <attributes>
                <attribute datatype="text">
                    <name><![CDATA[name]]></name>
                    <value><![CDATA[Benbo Trekker Monopod]]></value>
                </attribute>
                <attribute datatype="text">
                    <name><![CDATA[sku]]></name>
                    <value><![CDATA[BEN109]]></value>
                </attribute>
                <attribute datatype="numeric">
                    <name><![CDATA[price]]></name>
                    <value>4896</value>
                </attribute>
                <attribute datatype="text">
                    <name><![CDATA[manufacturer]]></name>
                    <value><![CDATA[Benbo]]></value>
                </attribute>
                <attribute datatype="text">
                    <name><![CDATA[url_key]]></name>
                    <value><![CDATA[benbo-trekker-monopod]]></value>
                </attribute>
                <attribute datatype="numeric">
                    <name><![CDATA[stock_lc_kroezenhoek]]></name>
                    <value>1</value>
                </attribute>
                <attribute datatype="numeric">
                    <name><![CDATA[stock_total]]></name>
                    <value>1</value>
                </attribute>
                <attribute datatype="numeric">
                    <name><![CDATA[eancode]]></name>
                    <value>3987654321</value>
                </attribute>
                <attribute datatype="text">
                    <name><![CDATA[manufacturer_code]]></name>
                    <value><![CDATA[BEN109]]></value>
                </attribute>
            </attributes>
            <categories>
                <categoryid>100042</categoryid>
                <categoryid>10004329</categoryid>
            </categories>
        </item>
        </items>

Now from this XML I want to store the each attributes value in a mysql table...each value will be a column...to obtain this I have used the following code:

$values = array();
$reader = new XMLReader();
$reader->open( 'test.xml' );
$id = 'attribute';
while ($reader->read()) {
    if ($reader->nodeType == XMLReader::ELEMENT) {
        $exp = $reader->expand();
        if ($exp->nodeName == "item") {
          //  if (count($values)) print implode(" : ", $values);
            //$values = array();
        }
        if ($exp->nodeName == $id) {
            foreach ($exp->childNodes as $node) {
                if ($node->nodeName == "value") {
                    $values[] = $node->textContent;

                }
            //  $values[] = null;
            }

        }

    }

    }

if (count($values)) print implode(" : ", $values);                  

This enables me to display the values from the array separated by a : but I want to store each values of tags from the "attributes" node in a MySql table...can anyone please help me I am really struggling with this since am very new to XML programming...

Thanks in advance!


App stops working after some time( may be because of httppost() sending request to my server) [duplicate]


This question already has an answer here:

I know this question has been asked before on this site but i can't use that answer as i am running the app on mobile. As it is related to calling i have to test the app live on my phone.I am making an app that sends the incoming call number to my server and the app receives the output and shows it. But the app stops working after 2-3 seconds when i receives a call, it gives me a error that unfortunately app stopped working. call.java

package com.example.hudixt.trigger;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;

import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

public class call extends BroadcastReceiver {

    private Context mContext;
    private Intent mIntent;
    // Create a new HttpClient and Post Header
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://ift.tt/1z4RXH9");
    @Override
    public void onReceive(Context context, Intent intent) {
        mContext = context;
        mIntent = intent;
        TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        int events = PhoneStateListener.LISTEN_CALL_STATE;
        tm.listen(phoneStateListener, events);
    }

    private final PhoneStateListener phoneStateListener = new PhoneStateListener()  {
        @Override
        public void onCallStateChanged(int state, String incomingNumber) {
            String callState = "UNKNOWN";
            switch (state) {
                case TelephonyManager.CALL_STATE_IDLE:
                    callState = "IDLE";
                    break;
                case TelephonyManager.CALL_STATE_RINGING:
                    // -- check international call or not.

                    String MyName = incomingNumber; //any data to send
                    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
                    nameValuePairs.add(new BasicNameValuePair("action", MyName));

                    try {
                        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                    } catch (UnsupportedEncodingException e) {

                    }

// Execute HTTP Post Request

                    ResponseHandler<String> responseHandler = new BasicResponseHandler();
                    String response = null;
                    try {
                        response = httpclient.execute(httppost, responseHandler);
                        Toast.makeText(mContext,  response, Toast.LENGTH_LONG).show();
                    } catch (IOException e) {

                    }



                    break;


            }
            super.onCallStateChanged(state, incomingNumber);
        }

    };

}

Android Manifiest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://ift.tt/nIICcg"
    package="com.example.hudixt.trigger" >
    <uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
    <uses-permission android:name="android.permission.INTERNET" />
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <receiver android:name=".call"
            android:enabled="true">
            <intent-filter>
                <action android:name="android.intent.action.PHONE_STATE"></action>
                <action android:name="android.intent.action.NEW_OUTGOING_CALL" />
            </intent-filter>
        </receiver>
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Please help me as i am beginner to android. Thanks in advance


Java DOM xml write "\n\t"


how can i add "\n\t" between elements. I want look like this:

<data no="1">
    <realColor>255 254 253</realColor>
    <sensorFreq>1 2 3</sensorFreq>
</data>

but it is look like this:

<data no="1">
    <realColor>255 254 253</realColor>
<sensorFreq>1 2 3</sensorFreq>  // I cant add '\t'
</data>


How do I find non-xml characters in mysql data column


I have a database where a java program is erroring out because there are non-xml characters in the mysql database. I would like to know how to do a regex to find the records that have non-valid XML characters. I could not find a query to run anywhere on the web.


XML Schema - cannot find the declaration of element


XML File

<?xml version="1.0" encoding="UTF-8"?>
<rootItem xmlns="http://ift.tt/rAg5Mm"
    xmlns:xsi="http://ift.tt/ra1lAU"
    xsi:schemaLocation="schema.xsd">
    <product category="software" type="individual" currentlyOffered="Y">
        <tid>725</tid>
        <tname>MS Office</tname>
        <reviewDate>2017-12-05</reviewDate>
        <note staffID="ee21kfj">Need to specify Windows version</note>
        <note staffID="ef23mls">Is there a price update?</note>
    </product>

    <product category="software" type="individual" currentlyOffered="Y">
        <tid>663</tid>
        <tname>Windows</tname>
        <reviewDate>2015-08-06</reviewDate>
        <note staffID="ef28xmm">Do we need to ensure that people aren't trying to put it on a calculator?</note>
    </product>

    <product category="software" type="group" currentlyOffered="Y">
        <tid>412</tid>
        <tname>Football Manager</tname>
        <reviewDate>2016-09-16</reviewDate>
    </product>

    <product category="hardware" type="individual" currentlyOffered="TBC">
        <tid>511</tid>
        <tname>Mouse</tname>
        <reviewDate>2016-09-26</reviewDate>
        <note staffID="fh26eij">Need to ensure that this is suitable for minors</note>
        <note staffID="mm25por">Need to check price on this</note>
    </product>
</rootItem>

XML Schema

    <!-- definition of simple elements -->
    <xs:element name="tid" type="xs:positiveInteger"/>
    <xs:element name="tname" type="xs:string"/>
    <xs:element name="reviewDate" type="xs:date"/>
    <xs:element name="note" type="xs:string"/>

    <!-- definition of attributes -->
    <xs:attribute name="category" type="xs:string"/>
    <xs:attribute name="type" type="xs:string"/>
    <xs:attribute name="currentlyOffered" type="xs:string"/>
    <xs:attribute name="staffID">
        <xs:simpleType>
            <xs:restriction base="xs:string">
                <xs:length value="7"/>
                <xs:pattern value="[a-z][a-z][0-9][0-9][a-z][a-z][a-z]"/>
            </xs:restriction>
        </xs:simpleType>
    </xs:attribute>

    <!-- definition of complex elements -->
    <xs:element name="product">
        <xs:complexType>
            <xs:sequence>
                <xs:element ref="tid"/>
                <xs:element ref="tname"/>
                <xs:element ref="reviewDate"/>
                <xs:element ref="note" minOccurs="0" maxOccurs="unbounded" />
            </xs:sequence>
        </xs:complexType>
    </xs:element>

    <xs:element name="rootItem">
        <xs:complexType>
            <xs:sequence>
                <xs:element ref="product"/>
            </xs:sequence>
            <xs:attribute ref="category" use="required"/>
            <xs:attribute ref="type" use="required"/>
            <xs:attribute ref="currentlyOffered" use="required"/>
        </xs:complexType>
    </xs:element>

</xs:schema>

And the response I get is "Cannot find the declaration of element 'rootItem' (note that I've changed names of things for reasons of confidentiality).

Any ideas? XML schemas really aren't something I'm especially good at.


Android colour resource - making a colour an alias of another


Is there a way to do something like the following?

<color name="gray1">#eeeeee</color>
<color name="separator_line_gray">@color/gray1</color>

So that I can use separator_line_gray in my code and quickly change it from gray1 to gray2 if needed


IFRAME Outlook Calendar (Office365)


I'm building a script which jumps around to index.php?p=1 - 3 which loads the calendars in what I hoped would be an iframe however Ive just found out that they are blocked.

Is there any alternative?


Transform XML to HTML in XSLT with string length condition


I have a XML file using TEI build like that:

<div type="chapter" n="1">
        <p>
          <s xml:id="e_1">sentence e1.</s>
          <s xml:id="f_1">sentence f1</s>
        </p>
        <p>
            <s xml:id="e_2"> sentence e2</s>
            <s xml:id="f_2"> sentence f2</s>
        </p>
</div>

<div type="chapter" n="2">
        <!-- -->
</div>

I need to transform it to this HTML structure:

<div>
<h1>Chapter 1</h1>
<div class="book-content">
 <p>
    <span class='source-language-sent' data-source-id='1'>sentence e1.</span>
    <span id='1' style='display:none'>sentence f1</span>
 </p>
 <p>
    <span class='source-language-sent' data-source-id='2'>sentence e2</span>
    <span id='2' style='display:none'>sentence f2</span>
 </p>
</div>
</div>
<div>
<h1>Chapter 2</h1>
<div class="book-content">
  <!-- -->
</div>
</div>

for now I use this XSLT file:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://ift.tt/tCZ8VR" xmlns:tei="http://ift.tt/1dDT9n4" version="1.0">
   <xsl:output method="html" encoding="UTF-8" indent="yes" />

   <xsl:template match="tei:body">
      <xsl:apply-templates />
   </xsl:template>

   <xsl:template match="tei:teiHeader">
      <xsl:comment>
         <xsl:apply-templates select="node()" />
      </xsl:comment>
   </xsl:template>

   <!--create chapter-->
   <xsl:template match="tei:div">
      <xsl:element name="div">
         <xsl:element name="div">
            <xsl:attribute name="class">
               <xsl:text>book-content</xsl:text>
            </xsl:attribute>
            <xsl:element name="h1">
               <xsl:text>Chapter</xsl:text>
               <xsl:value-of select="@n" />
            </xsl:element>
            <xsl:apply-templates select="node()" />
         </xsl:element>
      </xsl:element>
   </xsl:template>

   <!-- create p-->
   <xsl:template match="tei:p">
      <xsl:element name="p">
         <xsl:apply-templates />
      </xsl:element>
   </xsl:template>

   <!-- create s-->
   <xsl:template match="tei:s">
      <xsl:variable name="xmlid" select="@xml:id" />
      <xsl:if test="starts-with($xmlid, 'e')">
         <xsl:element name="span">
            <xsl:attribute name="class">
               <xsl:text>source-language-sent</xsl:text>
            </xsl:attribute>
            <xsl:attribute name="data-source-id">
               <xsl:value-of select="substring($xmlid, 3, 4)" />
            </xsl:attribute>
            <xsl:apply-templates select="node()" />
         </xsl:element>
      </xsl:if>
      <xsl:if test="starts-with($xmlid, 'f')">
         <xsl:element name="span">
            <xsl:attribute name="style">
               <xsl:text>display:none</xsl:text>
            </xsl:attribute>
            <xsl:attribute name="id">
               <xsl:value-of select="substring($xmlid, 3, 4)" />
            </xsl:attribute>
            <xsl:apply-templates select="node()" />
         </xsl:element>
      </xsl:if>
   </xsl:template>

</xsl:stylesheet>

My problem is that I need to create a new <div class="book-chapter"> foreach 900 characters. But I don't want to cut my s elements so I need to calculate how many selement do I have to include in one <div class="book-chapter">to have somethings like 900 characters.


marklogic save xml document with node-client-api?


I can't seem to save xml document into the marklogic with it's node-client-api. I had used the following code to try to save a dummy xml document

var marklogic = require('marklogic');
var my = require('../db/env.js');
var db = marklogic.createDatabaseClient(my.connInfo);

console.log("Write a single dummy xml document");

db.documents.write(
{
        uri: '/collegiate/testxml.xml',
        contentType: 'application/xml',
        content: '<entry-list><entry id="horror"></entry></entry-list>'
})

Then I used the following code to retrieve it:

var marklogic = require('marklogic');
var my = require('../db/env.js');
var db = marklogic.createDatabaseClient(my.connInfo);

console.log("Read a single xml document");

db.documents.read('/collegiate/testxml.xml')
.result().then(function(document) {
    //console.log('\nURI: ' + document.uri);
    for (var key in document) {
        console.log("key: " + key + " value: " + document.key);
    }
}).catch(function(error) {
    console.log(error);
});

What I get from the output is:

Read a single xml document
key: 0 value: undefined

So how to save a xml document correctly?