text:
Q: Validating a Google atom feed I'm getting the following error whilst trying to validate an XML document based on the Google Atom feed.

Error - Line 8, 10: org.xml.sax.SAXParseException; lineNumber: 8;
  columnNumber: 10; cvc-complex-type.2.4.a: Invalid content was found
  starting with element 'g:brand'. One of '{"xxx..w3.org/2005/Atom":id,
  "xxx.w3.org/2005/Atom":title, ".w3.org/2005/Atom":link,
  "xxx.w3.org/2005/Atom":brand}' is expected.

Here is my XML:
    <?xml version="1.0" encoding="UTF-8"?>
    <feed xmlns="http://www.w3.org/2005/Atom" xmlns:g="http://base.google.com/ns/1.0">
        <title>The name of your data feed.</title>
        <link rel="self" href="http://www.example.com"/>
        <updated>2006-06-11T18:30:02Z</updated>
    <entry>
    <title>Red wool sweater</title>
    <g:brand>Acme</g:brand>
    <g:condition>new</g:condition>
    <summary>Comfortable and soft, this sweater will keep you warm on those cold winter nights.</summary>
    <id>1</id>
    <g:image_link>http://www.example.com/image1.jpg</g:image_link>
    <link href="http://www.example.com/item1-info-page.html"/>
    <g:mpn>ABC123</g:mpn>
    <g:price>25</g:price>
    <g:product_type>Clothing & Accessories > Clothing > Outerwear > Sweaters</g:product_type>
    <g:quantity>3</g:quantity>
    <g:shipping>
       <g:country>US</g:country>
       <g:region>MA</g:region>
       <g:service>Ground</g:service>
       <g:price>5.95</g:price>
    </g:shipping>
    <g:shipping>
       <g:country>US</g:country>
       <g:region>024*</g:region>
       <g:service>Ground</g:service>
       <g:price>7.95</g:price>
    </g:shipping>
    <g:tax>
       <g:country>US</g:country>
       <g:region>CA</g:region>
       <g:rate>8.25</g:rate>
       <g:tax_ship>y</g:tax_ship>
    </g:tax>
    <g:tax>
       <g:country>US</g:country>
       <g:region>926*</g:region>
       <g:rate>8.75</g:rate>
       <g:tax_ship>y</g:tax_ship>
    </g:tax>
    <g:upc>0001230001232</g:upc>
    <g:weight>0.1 lb</g:weight>
    </entry>
    </feed>

And here is my XSD:
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema targetNamespace="http://www.w3.org/2005/Atom"
           elementFormDefault="qualified"
           attributeFormDefault="unqualified"
           xmlns:atom="http://www.w3.org/2005/Atom"
           xmlns:g="http://base.google.com/ns/1.0"
           xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:import namespace="http://www.w3.org/XML/1998/namespace"
             schemaLocation="http://www.w3.org/2001/03/xml.xsd"/>
  <xs:element name="feed" type="atom:feedType"/>
  <xs:element name="entry" type="atom:entryType"/>
  <xs:element name="extended_attribute" type="atom:extendedAttributeType"/>
  <xs:complexType name="textType" mixed="true">
    <xs:sequence>
      <xs:any namespace="http://www.w3.org/1999/xhtml" minOccurs="0"/>
    </xs:sequence>
    <xs:attribute name="type">
      <xs:simpleType>
        <xs:restriction base="xs:token">
          <xs:enumeration value="text"/>
          <xs:enumeration value="html"/>
          <xs:enumeration value="xhtml"/>
        </xs:restriction>
      </xs:simpleType>
    </xs:attribute>
    <xs:attributeGroup ref="atom:commonAttributes"/>
  </xs:complexType>
  <xs:complexType name="idType">
    <xs:simpleContent>
      <xs:extension base="xs:anyURI">
        <xs:attributeGroup ref="atom:commonAttributes"/>
      </xs:extension>
    </xs:simpleContent>
  </xs:complexType>
  <xs:complexType name="feedType">
    <xs:choice minOccurs="3" maxOccurs="unbounded">
      <xs:element name="link" type="atom:linkType" minOccurs="0" maxOccurs="unbounded"/>
      <xs:element name="title" type="atom:textType" minOccurs="1" maxOccurs="1"/>
      <xs:element name="updated" type="atom:dateTimeType" minOccurs="1" maxOccurs="1"/>
      <xs:element name="entry" type="atom:entryType" minOccurs="0" maxOccurs="unbounded"/>
      <xs:any namespace="##other" minOccurs="0" maxOccurs="unbounded"/>
    </xs:choice>
    <xs:attributeGroup ref="atom:commonAttributes"/>
  </xs:complexType>
  <xs:complexType name="extendedAttributeType">
    <xs:choice  maxOccurs="unbounded">
      <xs:element name="name" type="xs:string" minOccurs="1" maxOccurs="1"/>
      <xs:element name="value" type="xs:string" minOccurs="1" maxOccurs="1"/>
    </xs:choice>
    <xs:attributeGroup ref="atom:commonAttributes"/>
  </xs:complexType>
  <xs:complexType name="entryType">
    <xs:choice maxOccurs="unbounded">
      <xs:element name="id" type="atom:idType" minOccurs="1" maxOccurs="1"/>
      <xs:element name="title" type="atom:textType" minOccurs="1" maxOccurs="1"/>
      <xs:element name="link" type="atom:linkType" minOccurs="0" maxOccurs="unbounded"/>
      <xs:element name="brand" type="xs:string" minOccurs="0" maxOccurs="unbounded"/>
    </xs:choice>
    <xs:attributeGroup ref="atom:commonAttributes"/>
  </xs:complexType>

  <xs:complexType name="linkType" mixed="true">
    <xs:attribute name="href" use="required" type="xs:anyURI"/>
    <xs:attribute name="rel" type="xs:string" use="optional"/>
    <xs:attribute name="type" use="optional" type="xs:string"/>
    <xs:attribute name="hreflang" use="optional" type="xs:NMTOKEN"/>
    <xs:attribute name="title" use="optional" type="xs:string"/>
    <xs:attribute name="length" use="optional" type="xs:positiveInteger"/>
    <xs:attributeGroup ref="atom:commonAttributes"/>
  </xs:complexType>

  <xs:complexType name="dateTimeType">
    <xs:simpleContent>
      <xs:extension base="xs:dateTime">
        <xs:attributeGroup ref="atom:commonAttributes"/>
      </xs:extension>
    </xs:simpleContent>
  </xs:complexType>
  <xs:attributeGroup name="commonAttributes">
    <xs:attribute ref="xml:base"/>
    <xs:attribute ref="xml:lang"/>
    <xs:anyAttribute namespace="##other"/>
  </xs:attributeGroup>
</xs:schema>

I'm guessing the error has to do with my namespace declared in the XML (xmlns:g="http://base.google.com/ns/1.0").  I have entered this in the targetNamespace of the XSD, but I cannot get it to work.

A: Atom 1.0 XSD
The Atom Syndication Format is an establish standard with an existing XSD:
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema targetNamespace="http://www.w3.org/2005/Atom"
           elementFormDefault="qualified"
           attributeFormDefault="unqualified"
           xmlns:atom="http://www.w3.org/2005/Atom"
           xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:annotation>
    <xs:documentation>
      This version of the Atom schema is based on version 1.0 of the format specifications,
      found here http://www.atomenabled.org/developers/syndication/atom-format-spec.php.
    </xs:documentation>
  </xs:annotation>
  <xs:import namespace="http://www.w3.org/XML/1998/namespace"
             schemaLocation="http://www.w3.org/2001/03/xml.xsd"/>
  <xs:annotation>
    <xs:documentation>
      An Atom document may have two root elements, feed and entry, as defined in section 2.
    </xs:documentation>
  </xs:annotation>
  <xs:element name="feed" type="atom:feedType"/>
  <xs:element name="entry" type="atom:entryType"/>
  <xs:complexType name="textType" mixed="true">
    <xs:annotation>
      <xs:documentation>
        The Atom text construct is defined in section 3.1 of the format spec.
      </xs:documentation>
    </xs:annotation>
    <xs:sequence>
      <xs:any namespace="http://www.w3.org/1999/xhtml" minOccurs="0"/>
    </xs:sequence>
    <xs:attribute name="type">
      <xs:simpleType>
        <xs:restriction base="xs:token">
          <xs:enumeration value="text"/>
          <xs:enumeration value="html"/>
          <xs:enumeration value="xhtml"/>
        </xs:restriction>
      </xs:simpleType>
    </xs:attribute>
    <xs:attributeGroup ref="atom:commonAttributes"/>
  </xs:complexType>
  <xs:complexType name="personType">
    <xs:annotation>
      <xs:documentation>
        The Atom person construct is defined in section 3.2 of the format spec.
      </xs:documentation>
    </xs:annotation>
    <xs:choice minOccurs="1" maxOccurs="unbounded">
      <xs:element name="name" type="xs:string" minOccurs="1" maxOccurs="1"/>
      <xs:element name="uri" type="atom:uriType" minOccurs="0" maxOccurs="1"/>
      <xs:element name="email" type="atom:emailType" minOccurs="0" maxOccurs="1"/>
      <xs:any namespace="##other"/>
    </xs:choice>
    <xs:attributeGroup ref="atom:commonAttributes"/>
  </xs:complexType>
  <xs:simpleType name="emailType">
    <xs:annotation>
      <xs:documentation>
        Schema definition for an email address.
      </xs:documentation>
    </xs:annotation>
    <xs:restriction base="xs:normalizedString">
      <xs:pattern value="\w+@(\w+\.)+\w+"/>
    </xs:restriction>
  </xs:simpleType>
  <xs:complexType name="feedType">
    <xs:annotation>
      <xs:documentation>
        The Atom feed construct is defined in section 4.1.1 of the format spec.
      </xs:documentation>
    </xs:annotation>
    <xs:choice minOccurs="3" maxOccurs="unbounded">
      <xs:element name="author" type="atom:personType" minOccurs="0" maxOccurs="unbounded"/>
      <xs:element name="category" type="atom:categoryType" minOccurs="0" maxOccurs="unbounded"/>
      <xs:element name="contributor" type="atom:personType" minOccurs="0" maxOccurs="unbounded"/>
      <xs:element name="generator" type="atom:generatorType" minOccurs="0" maxOccurs="1"/>
      <xs:element name="icon" type="atom:iconType" minOccurs="0" maxOccurs="1"/>
      <xs:element name="id" type="atom:idType" minOccurs="1" maxOccurs="1"/>
      <xs:element name="link" type="atom:linkType" minOccurs="0" maxOccurs="unbounded"/>
      <xs:element name="logo" type="atom:logoType" minOccurs="0" maxOccurs="1"/>
      <xs:element name="rights" type="atom:textType" minOccurs="0" maxOccurs="1"/>
      <xs:element name="subtitle" type="atom:textType" minOccurs="0" maxOccurs="1"/>
      <xs:element name="title" type="atom:textType" minOccurs="1" maxOccurs="1"/>
      <xs:element name="updated" type="atom:dateTimeType" minOccurs="1" maxOccurs="1"/>
      <xs:element name="entry" type="atom:entryType" minOccurs="0" maxOccurs="unbounded"/>
      <xs:any namespace="##other" minOccurs="0" maxOccurs="unbounded"/>
    </xs:choice>
    <xs:attributeGroup ref="atom:commonAttributes"/>
  </xs:complexType>
  <xs:complexType name="entryType">
    <xs:annotation>
      <xs:documentation>
        The Atom entry construct is defined in section 4.1.2 of the format spec.
      </xs:documentation>
    </xs:annotation>
    <xs:choice maxOccurs="unbounded">
      <xs:element name="author" type="atom:personType" minOccurs="0" maxOccurs="unbounded"/>
      <xs:element name="category" type="atom:categoryType" minOccurs="0" maxOccurs="unbounded"/>
      <xs:element name="content" type="atom:contentType" minOccurs="0" maxOccurs="1"/>
      <xs:element name="contributor" type="atom:personType" minOccurs="0" maxOccurs="unbounded"/>
      <xs:element name="id" type="atom:idType" minOccurs="1" maxOccurs="1"/>
      <xs:element name="link" type="atom:linkType" minOccurs="0" maxOccurs="unbounded"/>
      <xs:element name="published" type="atom:dateTimeType" minOccurs="0" maxOccurs="1"/>
      <xs:element name="rights" type="atom:textType" minOccurs="0" maxOccurs="1"/>
      <xs:element name="source" type="atom:sourceType" minOccurs="0" maxOccurs="1"/>
      <xs:element name="summary" type="atom:textType" minOccurs="0" maxOccurs="1"/>
      <xs:element name="title" type="atom:textType" minOccurs="1" maxOccurs="1"/>
      <xs:element name="updated" type="atom:dateTimeType" minOccurs="1" maxOccurs="1"/>
      <xs:any namespace="##other" minOccurs="0" maxOccurs="unbounded"/>
    </xs:choice>
    <xs:attributeGroup ref="atom:commonAttributes"/>
  </xs:complexType>
  <xs:complexType name="contentType" mixed="true">
    <xs:annotation>
      <xs:documentation>
        The Atom content construct is defined in section 4.1.3 of the format spec.
      </xs:documentation>
    </xs:annotation>
    <xs:sequence>
      <xs:any namespace="##other" minOccurs="0" maxOccurs="unbounded"/>
    </xs:sequence>
    <xs:attribute name="type" type="xs:string"/>
    <xs:attribute name="src" type="xs:anyURI"/>
    <xs:attributeGroup ref="atom:commonAttributes"/>
  </xs:complexType>
  <xs:complexType name="categoryType">
    <xs:annotation>
      <xs:documentation>
        The Atom cagegory construct is defined in section 4.2.2 of the format spec.
      </xs:documentation>
    </xs:annotation>
    <xs:attribute name="term" type="xs:string" use="required"/>
    <xs:attribute name="scheme" type="xs:anyURI" use="optional"/>
    <xs:attribute name="label" type="xs:string" use="optional"/>
    <xs:attributeGroup ref="atom:commonAttributes"/>
  </xs:complexType>
  <xs:complexType name="generatorType">
    <xs:annotation>
      <xs:documentation>
        The Atom generator element is defined in section 4.2.4 of the format spec.
      </xs:documentation>
    </xs:annotation>
    <xs:simpleContent>
      <xs:extension base="xs:string">
        <xs:attribute name="uri" use="optional" type="xs:anyURI"/>
        <xs:attribute name="version" use="optional" type="xs:string"/>
        <xs:attributeGroup ref="atom:commonAttributes"/>
      </xs:extension>
    </xs:simpleContent>
  </xs:complexType>
  <xs:complexType name="iconType">
    <xs:annotation>
      <xs:documentation>
        The Atom icon construct is defined in section 4.2.5 of the format spec.
      </xs:documentation>
    </xs:annotation>
    <xs:simpleContent>
      <xs:extension base="xs:anyURI">
        <xs:attributeGroup ref="atom:commonAttributes"/>
      </xs:extension>
    </xs:simpleContent>
  </xs:complexType>
  <xs:complexType name="idType">
    <xs:annotation>
      <xs:documentation>
        The Atom id construct is defined in section 4.2.6 of the format spec.
      </xs:documentation>
    </xs:annotation>
    <xs:simpleContent>
      <xs:extension base="xs:anyURI">
        <xs:attributeGroup ref="atom:commonAttributes"/>
      </xs:extension>
    </xs:simpleContent>
  </xs:complexType>
  <xs:complexType name="linkType" mixed="true">
    <xs:annotation>
      <xs:documentation>
        The Atom link construct is defined in section 3.4 of the format spec.
      </xs:documentation>
    </xs:annotation>
    <xs:attribute name="href" use="required" type="xs:anyURI"/>
    <xs:attribute name="rel" type="xs:string" use="optional"/>
    <xs:attribute name="type" use="optional" type="xs:string"/>
    <xs:attribute name="hreflang" use="optional" type="xs:NMTOKEN"/>
    <xs:attribute name="title" use="optional" type="xs:string"/>
    <xs:attribute name="length" use="optional" type="xs:positiveInteger"/>
    <xs:attributeGroup ref="atom:commonAttributes"/>
  </xs:complexType>
  <xs:complexType name="logoType">
    <xs:annotation>
      <xs:documentation>
        The Atom logo construct is defined in section 4.2.8 of the format spec.
      </xs:documentation>
    </xs:annotation>
    <xs:simpleContent>
      <xs:extension base="xs:anyURI">
        <xs:attributeGroup ref="atom:commonAttributes"/>
      </xs:extension>
    </xs:simpleContent>
  </xs:complexType>
  <xs:complexType name="sourceType">
    <xs:annotation>
      <xs:documentation>
        The Atom source construct is defined in section 4.2.11 of the format spec.
      </xs:documentation>
    </xs:annotation>
    <xs:choice maxOccurs="unbounded">
      <xs:element name="author" type="atom:personType" minOccurs="0" maxOccurs="unbounded"/>
      <xs:element name="category" type="atom:categoryType" minOccurs="0" maxOccurs="unbounded"/>
      <xs:element name="contributor" type="atom:personType" minOccurs="0" maxOccurs="unbounded"/>
      <xs:element name="generator" type="atom:generatorType" minOccurs="0" maxOccurs="1"/>
      <xs:element name="icon" type="atom:iconType" minOccurs="0" maxOccurs="1"/>
      <xs:element name="id" type="atom:idType" minOccurs="0" maxOccurs="1"/>
      <xs:element name="link" type="atom:linkType" minOccurs="0" maxOccurs="unbounded"/>
      <xs:element name="logo" type="atom:logoType" minOccurs="0" maxOccurs="1"/>
      <xs:element name="rights" type="atom:textType" minOccurs="0" maxOccurs="1"/>
      <xs:element name="subtitle" type="atom:textType" minOccurs="0" maxOccurs="1"/>
      <xs:element name="title" type="atom:textType" minOccurs="0" maxOccurs="1"/>
      <xs:element name="updated" type="atom:dateTimeType" minOccurs="0" maxOccurs="1"/>
      <xs:any namespace="##other" minOccurs="0" maxOccurs="unbounded"/>
    </xs:choice>
    <xs:attributeGroup ref="atom:commonAttributes"/>
  </xs:complexType>
  <xs:complexType name="uriType">
    <xs:simpleContent>
      <xs:extension base="xs:anyURI">
        <xs:attributeGroup ref="atom:commonAttributes"/>
      </xs:extension>
    </xs:simpleContent>
  </xs:complexType>
  <xs:complexType name="dateTimeType">
    <xs:simpleContent>
      <xs:extension base="xs:dateTime">
        <xs:attributeGroup ref="atom:commonAttributes"/>
      </xs:extension>
    </xs:simpleContent>
  </xs:complexType>
  <xs:attributeGroup name="commonAttributes">
    <xs:attribute ref="xml:base"/>
    <xs:attribute ref="xml:lang"/>
    <xs:anyAttribute namespace="##other"/>
  </xs:attributeGroup>
</xs:schema>

However, using even this XSD to validate your XML still results in errors such as the following:

[Error] feed.xml:12:14: cvc-complex-type.2.4.c: The matching wildcard
  is strict, but no declaration can be found for element 'g:brand'.

Google Base Namespace
To eliminate the errors related to the http://base.google.com/ns/1.0 Google Base namespace extensions, you have two options:

*

*Import the Google Base XSD into the Atom XSD:
<xs:import namespace="http://base.google.com/ns/1.0"
           schemaLocation="base-google.xsd"/>

The challenges here are (a) the XSD associated with the http://base.google.com/ns/1.0 namespace does not appear to live at a well-known, official location and (b) the XSD may not be being maintained.  I found one here.  [If anyone knows a more official or more up-to-date Google Base XSD, please comment and I'll update the link.]

*Loosen xsd:any/@processContents="strict" (the default) to lax.
(For the difference, see processContents strict vs lax vs skip for
xsd:any.)
Which route you go will depend upon how much validation you wish to do on the Google elements falling under xsd:any.  The first route will provide stricter validation, but your next problem will be that you'll have to change the XML or the XSD to fix further errors such as no declaration for g:mpn.  The second route will blissfully ignore such errors.

A: I could not find XSD anywhere but the Google has the feed specification here:
https://support.google.com/merchants/answer/7052112
It's not XSD thou.


text:
Q: What methods are available to execute things in the background My question is short and simple.
What are the different methods are available to execute things in the background, and what is the pros and cons for them?
I've used a few, like Thread, AsyncTask, TimerTask, Serivce, Service in other process, but
i don't know what their pros and cons are.

A: Use AsyncTasks for small tasks. if you want to do something periodic, like checking for updates every x sec, use background services (background Services can run even when youre app is closed, but don't have to).
Look here, that's a great explanation and tutorial for Asynctasks and threads:
http://www.vogella.com/tutorials/AndroidBackgroundProcessing/article.html

A: AsyncTask - Useful for simple tasks to be completed in the background. Often used to start a new Thread with the "Fire and Forget" mindset.
Thread - Useful for when there is a process with several steps, or needs to run forever in the background.
TimerTask - Useful for tasks that need to execute on a time based schedule.
Android Service - These share the main thread of application.  Services are basically an Activity without a layout.  Used to run processes in the background throughout the life of the application or activity, but needs to spawn their own thread for any heavy lifting.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Draw a voided shape in SVG I want to draw a shape in SVG that has the centre hollowed out.
I asked this question for drawing a circle with a circle in the middle here.
I would like to draw any shape in SVG with the middle (of another shape) hollowed out.
Any ideas?
I'm thinking it could be possible using Masks or ClipPaths but I'm not sure if I understand them fully

A: Create your shape as a path, which consists of two sub-paths. The first subpath describes your outer shape; the second subpath describes the inside shape. Set the fill-rule of the pathto 'evenodd'.
e.g. for a hollowed out rectangle, we make a path consisting of two sub-paths. One for the outside rectangle; one for the inner rectangle:
<svg xmlns="http://www.w3.org/2000/svg" version="1.1">

<path d="M 100 100 L 200 100 L 200 200 L 100 200 z
     M 110 110 L 190 110 L 190 190 L 110 190 z"
     fill="red"
     stroke="black" stroke-width="1"
     fill-rule="evenodd"/>

</svg>


text:
Q: Wireless not working anymore on Acer Aspire 6930G when I upgraded to 12.04 I have been using Ubuntu for a long time and I have never encountered any driver related issues. However after I upgraded my Ubuntu to the latest version Ubuntu 12.04 LTS, wireless is not working anymore. My machine is Acer Aspire 6930G. The output of ifconfig:
eth0      Link encap:Ethernet  HWaddr 00:23:8b:ab:ca:75
          inet addr:192.168.1.37  Bcast:192.168.1.255  Mask:255.255.255.0
          inet6 addr: fe80::223:8bff:feab:ca75/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:22966 errors:0 dropped:0 overruns:0 frame:0
          TX packets:20439 errors:0 dropped:0 overruns:0 carrier:2
          collisions:0 txqueuelen:1000
          RX bytes:23522506 (23.5 MB)  TX bytes:3213803 (3.2 MB)
          Interrupt:47

lo        Link encap:Local Loopback
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:16436  Metric:1
          RX packets:2365 errors:0 dropped:0 overruns:0 frame:0
          TX packets:2365 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:385015 (385.0 KB)  TX bytes:385015 (385.0 KB)

wlan0     Link encap:Ethernet  HWaddr 00:22:fa:1a:6c:a8
          inet addr:192.168.1.35  Bcast:192.168.1.255  Mask:255.255.255.0
          inet6 addr: fe80::222:faff:fe1a:6ca8/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:208 errors:0 dropped:0 overruns:0 frame:0
          TX packets:60 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:32326 (32.3 KB)  TX bytes:12005 (12.0 KB)

A: I had a similar problem, and this helped.
https://help.ubuntu.com/community/WifiDocs/Driver/bcm43xx#Installing_STA_drivers
Note: In my case at this step  'System > Administration > Hardware/Additional Drivers,'  The driver failed to install correctly, but it starting working after rebooting the laptop.
Good luck.


text:
Q: Spring boot dynamic database URL based on REST parameters I am using Spring boot to develop an application, we have one database for each customer, and the main problem is to avoid creating one instance for each, connected to a single database. With that in mind, I got stuck in the following situation:
I need my application to make connections to several different databases, witch Aliases I don't know when the application starts. Those aliases will be provided via REST requests, so it's dynamic.
All other credentials are equal on the databases, the Driver, URL, username and password, I really just need to change the alias to provide the right URL for that request.
I've done it creating datasources at the momment of the request, like this:
private static void selectAll(String alias){

    String sql = "select * from user";

    DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create();
    dataSourceBuilder.url("jdbc:postgresql://localhost:5432/"+alias);
    dataSourceBuilder.username("username");
    dataSourceBuilder.password("password");
    DataSource dataSource = dataSourceBuilder.build();

    try {
        Connection con = dataSource.getConnection();
        con.setAutoCommit(true);
        con.prepareStatement(sql).executeQuery();
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

But by doing things that way, i can't use criteria and hibernate, and I have to map my objects retreived from the database by hand and write my own simple SQLs for each object/table.
The main question is, can i use Entities and Repositories (Spring data) with dynamic databases, or if I go for this I'll have to choose between those and having one instance for each customer, connected to a single database.
I've searched on forums, and the solutions are eigther based on static connections, configured inside Application.properties, or they assume that the the URL is known.
Thank you for your help, any other better aproaches are wellcome, any toughts at all.


text:
Q: Second-order nonlinear ODE involving cosine of the unknown function Question

I am interested in solving for $u : S^1 \to S^1$ given the following ODE, where $v : S^1 \to S^1$ is a given continuous function:
$$u'' = -A\cos(u-v) \tag{$\dagger$}$$
Is there any hope of an analytic solution? Can anything be said about the behavior of the solution as $A$ varies? If it helps, I have $\int_{S^1} \cos[v(\theta)]\ d\theta = \int_{S^1} \sin[v(\theta)]\ d\theta = 0$.

Background
I've been interested in crystalline and anisotropic mean curvature flows, along the line of the work of Novaga and Chambolle, e.g. https://onlinelibrary.wiley.com/doi/abs/10.1002/cpa.21668
My actual problem is more involved and three-dimensional, but to build intuition I've been trying to think about the following two-dimensional simplification.
Consider a curve $\gamma:S^1 \to \mathbb{R}^2$, which for simplicity we can take to be arclength-parameterized with arc length $2\pi$. Let us write $\gamma'(\theta) = [\cos(v[\theta]), \sin(v[\theta])]$. I want to study sections of the bundle of directors $\hat{m}(\theta) \in S^1$ along the curve: I want these directors to approximate the orientation of the curve normal, while also behaving more smoothly near regions of sharp curvature. Let $\hat{n}(\theta) = [-\sin(v[\theta]), \cos(v[\theta])]$ denote the curve normal at $\theta$; I would like to look at minimizers of the functional
$$E(\hat m) = \int_{S^1} \left(\frac{1}{2}\left\|\hat{m}'(\theta)\right\|^2 + \frac{A}{2} \left\|\hat m(\theta) - \hat n(\theta)\right\|^2\right)\,ds$$
where the real constant $A$ controls the relative importance of smoothness vs adapting to the curve normal.
Applying the calculus of variations, we have that an extremizer $\hat{m}^*(\theta) = [\cos u^*(\theta), \sin u^*(\theta)]$ of $E$ satisfies the ODE
$(u^*)''(\theta) = -A\cos[u^*(\theta) - v(\theta)]$, where $v: S^1\to S^1$ is prescribed by the choice of $\gamma$. And we know that $\int_{S^1} \cos[v(\theta)]\ d\theta = \int_{S^1} \sin[v(\theta)]\ d\theta = 0$, since the curve $\gamma$ is closed. Hence my question.
My eventual goal is to take variations of $E(\hat{m}^*)$ with respect to $\gamma$ to flow the curve, so an analytic solution to the ODE ($\dagger$) would be very helpful.
Some trivial observations: $E(\hat{m}^*)$ is bounded above by on the one hand $A\pi$, and on the other hand, $\int_{S^1} \kappa(\theta)^2\,ds$ (where $\kappa(\theta)$ is the curvature at $\theta$), for a constant director field, and $\hat m = \hat n$, respectively.

A: For arbitrary $v$?  No, no hope.  For certain specific $v$, yes.
In fact, let $U(\theta)$ be any twice-differentiable function with $|U''/A|< 1$
and take $v(\theta) = U(\theta) + \arccos(U''/A)$, and $U(\theta)$ will be a solution.


text:
Q: How can we derive the equations? This is an excerpt from the book Curves and Surfaces for Computer Graphics.

How did the author derive $ \alpha $ and $ \beta $?

A: $\alpha\ \mathbf{A} + \beta\ \mathbf{B} + \mathbf{C} = 0$ is nothing but a system of two equations, one for each component $x$ and $y$:
$$
\cases{
\alpha {A_x} + \beta B_x + C_x = 0&\cr
\alpha {A_y} + \beta B_y + C_y = 0&\cr
}
$$
 One can solve it with a variety of well known methods.

A: $$
\alpha \mathbf{A} + \beta \mathbf{B} = -\mathbf{C}
$$
Knowing that the vector cross product of parallel vectors leads to zero so
$$
\alpha \mathbf{A}\times \mathbf{B} = -\mathbf{C}\times \mathbf{B}
$$ thus we get
$$
\alpha = -\frac{\mathbf{C}\times \mathbf{B}}{\mathbf{A}\times \mathbf{B}}
$$
And similarly
$$
\beta = -\frac{\mathbf{C}\times \mathbf{A}}{\mathbf{B}\times \mathbf{A}}
$$
Do you need me to go over the products?


text:
Q: Fermat's numbers as the difference of two consecutive squares By well known result we know that Fermat's number is prime if and only if it can be uniquely written in the sum of two squares.
My question is that: Can we write every Fermat's number as the difference of two consecutive squares.
Using that I want to relate the problem with Legendre's conjecture that is there exist a prime between any two consecutive squares.

A: Yes. Every odd number is a difference of consecutive squares - we have $2k+1=(k+1)^2-k^2$.


text:
Q: How to write an event for multiple checkbox.Checked? I am building a plumbing services windows form that has three checkboxes, each with different totals representing the type of service. If two or more were checked how would I combine their totals so they can be displayed in a designated text box rather than just displaying the individual amount.
        private void apprenticeCheck_CheckedChanged(object sender, EventArgs e)
        {
            double apprenticeCost;
            apprenticeCost = 55.00 + CALLOUT_AMOUNT;

            if (apprenticeCheck.Checked)
                serviceTotalText.Text = apprenticeCost.ToString("C");

A: You can create a variable for keeping track of total amount and update this variable at every check of any checkbox
    const int CALLOUT_AMOUNT = 5;
    double TotalCost = 0;

    private void apprenticeCheck_CheckedChanged(object sender, EventArgs e)
    {
        double apprenticeCost = 55.00 + CALLOUT_AMOUNT;

        if (apprenticeCheck.Checked)
            TotalCost += apprenticeCost;
        else
            TotalCost -= apprenticeCost;

        serviceTotalText.Text = TotalCost.ToString("C");
    }

A: A simple approach, create a class to represent a service.
public class Service
{
    public int Id { get; set; }
    public string Name { get; set; }
    public double Cost { get; set; }
}

Using a private list of CheckBox, assign OnCheckedChanged event for each CheckBox. In the Check changed event use a lambda statement to get total against those CheckBoxes that are checked.
Code assumes the CheckBox controls are directly on the form.
namespace PlumbingExample
{
    public partial class Form1 : Form
    {
        private readonly List<CheckBox> _checkBoxes;
        private double _serviceCharge = 5d;

        public Form1()
        {
            InitializeComponent();
            Shown += OnShown;
            _checkBoxes = Controls.OfType<CheckBox>().ToList();
        }

        private void OnShown(object sender, EventArgs e)
        {
            Service1CheckBox.Tag = new Service() { Id = 1, Name = "Service 1", Cost = 45.00d };
            Service2CheckBox.Tag = new Service() { Id = 2, Name = "Service 2", Cost = 55.00d };
            Service3CheckBox.Tag = new Service() { Id = 3, Name = "Service 3", Cost = 65.00d };

            _checkBoxes.ForEach(x => x.CheckStateChanged += CheckBoxOnCheckedChanged);

            serviceTotalText.Text = "$0.00";
        }

        private void CheckBoxOnCheckedChanged(object sender, EventArgs e)
        {
            var total = _checkBoxes
                .Where(checkBox => checkBox.Checked)
                .Select(checkBox => ((Service)checkBox.Tag).Cost + _serviceCharge)
                .Sum();

            serviceTotalText.Text = total.ToString("C");
            serviceTotalText.Tag = total;
        }
    }
}


text:
Q: How can I get the count of elements between elements of another class? I need to get the count of rows between the first category header and the second category header to use in a for loop as an increment. Here is an example of the html:

...

...

...

...

...

...

...

...

...

...

...

...

...

...

...

Here is what I have put together so far (obviously it doesn't work):
final int noItemsIn1stCat = driver.findElement(By.xpath("//div[@class='datagrid-ready']/div[contains(@class,'productTableRow')]")).size();

I am at a loss on how to get 5 into noItemsIn1stCat.
Would it be easier or more reliable to use a css selector?
I am new to java and selenium, so any help would be entirely appreciated!

A: The node-set containing sibling elements between two other siblings can be obtained calculating the intersection of two sets. Set A: the set of elements that are following siblings of the first element, with Set B: the set of elements that are preceding siblings of the last element.
You can use the Kaysian method to select an intersection between two sets (see a more detailed explanation in the links I posted in the comments). The formula to obtain the intersection is:
SetA [ count( . | setB) = count( setB ) ]

Applying that to your problem, with:
SetA = //div[@class='datagrid-ready']
        /div[@class='categoryHeader'][1]
        /following-sibling::div[@class='productTableRow']

and
SetB = //div[@class='datagrid-ready']
        /div[@class='categoryHeader'][2]
        /preceding-sibling::div[@class='productTableRow']

you have:
//div[@class='datagrid-ready']
  /div[@class='categoryHeader'][1]
  /following-sibling::div[@class='productTableRow']
    [ count( . | //div[@class='datagrid-ready']
                  /div[@class='categoryHeader'][2]
                  /preceding-sibling::div[@class='productTableRow'])
    = count( //div[@class='datagrid-ready']
              /div[@class='categoryHeader'][2]
              /preceding-sibling::div[@class='productTableRow'] ) ]

or in one line:
//div[@class='datagrid-ready']/div[@class='categoryHeader'][1]/following-sibling::div[@class='productTableRow'][count(.|//div[@class='datagrid-ready']/div[@class='categoryHeader'][2]/preceding-sibling::div[@class='productTableRow']) = count( //div[@class='datagrid-ready']/div[@class='categoryHeader'][2]/preceding-sibling::div[@class='productTableRow'] ) ]

In your example, this expression will select these five nodes:

To count the nodes, simply place the whole expression as an argument to the count() function:
count(//div[@class='datagrid-ready']/div[@class='categoryHeader'][1]/following-sibling::div[@class='productTableRow'][count(.|//div[@class='datagrid-ready']/div[@class='categoryHeader'][2]/preceding-sibling::div[@class='productTableRow']) = count( //div[@class='datagrid-ready']/div[@class='categoryHeader'][2]/preceding-sibling::div[@class='productTableRow'])])


text:
Q: Taking the data from one file, altering it, and then rewriting it to a new file using python So I'm somewhat new to python and I am trying to write a program that takes the numerical grades in one file and changes them to letter grades. I am also trying to do this without using "with" or sets. This is what I have so far
def main():

    #read the file
    name = "grades.dat"
    file = open(name,'r')

    for line in file:
        read_file_contents = file.readline()
        grade_change(read_file_contents)
    file.close()
    write_file_name = name + "_out"
    write_file = open(write_file_name, 'w')
    write_file.write(read_file_contents)

    write_file.close()

def grade_change(grade):
    float(grade)
    if grade>90:
        return "A"
    elif grade>80:
        return "B"
    elif grade>70:
        return "C"
    elif grade>60:
        return "D"
    elif grade>0:
        return "F"

main()

A: This will just write out the first line of the input file. You should append to a list with each of the output letter grades and then write out each of these to the out file at the end.

A: In your function you would need to set grade = float(grade) to actually cast grade as a float and reassign grade to the result, the easiest way is to loop over your file object and cast as you pass it to your function then open the output file with and write:
name = "grades.dat"
def grade_change(grade):
    if grade > 90:
        return "A"
    elif grade > 80:
        return "B"
    elif grade > 70:
        return "C"
    elif grade > 60:
        return "D"
    else:
        return "F"

with open(name) as f:
    # pass each grade to your function cast to a float
    changed = (grade_change(float(grde)) for grde in f)

with open(write_file_name, "w") as out:
    # iterate over each grade in changed and write adding a newline char
    for gde in changed:
        out.write("{}\n".format(ged))

You can do the same thing without using with but using with is the idiomatic way to open a file in python.
 I presume if the grade is not from A-E it must be an F so we just need an else.
If your file is actually a single line or lines of data separated by spaces then you need to split into individual elements something like the following, if the delimiter is a comma etc.. then pass a comma to split instead, you will also need to decide if you want each grade on single line or a line of grades :
with open(name) as f:
    changed = (grade_change(gde) for line in f for gde in line.split())


text: Q: Is flexbox considered part of vanilla CSS? I'm just confused because it's a thing with a specific name that people use a lot, as if it's separate from vanilla, but it's just a thing that's built in. Would I need to mention that I know how to use flexbox on a skill list?


text:
Q: RODBC connection failing in opencpu I need to fetch data on a SQL Server through opencpu. RODBC works perfectly with single-user version of opencpu. However on the cloud server I get this error:
first argument is not an open RODBC channel
In call:
RODBC::sqlQuery(dbhandle, sql_query)

The very same function fetches data perfectly on Rstudio server (same server ubuntu 16.04, same connection string, using driver FreeTDS).
Is there some special driver settings I'm missing for ODBC to work with opencpu ?

A: Finally found this question that helped a lot.
Looks like the problem was AppArmor. By opening /var/log/kern.log I realized there were some rules to add in /etc/apparmor.d/opencpu.d/custom

A: As an example, if you use msodbcsql, the following line in /etc/apparmor.d/opencpu.d/custom should work:
/opt/microsoft/msodbcsql/** r,

Don't forget to restart apparmor:
sudo service apparmor restart


text:
Q: Show $\nu \ll \mu$ iff there is a sequence s.t $\nu = \sum_{n=1}^{\infty}a_n \delta_n$. What is $d\nu/d\mu$. Let $\mu$ be a counting measure over ($\mathbb{N}, \mathcal{P}(\mathbb{N})$). Show that a
measure $\nu$ over ($\mathbb{R}, \mathcal{B}(\mathbb{R})$), is absolutely continuous with respect to $\mu$ iff there is a sequence $\{a_n\}$ of non-negative real numbers s. t. $\nu = \sum_{n=1}^{\infty}a_n \delta_n$. Compute $d\nu/d\mu$.
Any help is appreciated!
Thanks!


text:
Q: Command line options with optional arguments in Python I was wondering if there's a simple way to parse command line options having optional arguments in Python.  For example, I'd like to be able to call a script two ways:
> script.py --foo
> script.py --foo=bar

From the Python getopt docs it seems I have to choose one or the other.

A: Also, note that the standard library also has optparse, a more powerful options parser.

A: check out argparse:
http://code.google.com/p/argparse/
especially the 'nargs' option

A: optparse module from stdlib doesn't support it out of the box (and it shouldn't due to it is a bad practice to use command-line options in such way).
As @Kevin Horn pointed out you can use argparse module (installable via easy_install argparse or just grab argparse.py and put it anywhere in your sys.path).
Example
#!/usr/bin/env python
from argparse import ArgumentParser

if __name__ == "__main__":
    parser = ArgumentParser(prog='script.py')
    parser.add_argument('--foo', nargs='?', metavar='bar', default='baz')

    parser.print_usage()
    for args in ([], ['--foo'], ['--foo', 'bar']):
        print "$ %s %s -> foo=%s" % (
            parser.prog, ' '.join(args).ljust(9), parser.parse_args(args).foo)

Output

usage: script.py [-h] [--foo [bar]]
$ script.py           -> foo=baz
$ script.py --foo     -> foo=None
$ script.py --foo bar -> foo=bar

A: There isn't an option in optparse that allows you to do this. But you can extend it to do it:
http://docs.python.org/library/optparse.html#adding-new-actions

A: Use the optparse package.


text:
Q: How to set spring active profiles with maven profiles I have an application with maven as a build tool.
I am using maven profiles to set up different properties from different profiles.
What i would like to do is that all active profiles in maven will be ported to spring active profiles as well so i can reference them in bean signature (@profile). but i am not sure how to do it.
for example: consider the following maven setup
<profiles>
    <profile>
        <id>profile1</id>
        <activation>
            <activeByDefault>true</activeByDefault>
        </activation>
        <properties>
        </properties>
    </profile>
    <profile>
        <id>profile2</id>
        <properties>
        </properties>
    </profile>
    <profile>
        <id>development</id>
        <activation>
            <activeByDefault>true</activeByDefault>
        </activation>
        <properties>
        </properties>
    </profile>
    <profile>
        <id>production</id>
        <properties>
        </properties>
    </profile>
</profiles>

assuming i run maven with out specifying any other profiles i would like for spring to have profile1 and  development as active profiles.

A: For a Spring Boot application, one can add a property in the Maven profile in pom.xml and then reference that property in application.properties.
Add Maven profiles to pom.xml with, for example, a property called spring.profile.from.maven:
<profiles>
    <profile>
        <id>postgres</id>
        <activation>
            <activeByDefault>true</activeByDefault>
        </activation>
        <properties>
            <spring.profile.from.maven>postgres</spring.profile.from.maven>
        </properties>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-jpa</artifactId>
            </dependency>
            <dependency>
                <groupId>org.postgresql</groupId>
                <artifactId>postgresql</artifactId>
                <scope>runtime</scope>
            </dependency>
        </dependencies>
    </profile>
    <profile>
        <id>noDb</id>
        <properties>
            <spring.profile.from.maven>noDb</spring.profile.from.maven>
        </properties>
    </profile>
</profiles>

Reference the Maven property in application.properties:
spring.profiles.include=@spring.profile.from.maven@

With this setup, running maven with the postgres Maven profile or with no profile adds the postgres Spring profile to the list of Spring's active profiles, while running maven with the noDb Maven profile adds the noDb Spring profile to the list of Spring's active profiles.

A: There is a more elegant way to switch between 2 maven+spring profiles simultaneously.
First, add profiles to POM (pay attention - maven+spring profile is activated by single system variable):
<profiles>
    <profile>
        <id>postgres</id>
        <activation>
            <activeByDefault>true</activeByDefault>
            <property>
                <name>spring.profiles.active</name>
                <value>postgres</value>
            </property>
        </activation>
        <dependencies>
            <dependency>
                <groupId>postgresql</groupId>
                <artifactId>postgresql</artifactId>
                <version>9.1-901.jdbc4</version>
            </dependency>
        </dependencies>
    </profile>
    <profile>
        <id>h2</id>
        <activation>
            <property>
                <name>spring.profiles.active</name>
                <value>h2</value>
            </property>
        </activation>
        <dependencies>
            <dependency>
                <groupId>com.h2database</groupId>
                <artifactId>h2</artifactId>
                <version>1.4.191</version>
            </dependency>
        </dependencies>
    </profile>
</profiles>

Second, set default profile for spring (for maven it is already set in POM). For web application, I inserted following lines to web.xml:
<context-param>
   <param-name>spring.profiles.default</param-name>
   <param-value>postgres</param-value>
</context-param>

Third, add profile-dependent beans to your config. In my case (XML config), it is:
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="dataSource" ref="mainDataSource" />
    <property name="jpaVendorAdapter">
        <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
    </property>
    <property name="jpaProperties" ref="hibProps"/>
    <property name="packagesToScan">
        <list>
            <value>my.test.model</value>
        </list>
    </property>
</bean>
...
<beans profile="postgres">
    <bean name="mainDataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="org.postgresql.Driver" />
        <property name="url" value="jdbc:postgresql://127.0.0.1:5432/webchat" />
        <property name="username" value="postgres" />
        <property name="password" value="postgres" />
    </bean>
</beans>

<beans profile="h2">
    <bean name="mainDataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="org.h2.Driver" />
        <property name="url" value="jdbc:h2:file:./newsdb;INIT=RUNSCRIPT FROM 'classpath:init.sql';TRACE_LEVEL_FILE=0" />
        <property name="username" value="sa" />
        <property name="password" value="" />
    </bean>
</beans>

Now it is possible to:

*

*Run my web-app on Postgres DB with mvn jetty:run or mvn jetty:run -Dspring.profiles.active=postgres commands

*Run my web-app on H2 DB with mvn clean jetty:run -Dspring.profiles.active=h2

A: The first thing you need is two properties files for keeping your configurations. The names of the files should match with the pattern application-{custom_suffix}.properties. Create them in the src/main/resources directory of your Maven project, next to the main application.properties file, which you're going to use later to activate one of the others and to hold values shared by both profiles.
Then it's time to modify your pom.xml. You need to define a custom property in each of your Maven profiles and set their values to match with suffixes of corresponding properties files that you want to load with a particular profile. The following sample also marks the first profile to run by default, but it's not mandatory.
<profile>
    <id>dev</id>
    <properties>
        <activatedProperties>dev</activatedProperties>
    </properties>
    <activation>
        <activeByDefault>true</activeByDefault>
    </activation>
</profile>
<profile>
    <id>release</id>
    <properties>
        <activatedProperties>release</activatedProperties>
    </properties>
</profile>

Next, in the build section of the same file, configure filtering for the Resources Plugin. That will allow you to insert properties defined in the previous step into any file in the resources directory, which is the subsequent step.
<build>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <filtering>true</filtering>
        </resource>
    </resources>
    …
</build>

Finally, add the following line to the application.properties.
spring.profiles.active=@activatedProperties@

When the build is run, the Resources Plugin will replace the placeholder with the value of the property defined in the active Maven profile. After starting  your application, the Spring framework will load the appropriate configuration file based on the name of the active Spring profile, which is described by the value of the spring.profiles.active property. Note that Spring Boot 1.3 replaced the default Resources Plugin syntax for filtered values and uses @activatedProperties@ instead of ${activatedProperties} notation.
It worked to perfection. Hope this can help you.

A: Add placeholder ${activeProfile} in web.xml:
<context-param>
  <param-name>spring.profiles.active</param-name>
  <param-value>${activeProfile}</param-value>
</context-param>

Set properties in pom.xml for each profile:
<profiles>
  <profile>
    <id>profile1</id>
    <activation>
      <activeByDefault>true</activeByDefault>
    </activation>
    <properties>
      <activeProfile>profile1</activeProfile>
    </properties>
  </profile>
  <profile>
    <id>profile2</id>
    <properties>
      <activeProfile>profile2</activeProfile>
    </properties>
  </profile>
</profiles>

Add maven-war-plugin and set <filteringDeploymentDescriptors>true</filteringDeploymentDescriptors> to replace the placeholder when running mvn package -Pprofile1 or mvn package -Pprofile2:
<build>
  <plugin>
    <artifactId>maven-war-plugin</artifactId>
    <version>3.2.2</version>
    <configuration>
      <filteringDeploymentDescriptors>true</filteringDeploymentDescriptors>
    </configuration>
  </plugin>
</build>

A: You'll have to filter a resources of your application, for instance a property file, that holds the information of which profile to activate in spring.
For instance
spring.profile = ${mySpringProfile}

And for each profile, define a value for this variable (mySpringProfile).
During the build, this will be filtered accordingly to the value defined in the currently active profile.
Then during the bootstrap of your application you'll select the appropriated profile according to this file (can't help you more as you didn't gave us more information, but this is quite easy.
Note: I can't find a way to get the currently active profile in maven (something like project.profiles.active that holds your -P values), that's why you'll have to set a new variable for each profile.
Note 2: if you are running a web application, instead of using this intermediate file, filter this value in your web.xml
<context-param>
    <param-name>spring.profiles.active</param-name>
    <param-value>${mySpringProfile}</param-value>
</context-param>

Note 3: This is actually a bad practice, and you should set the profile at runtime with a system property

A: I'm currently building a small webapp that (due to reasons beyond my control) has to be capable of running on an old server/container that only supports Servlet 2.5 and Java 6. There is also a requirement for the webapp configuration to be completely self-contained, so even system variables and/or JVM parameters cannot be used. The administrator just wants a .war file for each environment that can be dropped into the container for deployment.
I'm using Spring 4.x in my webapp. This is how I configured my application such that the active Maven profile is used to set the active Spring 4.x profile.

pom.xml file changes
I added the following bits to my POM file. My POM is using model version 4.0.0 and I'm running Maven 3.1.x when I do my builds.
<modelVersion>4.0.0</modelVersion>

...

<profiles>
    <profile>
        <id>dev</id>
        <activation>
            <!-- Default to dev so we avoid any accidents with prod! :) -->
            <activeByDefault>true</activeByDefault>
        </activation>
        <properties>
            <!-- This can be a single value, or a comma-separated list -->
            <spring.profiles.to.activate>dev</spring.profiles.to.activate>
        </properties>
    </profile>
    <profile>
        <id>uat</id>
        <properties>
            <!-- This can be a single value, or a comma-separated list -->
            <spring.profiles.to.activate>uat</spring.profiles.to.activate>
        </properties>
    </profile>
    <profile>
        <id>prod</id>
        <properties>
            <!-- This can be a single value, or a comma-separated list -->
            <spring.profiles.to.activate>prod</spring.profiles.to.activate>
        </properties>
    </profile>
</profiles>

...

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-war-plugin</artifactId>
            <version>2.6</version>
            <configuration>
                <webResources>
                    <webResource>
                        <filtering>true</filtering>
                        <directory>src/main/webapp</directory>
                        <includes>
                            <include>**/web.xml</include>
                        </includes>
                    </webResource>
                </webResources>
                <failOnMissingWebXml>true</failOnMissingWebXml>
            </configuration>
        </plugin>
        ...
    </plugins>
</build>

web.xml file changes
<!-- ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Setup for root Spring context
-->
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/spring-core-config.xml</param-value>
</context-param>
<!--
Jim Tough - 2016-11-30
Per Spring Framework guide: http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#beans-environment

...profiles may also be activated declaratively through the spring.profiles.active
property which may be specified through system environment variables, JVM system
properties, servlet context parameters in web.xml, or even as an entry in JNDI.
-->
<context-param>
    <param-name>spring.profiles.active</param-name>
    <param-value>${spring.profiles.to.activate}</param-value>
</context-param>
<!-- ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -->

Now I can create Java-based configuration classes like the one below that will only be used when a particular Spring profile is active.
@Configuration
@Profile({"dev","default"})
@ComponentScan
@EnableTransactionManagement
@EnableSpringDataWebSupport
public class PersistenceContext {
    // ...
}

A: spring boot plugin itself can help:
  <profiles>
    <profile>
      <id>postgres</id>
      <build>
        <plugins>
          <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <configuration>
              <jmxPort>9001</jmxPort>
              <environmentVariables>
                <SPRING_PROFILES_ACTIVE>postgres</SPRING_PROFILES_ACTIVE>
              </environmentVariables>
            </configuration>
          </plugin>
        </plugins>
      </build>
    </profile>
    <profile>
      <id>h2</id>
      <build>
        <plugins>
          <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <configuration>
              <jmxPort>9002</jmxPort>
              <environmentVariables>
                <SPRING_PROFILES_ACTIVE>h2</SPRING_PROFILES_ACTIVE>
              </environmentVariables>
            </configuration>
          </plugin>
        </plugins>
      </build>
    </profile>
  </profiles>

A: In the spring boot application, there are several ways to set profiles (dev, uat, prod, etc.)
For exmaple : You can add this in your property file:
spring.profiles.active=dev

Programmatically:
SpringApplication.setAdditionalProfiles("dev");

To specify what profiles are active, use this line
@ActiveProfiles("dev")

In a Unix environment
export spring_profiles_active=dev

Running the jar file with the dev profile.
java -jar -Dspring.profiles.active=dev JARNAME.jar

here JARNAME.jar means your application's jar


text:
Q: Sobolev space of differential forms I came across the following definition:
The Sobolev space $W^{k,p}_1(M)$ is the space of differential forms $\alpha\in\Omega^pM$  such that
$$\|\alpha\|^2_0=\int_M\alpha\wedge \star\alpha<\infty \qquad \&\qquad \|\nabla^l\alpha\|^2_0<\infty \quad 1\leq l\leq k,$$
i.e. $\alpha$ is in $L^2$ together with its covariant derivatives up to order $k$.
I was wondering how the covariant derivative of any $p$-form is defined. I guess it is constructed from the Levi-Civita connection on the bundle $\Lambda^pTM^*$ but I don't get how to apply it to the previous definition. Don't we need a direction $X\in \mathfrak{X}(M)$ for the covariant derivatives? Are we checking the previous condition on every possible direction?


text:
Q: Query XML Nodes Containing Periods In PowerShell I have a web based application used to query a number of different servers.  There is an XML file that contains all the other servers along with the ports used to communicate with those servers. If I query:
$File.servers.add.parameters

I can see a list of all the parameters for each server.  If I query:
$File.servers.add.parameters.specificParameter

I can get a list of almost all the parameters listed, however there is one parameter called
server.Query.Port

That I can't return, and I'm certain it's because it has periods in it.
I have tried
$File.servers.add.parameters['server.Query.Port']

Which returns nothing at all.  Anyone have a suggestion as to how to make this work?

A: $File.servers.add.parameters."server.Query.Port" worked.


text:
Q: Dynamic PHP PDO MYSQL query doesn't Update [No error returned] Ok, i try to make an update query with PDO MYSQL so to learn how make it work and then make a function to make it more efficiently
The problem is doesn't work, i do all the debugg the Log files allow me, and the personal returns too, i alsy fix wherever the navigator tell & even with Firebug
Any ideas what can be?
Any suggestion, question, comment or any kind of answer than help to improve, clarify or answer the question would be much aprreciated
Thanks in advance
<?php
include('conexion.php');
session_start();

 $idf = $_POST['Id_Msg'];
 $ids = (int) $idf;

 var_dump($ids);
  echo '

';
 var_dump($_FILES);

 echo '

';
 var_dump($_POST);
 echo '

';

  $wlq = -1;

 if($_POST['Title']) {
     $wlq++;
 }
 if($_POST['Prelude']) {
     $wlq++;
 }

 if($_POST['Text']) {
     $wlq++;
 }

 if($_POST['NOMBR1']) {
     $wlq++;
 }

 if($_POST['NOMBR2']) {
     $wlq++;
 }

 if($_POST['NOMBR3']) {
     $wlq++;
 }

 if($_POST['NOMBR4']) {
     $wlq++;
 }

 if($_POST['REGIN']) {
     $wlq++;
 }

 if($_POST['CTGRY']) {
     $wlq++;
 }

 if(!empty($_FILES['RutIm']['name'])) {
     $wlq++;
     echo 'me esta detectando visteh!';
 }

 echo "Asignado es: ".$wlq.'

';

 $qls = "UPDATE `cmtmplo` SET";

 if($_POST['Title']) {
     if($wlq > 0){
    $qls .=" `Title` = :Title , ";
    $wlq--;
     } else {
    $qls .=" `Title` = :Title";
    }
 }

 if($_POST['Prelude']) {
     if($wlq > 0){
    $qls .=" `Prelude` = :Prelude , ";
    $wlq--;
     } else {
    $qls .=" `Prelude` = :Prelude";
    }
 }

 if($_POST['Text']) {
     if($wlq > 0){
    $qls .=" `Text` = :Text , ";
    $wlq--;
     } else {
    $qls .=" `Text` = :Text";
    }
 }

 if($_POST['NOMBR1']) {
     if($wlq > 0){
    $qls .=" `NOMBR1` = :NOMBR1 , ";
    $wlq--;
     } else {
    $qls .=" `NOMBR1` = :NOMBR1";
    }
 }

 if($_POST['NOMBR2']) {
     if($wlq > 0){
    $qls .=" `NOMBR2` = :NOMBR2 , ";
    $wlq--;
     } else {
    $qls .=" `NOMBR2` = :NOMBR2";
    }
 }

 if($_POST['NOMBR3']) {
     if($wlq > 0){
    $qls .=" `NOMBR3` = :NOMBR3 , ";
    $wlq--;
     } else {
    $qls .=" `NOMBR3` = :NOMBR3";
    }
 }

 if($_POST['NOMBR4']) {
     if($wlq > 0){
    $qls .=" `NOMBR4` = :NOMBR4 , ";
    $wlq--;
     } else {
    $qls .=" `NOMBR4` = :NOMBR4";
    }
 }

 if($_POST['REGIN']) {
     if($wlq > 0){
    $qls .=" `REGIN` = :REGIN , ";
    $wlq--;
     } else {
    $qls .=" `REGIN` = :REGIN";
    }
 }

 if($_POST['CTGRY']) {
     if($wlq > 0){
    $qls .=" `CTGRY` = :CTGRY , ";
    $wlq--;
     } else {
    $qls .=" `CTGRY` = :CTGRY";
    }
 }

 if(!empty($_FILES['RutIm']['name'])) {
     if($wlq > 0){
    $qls .=" `RutIm` = :RutIm , ";
    $wlq--;
     } else {

    }
 }

 $qls .= " WHERE 'Id_Msg' = :ids";
 echo $qls;
 $stmt = $con->prepare($qls);
 $stmt->bindValue(':ids', $ids);

 if(isset($_POST['Title']) && !empty($_POST['Title'])) {
    $stmt->bindValue('Title', $_POST['Title']);
 }

 if(isset($_POST['Prelude']) && !empty($_POST['Prelude'])) {
    $stmt->bindValue('Prelude', $_POST['Prelude']);
 }

 if(isset($_POST['Text']) && !empty($_POST['Text'])) {
    $stmt->bindValue('Text', $_POST['Text']);
 }

 if(isset($_POST['NOMBR1']) && !empty($_POST['NOMBR1'])) {
    $stmt->bindValue('NOMBR1', $_POST['NOMBR1']);
 }

 if(isset($_POST['NOMBR2']) && !empty($_POST['NOMBR2'])) {
    $stmt->bindValue('NOMBR2', $_POST['NOMBR2']);
 }

 if(isset($_POST['NOMBR3']) && !empty($_POST['NOMBR3'])) {
    $stmt->bindValue('NOMBR3', $_POST['NOMBR3']);
 }

 if(isset($_POST['NOMBR4']) && !empty($_POST['NOMBR4'])) {
    $stmt->bindValue('NOMBR4', $_POST['NOMBR4']);
 }

 if(isset($_POST['REGIN']) && !empty($_POST['REGIN'])) {
    $stmt->bindValue('REGIN', $_POST['REGIN']);
 }

 if(isset($_POST['CTGRY']) && !empty($_POST['CTGRY'])) {
    $stmt->bindValue('CTGRY', $_POST['CTGRY']);
 }

 if(!empty($_FILES['RutIm']['name'])) {
    $carpeta = "images/";
    opendir($carpeta);
    $destiny = $carpeta.$_FILES['RutIm']['name'].".jpg";
    copy($_FILES['RutIm']['tmp_name'],$destiny);
    $skr=$_FILES['RutIm']['name'];
    $stmt->bindValue('RutIm', $skr);
 }
$stmt->execute();
?>

echo $qls output
UPDATE cmtmplo SET Title = :Title , REGIN = :REGIN , CTGRY = :CTGRY WHERE 'Id_Msg' = :ids

A: PHP PDO provides a good way of finding out what might be wrong with the query.
PDOStatement::execute() only returns true or false by default. It won't return any specific detail.
For detailed error information, you can use:
var_dump($con->errorInfo());

For more details, refer to the documentation page: http://php.net/manual/en/pdo.errorinfo.php

A: you need change all labels like 'Title' to ':Title':
 if(isset($_POST['Title']) && !empty($_POST['Title'])) {
    $stmt->bindValue(':Title', $_POST['Title']);
 }

....

and so on... all parameters you bind must start with :
so now we can see that you should change
$qls .= " WHERE 'Id_Msg' = :ids";

to
$qls .= " WHERE `Id_Msg` = :ids";

apostrophs to ticks


text:
Q: Import and Export on User Style Files I have a near philosophical question now.  I am not a LaTeX programmer, but a LaTeX end user (writer).  I have a collection of LaTeX style files used for a pretty fancy book written in LaTeX.  My style files sometimes depend on macros in my other style files, and are exporting macros.  I sometimes want to test them out by themselves in a minimal example, too.
Right now, my plan is to reorganize my style files as follows:
At the top of each style file, say a question.sty file, I first put the required imports
\ProvidesPackage{question}[2022/04/01]

%% imports
\usepackage{xcolor} %% standard TL

\ProvideDocumentEnvironment{ threecolumn }%% my own macro hack facility, from elsewhere
  { \begin{center}\color{red} begin threecolumn \end{center} }
  { \begin{center}\color{red} end threecolumn \end{center} }

Having a stub will allow me to test out this stylefile in a simple tex file by itself, even though in its fancier forms it will use the threecolumn environment from elsewhere.  Then, this would be followed by what this style file actually provides for quick reference without delving into the implementation details.
%% exports
\ProvideDocumentCommand{\question}{ O{red} m }{}

(edit --- david carlisel suggested rightly that the above should probably better be a \NewDocumentCommand)
This will be followed by longer documentation, a changelog, etc.  Sort of like a 'pod' (perl).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% question.sty
%%%
%%% this provides a nicely formatted question macro,
%%% with one argument blah blah blah
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

Finally, I have the actual implementation, typically messy and cobbled together magic from lots of help that I have received on tex.stackexchange over the years (half of which I do not understand, all of which I highly appreciate).
\RenewDocumentCommand{\question}{ O{red}m }{
    \begin{threecolumn}
         \textcolor{#1.} #2
    \end{threecolumn}
}

Any other macros than \question should probably have a '@' in them, and require \makeatletter.

*

*Is this a good plan?

*Is this reinventing the wheel or ignoring useful existing latex style facilities for end-users/writers like myself?

A: I see no advantage in having the \ProvideDocumenCommand it just makes things slower and is of dubious documentation value. It also completely masks package clashes with your package and existing code from other packages.
If your package intends to define a new \question command, then if you do the natural form
\NewDocumentCommand{\question}{ O{red}m }{% don't forget %
    \begin{onecolumn}%
         \textcolor{#1.} #2%
    \end{onecolumn}%
}

Then if you accidentally have loaded some other code into the document that has already defined this, you get an error and can adjust the package loading.
However your \Provide.. \Renew... combination will always silently over-ride the existing definition with no warning. It's like using \def and negates all the checking done by LaTeX's \New... definition forms


text:
Q: how to calculate a value of the last row with a new inserted value in mysql All
how to calculate a value of the last row with a  new inserted value in mysql
final_stock (2nd) row = final_stock(1st) row - out(2nd) row
i have a table
no   date         product_code   first_stock   in  out  final_stock
1    2018/01/18      A001          50          0   0      50 (last inserted)
2    2018/01/18      A001          0           0   35     15 <==== i want to achieve this

when I insert a new data (data no 2 ) and fill column "out" with 35, the "final_stock" column in 2nd row will have 15. how can I achieve that
this is the query
mysql_query("insert into flow_stock (date, product_code, first_stock, in, out, final_stock )
values('$date', '$code','','','$out',(select final_stock from flow_stock order by no desc limit 1) - ".$out.")");

need your help, the query doesn't calculate

A: DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table
(no INT NOT NULL AUTO_INCREMENT PRIMARY KEY
,date DATE NOT NULL
,product_code CHAR(4) NOT NULL
,first_stock INT NOT NULL
,`in` INT NOT NULL
,`out` INT NOT NULL
,final_stock INT NOT NULL
);

INSERT INTO my_table VALUES (1,'2018-01-18','A001',50,0,0,50);

SELECT * FROM my_table;
+----+------------+--------------+-------------+----+-----+-------------+
| no | date       | product_code | first_stock | in | out | final_stock |
+----+------------+--------------+-------------+----+-----+-------------+
|  1 | 2018-01-18 | A001         |          50 |  0 |   0 |          50 |
+----+------------+--------------+-------------+----+-----+-------------+

INSERT INTO my_table (date,product_code,first_stock,`in`,`out`,final_stock)
SELECT '2018-01-21'
     , 'A001'
     , 0
     , 0
     , 35
     , final_stock - 35
  FROM my_table
 WHERE product_code = 'A001'
 ORDER
    BY no DESC
 LIMIT 1;

Query OK, 1 row affected (0.04 sec)
Records: 1  Duplicates: 0  Warnings: 0

SELECT * FROM my_table;
+----+------------+--------------+-------------+----+-----+-------------+
| no | date       | product_code | first_stock | in | out | final_stock |
+----+------------+--------------+-------------+----+-----+-------------+
|  1 | 2018-01-18 | A001         |          50 |  0 |   0 |          50 |
|  2 | 2018-01-21 | A001         |           0 |  0 |  35 |          15 |
+----+------------+--------------+-------------+----+-----+-------------+


text:
Q: create virtual directory on Amazon Instance Alright,
So I have an AMI that I use for a beanstalk app. I started with the generic amazon instance it gives you, and then mounted an EBS volume on it. I then uploaded my webapp. What I wanted to do next was have some kind of virtual directory on the site /files that is accessible via the web and points to the mount location /mnt/Files . I tried
sudo ln -s /mnt/Files /home/webapp/files
But that didn't work. I don't have access to webapp folder, so I can't really dig around.
So my question here is two fold.
1) Is there a way to configure a virtual directory like that without modifying the vm itself.
2) If there isn't a way to do it that way, how would I go about making a virtual directory? I'm not even certain that webapp contains the server files etc.

A: I was searching in the wrong place. The place where I needed to make the symlink was in /var/www/html, then I could save it as an ami and then reload it.

A: It would be easier to use the .ebextensions mechanism to run commands at instance creation time rather than creating a custom AMI.
Something along the lines of:
commands:
   create_html_dir:
   command: mkdir /var/www/html


text:
Q: Hibernate acessing table in schema other than dbo results with Schema-validation: missing table I have a datasource that has two schemas: dbo and example.
I've created a table in dbo schema called A, and mapped it in hibernate:
@Entity
@Table(name = "A")
public class ATable {
    private Integer id;

    @Id
    @Column(name = "id")
    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }
}

It runs without any errors as expected, I then proceeded to move the table to example schema with the following statement (runs successfully):
alter schema example transfer dbo.A

And changed the hibernate class as well:
@Entity
@Table(name = "A", schema = "example")
public class ATable {
    private Integer id;

    @Id
    @Column(name = "id")
    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }
}

But upon running it, it throws the following exception, and exit the program.
INFO: HHH000262: Table not found: A
Exception in thread "main" org.hibernate.tool.schema.spi.SchemaManagementException: Schema-validation: missing table [A]
    at org.hibernate.tool.schema.internal.SchemaValidatorImpl.validateTable(SchemaValidatorImpl.java:130)
    at org.hibernate.tool.schema.internal.SchemaValidatorImpl.performValidation(SchemaValidatorImpl.java:100)
    at org.hibernate.tool.schema.internal.SchemaValidatorImpl.doValidation(SchemaValidatorImpl.java:65)
    at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:184)
    at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:65)
    at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:459)
    at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:465)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:711)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:727)
    at com.venditio.Application.main(Application.java:21)

I also tried using the following table annotation instead:
@Table(name = "example.A")

But it throws somewhat the same exception:
INFO: HHH000262: Table not found: example.A
Sep 22, 2017 3:53:36 PM org.hibernate.tool.schema.extract.internal.InformationExtractorJdbcDatabaseMetaDataImpl processGetTableResults
INFO: HHH000262: Table not found: example.A
Exception in thread "main" org.hibernate.tool.schema.spi.SchemaManagementException: Schema-validation: missing table [example.A]
    at org.hibernate.tool.schema.internal.SchemaValidatorImpl.validateTable(SchemaValidatorImpl.java:130)
    at org.hibernate.tool.schema.internal.SchemaValidatorImpl.performValidation(SchemaValidatorImpl.java:100)
    at org.hibernate.tool.schema.internal.SchemaValidatorImpl.doValidation(SchemaValidatorImpl.java:65)
    at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:184)
    at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:65)
    at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:459)
    at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:465)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:711)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:727)
    at com.venditio.Application.main(Application.java:21)

It seems that I need to somehow configure hibernate to support the extra schema, but don't understand how.
Application:
public class Application {
    private static SessionFactory sessionFactory;
    public static void main(String[] args) {
        Configuration configuration = new Configuration().configure();
        sessionFactory = configuration.buildSessionFactory();

        sessionFactory.openSession().close();
    }
}

And hibernate.cfg.xml
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <!--MSSQL-->
        <property name="hibernate.connection.url">jdbc:jtds:sqlserver://localhost:1433/d1</property>
        <property name="connection.driver_class">net.sourceforge.jtds.jdbc.Driver</property>

        <property name="hibernate.connection.username">a</property>
        <property name="hibernate.connection.password">1</property>
        <property name="dialect">org.hibernate.dialect.SQLServerDialect</property>

        <!--Global-->
        <property name="hibernate.connection.pool_size">10</property>
        <property name="show_sql">true</property>
        <property name="hibernate.hbm2ddl.auto">validate</property>
        <property name="hibernate.current_session_context_class">thread</property>

        <mapping class="com.a.A" />
    </session-factory>
</hibernate-configuration>

A: Turns out, removing the following line from hibernate.cfg.xml did the trick
<property name="hibernate.hbm2ddl.auto">validate</property>


text:
Q: How Do I globally apply CSS in eclipse I have made one CSS file for all fxml I have but I have no idea how to apply it to them.

I'm trying to apply bakery.css to all fxml file you see in the picture.
I have tried to put in the build path of the project but didn't work.
Is there a way to globally apply one CSS to all fxml files?


text:
Q: Interface between rdesktop and gocr I'm trying to integrate gocr to rdesktop.
To do it, I'm thinking to add code to ui_memblt routine. I have two methods:
a) Copy the screen changes (rects) to a shared memory readed by a "daemon" using gocr. My problem with it, I don't know the format of Pixmap, to copy its bytes to a shared memory area.
b) Using the XShm routines:
if(ximage==NULL)
 {
  ximage=XShmCreateImage(g_display, visual, 1, /* g_depth, */ XYPixmap, NULL, &shminfo, g_width, g_height);
  shminfo.shmid=shmget(IPC_PRIVATE,ximage->bytes_per_line*ximage->height, IPC_CREAT|0777);
  shminfo.shmaddr=ximage->data=shmat(shminfo.shmid,0,0);
  shminfo.readOnly=True;
  XShmAttach(g_display,&shminfo);
  printf("MIT-SHM: Shared memory KID=%d, at=%p\n",shminfo.shmid,shminfo.shmaddr);
}
XShmPutImage(g_display, g_wnd, g_gc, ximage, 0, 0, x, y, cx, cy, False);

When I executed this code, I'm receiving:
MIT-SHM: Shared memory KID=71827465, at=0xb6c25000
X Error of failed request:  BadMatch (invalid parameter attributes)
Major opcode of failed request:  130 (MIT-SHM)
Minor opcode of failed request:  3 (X_ShmPutImage)
Serial number of failed request:  78
Current serial number in output stream:  78

Any idea?
I'm trying to do a fast-copy (or sharing) between rdesktop and gocr "daemon".


text:
Q: Harvey-Newbold test (2000) in R I want to estimate the best nested model out-of sample and for that purpose, I will implement Harvey-Newbold test. However, I cannot find the respective test in any package.
Can anyone help me?
If this test is not implemented yet, do you have any alternative that meets the goal of estimating the best nested model out-of sample and is possible to implement in r?
Thanks in advance.


text:
Q: tcpdump: filtering out localhost, packets show up anyway? I'm trying to use tcpdump to explore what on my computer talks with whom on the world wide web.
I've came this far as of yet:
lan_hosts="(hosts || to || exclude)"
local_hosts="(127.0.0.1 || ips_of_my_nics || localhost || local_hostname)"
excused_local_ports="(ssh || https || domain || $(netstat -ap | egrep -h '/(processes|I_dont|want|to_see|traffic_of)' | tr -s ' ' | cut -d ' ' -f 4 | rev | cut -d ':' -sf 1 | rev | sort | sed ':a; N; $!ba; s/\n/ \|\| /g'))"
tcpdump -vi any "ip && ! icmp && ! arp && (src ! $local_hosts || dst ! $local_hosts) && (src $local_hosts || dst $local_hosts) && (src ! $local_hosts || src port ! $excused_local_ports) && (dst ! $local_hosts || dst port ! $excused_local_ports) && host ! $lan_hosts"

Now the reason I'm posting this here as question: I don't understand why / how these packets still show up in the output:
tcpdump: listening on any, link-type LINUX_SLL (Linux cooked v1), capture size 262144 bytes
14:49:30.660109 IP (tos 0x0, ttl 64, id 23067, offset 0, flags [DF], proto UDP (17), length 71)
    localhost.38976 > localhost.domain: 26002+ [1au] A? lan_host.lan. (43)
14:49:30.686174 IP (tos 0x0, ttl 64, id 23110, offset 0, flags [DF], proto UDP (17), length 80)
    localhost.47181 > localhost.domain: 45895+ [1au] PTR? some_ip.in-addr.arpa. (52)
14:49:30.686219 IP (tos 0x0, ttl 64, id 2440, offset 0, flags [DF], proto UDP (17), length 103)
    localhost.domain > localhost.47181: 45895 1/0/1 some_ip.in-addr.arpa. PTR localhost. (75)

I thought that the segment (src ! $local_hosts || dst ! $local_hosts) of my filter declaration, which is only concatenated with && logic to other filter parts should exclude those? And even if I didn't have that part in the filter, they should again be excluded because of the inclusion of domain in my excused_local_ports variable.
Let's unpack the filter declaration a bit and try to explain what I wanted to achieve with each part:

*

*ip -> only look at ipv4 packets, since this machine doesn't have an ipv6 path to the internet I am not concerned with ipv6 here.

*! icmp -> don't care about ping requests / replies and other icmp routing metadata.

*! arp -> filter out adress resolution protocol packets

*(src ! $local_hosts || dst ! $local_hosts) -> hide packets of the localhost talking to itself

*(src $local_hosts || dst $local_hosts) -> hide broadcasts from other hosts

*(src ! $local_hosts || src port ! $excused_local_ports) -> hide packets my host has sent from one of the ports of the programs I don't want to look at right now.

*(dst ! $local_hosts || dst port ! $excused_local_ports) -> hide packets my host has received on one of the ports of the programs I don't want to look at right now.

*(host ! $lan_hosts) -> hide communication with the defined hosts


text:
Q: No parent in style in android-support-v7-appcompat i imported support-v7-appcompat library, and during build process i got following issue:
Error:(380, 5) String types not allowed (at 'blue' with value '').
app\build\intermediates\exploded-aar\com.android.support\appcompat-v7\23.1.1\res\values\values.xml

Line (380,5):
<style name="Base.TextAppearance.AppCompat.SearchResult" parent="">
    <item name="android:textStyle">normal</item>
    <item name="android:textColor">?android:textColorPrimary</item>
    <item name="android:textColorHint">?android:textColorHint</item>
</style>

I am currently using 23.1.1 version of support library. This issue comes up everytime i build the app. I have tried cleaning the code.
build.gradle:
apply plugin: 'com.android.model.application'
model {
    android {
        compileSdkVersion 'Google Inc.:Google APIs:23'
        buildToolsVersion "23.0.2"

        defaultConfig.with {
            applicationId "com.ms.sensors"
            minSdkVersion.apiLevel 13
            targetSdkVersion.apiLevel 23
            versionCode 1
            versionName "1.0"
        }

        compileOptions.with {
            sourceCompatibility = JavaVersion.VERSION_1_7
            targetCompatibility = JavaVersion.VERSION_1_7
        }

        buildTypes {
            release {
                minifyEnabled = false
                proguardFiles.add(file('proguard-rules.txt'))
            }
        }
    }

    android.ndk {
        moduleName = "sensorgraph"
        cppFlags.add("-Werror")
        ldLibs.addAll(["log", "GLESv2", "android"])
        stl = "c++_static"
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:23.1.1'
    compile 'com.android.support:support-v4:23.1.1'
}

How to fix this issue?

A: Try changing:
compileSdkVersion 'Google Inc.:Google APIs:23'

with:
compileSdkVersion 23


text:
Q: How to restrict a user account to a specific time period
Possible Duplicate:
How do I restrict my kids' computing time?

I'm using 12.04 and would like to make one user account open for use 24/7 and one account only available from 8:00am to 12:00am so when the user attempts to login after midnight , they are denied access .


text:
Q: Start activity from service android 10 I am trying to create a locker application to show pin view when the user enters to defended application. I created a service that runs and tracks the current foreground application. However, on devices with android version 10 activity is not starting from my service. I know that from android 10 there are restrictions to start an activity from the background, however, there are exceptions either. The activity can start from the background when the application is in the foreground, but it won't help in my case. So the question is how can I start the activity from service to show pin view?
P.s: I tried it with window manager but again in higher android versions there is an annoying notification that can open settings do dismiss overlay permission. Also, I saw a working "app locker" application in the play store, so I believe there is a way.

A: From android 10 foreground service will work only if u start the service while the app is in foreground. If your app is in background you will need background location permission which has to be requested separate after you gain permission for coarse and fine location. Also if your app is in testing mode and not in Play Store and u update your device to android 10 a fresh install of the app is needed.
There is no point in using a foreground service if u want to start that service from background. Just get background location and stop using foreground service.


text:
Q: How to change view of expandable list view children when parent is collapsed in Android? I am implementing a selection mode in ExpandableListView. The selection toggles when I click a child. I have a CheckBox in each parent, from which I want to control the selection of all the children at once.
My problem is that when the parent is collapsed and I click its CheckBox, the app crashes due to null pointer exception because when I try to change the selection of the children, I can't find the children and get null. But everything works fine when the parent is expanded.
So, what is a good approach to tackle such kind of problem?

A: I solved by adding some lines of code without changing the previous code, so this answer may be helpful for someone who doesn't want to rewrite the code with a different approach.
In the calling Fragment or Activity, where the Adapter is being set, add:
private val isMyGroupExpanded = SparseBooleanArray()

val MyAdapterEV = AdapterEV(/* params */) { isChecked, groupPosition ->
    changeSelection(isChecked, groupPosition)
}
// record which groups are expanded and which are not
MyAdapterEV.setOnGroupExpandListener { i -> isMyGroupExpanded.put(i, true) }
MyAdapterEV.setOnGroupCollapseListener { i -> isMyGroupExpanded.put(i, false) }

// and where changing the selection of child
private fun changeSelection(isChecked: Boolean, groupPosition: Int) {
    if (isMyGroupExpanded.get(groupPosition, false)) {
        /* change only if the group is expanded */
    }
}

So, the children of the collapsed group are not affected, but they are needed to be changed when the group expands, for that, add some lines of code in the Adapter:
private val isGroupChecked = SparseBooleanArray()

// inside override fun getGroupView(...
MyCheckBoxView.setOnCheckedChangeListener { _, isChecked ->
    onCheckedChangeListener(isChecked, groupPosition)
    isGroupChecked.put(groupPosition, isChecked)
}

// inside override fun getChildView(...
if (isGroupChecked.contains(groupPosition)) {
    myView.visibility = if (isGroupChecked.get(groupPosition)) View.VISIBLE else View.INVISIBLE
}


text:
Q: Unable to deploy the app on Moto360 I am trying to deploy wear portion of the app on Moto360 from Android Studio 0.8.9. At this point it is just a boiler plate code generated by Studio.
I am getting the following messages
Waiting for device.
Target device: motorola-moto_360-localhost:4444

Uploading file
    local path: /<redacted>/wear/build/outputs/apk/wear-debug.apk
    remote path: /data/local/tmp/com.[redacted]
Installing com.[redacted]

DEVICE SHELL COMMAND: pm install -r "/data/local/tmp/com.[redacted]"
CANNOT LINK EXECUTABLE: could not load library "libandroid_runtime.so" needed by "app_process"; caused by cannot locate symbol "uloc_toLcnguageTag_51" referenced by "libandroid_runtime.so"...

Launching application: com.[redacted]/com.[redacted].WearActivity.
DEVICE SHELL COMMAND: am start -n "com.[redacted]/com.[redacted].WearActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
CANNOT LINK EXECUTABLE: could not load library "libandroid_runtime.so" needed by "app_process"; caused by cannot locate symbol "uloc_toLcnguageTag_51" referenced by "libandroid_runtime.so"...

Moto360 is running 4.4W.1 Build KGW42R. Needless to say it deploys fine on wear emulator. I am wondering if the latest Moto360 system update has anything to do with it.

A: Well, looks like latest SDK updates from 10/17/2014 for Android studio fixed the issue.


text:
Q: Number of solutions to an equation using the inclusion-exclusion principle
Possible Duplicate:
Inclusion-exclusion principle: Number of integer solutions to equations

This is a problem that I have had much trouble with. If you attempt in helping me with this, please explain step by step and present your formulas. It will be greatly appreciated.
Find the number of integer solutions to:
$$x_1+x_2+x_3+x_4=25$$
satisfying:
$$\begin{array}{rcccl}
0&\leq &x_1 &\leq& 7\\
3 &\leq & x_2 & \leq &5\\
4 &\leq & x_3 & \leq & 8\\
-2 & \leq& x_4 & \leq & 2.
\end{array}$$
Please emphasize on how to use the inclusion exclusion principle.
Thanks.


text:
Q: Measure rpm of a DC motor using two timers/counter and IR sensor (atmega 328p) I'm trying to measure the speed of a DC motor. I have an IR speed sensor connected to the T1 pin(PD5) of an ATMega 328p. My idea is when there is a change from LOW to HIGH, a counter is incremented and for this I'm using TIMER2 to create a 1 second interrupt and TIMER1 to count the pulses.
First problem is that the TCNT1 is giving me random values even if I pass only one time in the sensor (counts from 0 to 200).
Second problem is that its counting both changes from LOW to HIGH and HIGH to LOW.
My sensor is www.botnroll.com/pt/sensores/957-motor-speed-sensor-module.html
Here is my current code:
#include <avr/io.h>
#include <avr/interrupt.h>

volatile unsigned int overflow;
volatile unsigned int timer_counts = 0;

void conf_timer2()
{
    //prescaler = 256
    TCCR2B |= (1 << CS22)|(1 << CS21);

    TCNT2 = 0;
    // overflow interrupt
    TIMSK2 |= (1 << TOIE2);

    overflow = 0;
}

void config_timer1()
{
    TCCR1B |= (1<<CS10) | (1<<CS11) | (1<<CS12);    //rising edge
    TIMSK1 |= (1<<TOIE1);   //enable overflow interrupt

    DDRD &= ~(1 << DDB5);
    //PORTD |= (1 << PORTD5);
}

ISR(TIMER2_OVF_vect)
{
    overflow++;
}

ISR(TIMER1_OVF_vect)
{
    //overflow1++;
    //no need since it will never reach 65536 in 1 sec
}

int main()
{
    sei();
    config_timer1();
    conf_timer2();
    char aux2[10];
    char aux1[10];

    unsigned int rpm;

    while(1)
    {
    if(overflow >= 152) // for 1 sec
    {
        if(TCNT2 > 149) //for 1 sec
        {
            timer_counts = TCNT1;
            rpm = timer_counts * 60;

            itoa(rpm, aux2, 10);
            itoa(timer_counts, aux1, 10);
            USART_putstring("Rot. per sec: "); //print values
            USART_putstring(aux1);
            USART_putstring("\n");
            USART_putstring("Rot. per min = ");
            USART_putstring(aux2);
            USART_putstring("\n");

            TCNT1 = 0;
            overflow = 0;
            rpm = 0;
        }
    }
}
return 0;

}
Any1 help is valuable!

A: Putting the software listing aside for the moment, it makes me wonder if your opto-sensor circuit is producing lots of fast-switching edges as it the photo-transistor beam is broken or made. Can you look closely at those edges on an oscilloscope.
Looking at the sensor, there's no schematic given for it but it says it uses a LM393 dual comparator and I can see 6 resistors. That means they could have a Schmitt trigger on the photo-transistor output to prevent the output multi-switching with slow beam interruptions, when the photo-transistor output is going on or off slowly.
Also, LM393 is an open-collector part but it's almost a given that there's an output pull-up resistor on board there. Almost...but do try putting a 4K7 pull-up between the board output and the supply rail (3V3 I imagine), see if it improves.


text: Q: wowza media server 2 license key Can Wowza Media Server 2 license keys be used on multiple machines? If not where do I get a new license key for this version of Wowza? The Wowza website only provides keys for Wowza 4, as far as I can tell.


text:
Q: Encoding arraybuffer to base64 not giving proper output for larger files I am trying to convert arraybuffer to base64 which works for smaller file, but when U uploaded a file of size 10MB it is not giving me the desired base64 output

var AttachmentsArray = [];
$("#file-attach").change(function() {
  getSelectedFiles($('#file-attach'), AttachmentsArray);
  //console.log(AttachmentsArray);
});

function getSelectedFiles(fileId, data) {
  for (var j = 0; j < fileId[0].files.length; j++) {
    readTheFile(fileId[0].files[j], data);
  }
}

function readTheFile(file, data) {
  var fileReader = new FileReader();
  fileReader.filename = file.name;
  fileReader.size = file.size;
  fileReader.onload = function(e) {
    var bits = e.target.result;
    var Object = {
      FileName: e.target.filename,
      Size: e.target.size,
      length: bits.length,
      DocumentData: _arrayBufferToBase64(bits)
    };
    data.push(Object);
    console.log(Object);
  };
  fileReader.readAsArrayBuffer(file);
}

function _arrayBufferToBase64(buffer) {
  var base64 = ''
  var bytes = new Uint8Array(buffer);
  var byteLength = bytes.byteLength
  var byteRemainder = byteLength % 3
  var mainLength = byteLength - byteRemainder
  var a, b, c, d
  var chunk
  var encodings = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
  console.log(mainLength);
  // Main loop deals with bytes in chunks of 3
  for (var i = 0; i < mainLength; i = i + 3) {
    // Combine the three bytes into a single integer
    chunk = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2]

    // Use bitmasks to extract 6-bit segments from the triplet
    a = (chunk & 16515072) >> 18 // 16515072 = (2^6 - 1) << 18
    b = (chunk & 258048) >> 12 // 258048   = (2^6 - 1) << 12
    c = (chunk & 4032) >> 6 // 4032     = (2^6 - 1) << 6
    d = chunk & 63 // 63       = 2^6 - 1

    // Convert the raw binary segments to the appropriate ASCII encoding
    base64 += encodings[a] + encodings[b] + encodings[c] + encodings[d]
  }

  // Deal with the remaining bytes and padding
  if (byteRemainder == 1) {
    chunk = bytes[mainLength]

    a = (chunk & 252) >> 2 // 252 = (2^6 - 1) << 2

    // Set the 4 least significant bits to zero
    b = (chunk & 3) << 4 // 3   = 2^2 - 1

    base64 += encodings[a] + encodings[b] + '=='
  } else if (byteRemainder == 2) {
    chunk = (bytes[mainLength] << 8) | bytes[mainLength + 1]

    a = (chunk & 64512) >> 10 // 64512 = (2^6 - 1) << 10
    b = (chunk & 1008) >> 4 // 1008  = (2^6 - 1) << 4

    // Set the 2 least significant bits to zero
    c = (chunk & 15) << 2 // 15    = 2^4 - 1

    base64 += encodings[a] + encodings[b] + encodings[c] + '='
  }

  return base64
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="file" id="file-attach" multiple="multiple" />

This is the output when I tried for the image of 62KB

When I tried to upload a PDF which is of size 10MB it didn't give any

I have a limitation where user can upload up to 40MB, so can I get the working code to convert the desired to base64. This it the code I used
https://gist.github.com/jonleighton/958841


text:
Q: Is the integral operator with continuous kernel from $H^{-\frac 1 2}(\partial\Omega)$ to $H^{\frac 1 2}(\partial\Omega)$ a compact operator? For a bounded domain $\Omega$ with $C^1$ boundary, define a integral operator $A$ with a continuous kernel $k$ satisfies
$$
A f (x) = \int_{\partial\Omega} k(x,y)f(y)~{\rm d}y \quad {\rm for }~x\in\partial\Omega.
$$
Here $k(x,y)$ is continuous on $\partial\Omega \times \partial\Omega$.
I know $A:L^2(\partial\Omega) \rightarrow L^2(\partial\Omega)$ is compact. Then is $A:H^{-\frac 1 2}(\partial\Omega) \rightarrow H^{\frac 1 2}(\partial\Omega)$ still compact?


text:
Q: Form validation by country value I have a query form with a country list. Mobile number and e-mail validation are working fine when the country India is selected, but when the user selects another country, I need mobile number validation off. Here is the code for validation:

A: If I understand correct that you don't want to check mobile no when country is not India then I assumed your country is a dropdown field with id "country" then you can do following:
if($('#country option:selected').val() == 'india')
{
        var phoneNumberPattern = /^[0-9]{10}$/;
        if(!phoneNumberPattern.test(enqMobileNo))
        {
            $("#returnmessage").append("Enter your 10 digits mobile no only.");
            return false;
        }
}

Please update id selector and value accordingly


text:
Q: Angular Dynamic form I do not understand what is happening.
First I am entered 1111 to 5555 number. Total 5 records then I have delete 3333 number record after that I have clicked on Add Target button It show me https://i.stack.imgur.com/6e4dc.png where 5555 record gone but it exist in targetModel. When I debug the variable {{targetModel | json }}.

Add the few records then delete from middle record then click on add
  button. It show different result.

Please tell me where I am doing wrong.
HTML:
<form #addTargetForm="ngForm">

                <input  maxlength="50" placeholder="Enter target name here"
                        name="name_{{i}}" [(ngModel)]="target.Name" required>
                0" style="color:black"
                      (click)="removeTarget1(i)">remove

            <button class="btn sm mat-btn-custom w_icon btn-outline"
                 (click)="addTarget1()" >

                <mat-icon>add</mat-icon>
            Add Target
            </button>

</form>

TS:
    targetModel: any;

    constructor() {
            this.targetModel=[{Name:""}];
    }

    addTarget1() {
          let target={Name:""};
          this.targetModel.push(target);
    }

    removeTarget1(target) {
          this.targetModel.splice(target, 1)
    }

ScreenShots

ScreenShot1 :  https://i.stack.imgur.com/dP1QF.png
ScreenShot2 :  https://i.stack.imgur.com/BIUcQ.png
ScreenShot3 :  https://i.stack.imgur.com/6e4dc.png


text:
Q: Finding Numpy array content with gdb I am trying to debug a python script with a c++ extension that takes a numpy array as argument. The numpy array is called times
times = np.arange(0.0,5.0)
result = f(times)

This is an input in a C++ function that takes a PyObject*
f(PyObject* times)

is a C++ function (it goes via Boost.Python)
I am trying to debug into this using gdb, but I can't seem to find the data of times. See my output below. I suspect it gets an empty array (as ob_size =0), but I am not sure as I am not very experienced with the C++ underlyings of numpy arrays.
Any thoughts,
Mike
GDB debugging session
(gdb) p times
$21 = (PyObject *) 0x7ffff2c9b620
(gdb) p *$21
$22 = {ob_refcnt = 2, ob_type = 0x7ffff5518a80 <PyArray_Type>}
(gdb) p *$22.ob_type
$23 = {ob_refcnt = 190, ob_type = 0x91f8e0 <PyType_Type>, ob_size = 0,
tp_name = 0x7ffff52d5566 "numpy.ndarray", tp_basicsize = 80, tp_itemsize = 0,
tp_dealloc = 0x7ffff51d35b0 <array_dealloc>, tp_print = 0x0, tp_getattr = 0x0, tp_setattr = 0x0,
tp_compare = 0x0, tp_repr = 0x7ffff51d3810 <array_repr>,
tp_as_number = 0x7ffff551fc40 <array_as_number>, tp_as_sequence = 0x7ffff551fd80    <array_as_sequence>,
tp_as_mapping = 0x7ffff551d570 <array_as_mapping>, tp_hash = 0x0, tp_call = 0x0,
tp_str = 0x7ffff51d37a0 <array_str>, tp_getattro = 0x442fef <PyObject_GenericGetAttr>,
tp_setattro = 0x4272ff <PyObject_GenericSetAttr>, tp_as_buffer = 0x7ffff551b920 <array_as_buffer>,
tp_flags = 2233851,
tp_doc = 0xbf2814 "ndarray(shape, dtype=float, buffer=None, offset=0,\n", ' ' <repeats 12 times>, "strides=None, order=None)\n\n    An array object represents a multidimensional, homogeneous array\n    of fixed-size items.  An associated d"..., tp_traverse = 0x0, tp_clear = 0x0,
tp_richcompare = 0x7ffff51d4750 <array_richcompare>, tp_weaklistoffset = 72,
tp_iter = 0x7ffff51d3760 <array_iter>, tp_iternext = 0x0, tp_methods = 0x7ffff551da00 <array_methods>,
tp_members = 0x0, tp_getset = 0x7ffff551c8e0 <array_getsetlist>,
tp_base = 0x9175e0 <PyBaseObject_Type>, tp_dict = 0x7ffff7e83a28, tp_descr_get = 0x0,
tp_descr_set = 0x0, tp_dictoffset = 0, tp_init = 0x5112d0, tp_alloc = 0x7ffff51d3050 <array_alloc>,
tp_new = 0x7ffff51d4d50 <array_new>, tp_free = 0x7ffff51d3040 <array_free>, tp_is_gc = 0x0,
tp_bases = 0x7ffff7e82a10, tp_mro = 0x7ffff7e8bab8, tp_cache = 0x0, tp_subclasses = 0x7ffff4cc2cf8,
tp_weaklist = 0x7ffff7e89100, tp_del = 0x0, tp_version_tag = 0}