text:
Q: How do I create a TableLayout that fills the parent and has rows with equal height? I want to create a TableLayout that fills it's parent where every row has equal height. What do I have to do to get rows with equal height?

A: You can use layout_weight attribute for the TableRow elements in your layout. This will distribute the height equally (if you set your weights to be the same) over the parent height. First, set the parent android:weightSum="1" and then make sure all the weights of individual rows add up to 1.
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/tableLayout1"
    android:weightSum="1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <!-- Row 1 -->
    <TableRow
        android:id="@+id/tableRow1"
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:layout_weight="0.5"
        android:padding="5dp" >

        <!-- Your columns here... -->

    </TableRow>
<!-- Row 2 -->
<TableRow
        android:id="@+id/tableRow2"
        android:layout_weight="0.5"
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:padding="5dp" >
     <!-- Your columns here... -->
    </TableRow>
</TableLayout>

I hope this helps. Please give it a try and let me know if this is what you are looking for.

A: try this:
 In your layout
 <TableLayout
        android:id="@+id/sub_cat_layout"
        android:layout_width="match_parent"
        android:layout_below="@+id/subcat_headerlayout"
        android:layout_height="fill_parent"
        android:orientation="vertical"
        android:padding="0dp"
      >
     </TableLayout>

  InActivity
  TableLayout SubCAtLyt = (TableLayout)findViewById(R.id.sub_cat_layout);

   View v1 = null;
        LinearLayout linear_pmain = new LinearLayout(getActivity());
        linear_pmain.setOrientation(LinearLayout.HORIZONTAL);
        LayoutInflater vii = (LayoutInflater)  getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);

         TableRow tblRow = new TableRow(getActivity());
             tblRow.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
           arrBookDetails = db.Book( subCatid);
            int catAllLength = arrCatAllBookDetails.size();

           for (int j = 0; j < catAllLength; j++) {

          List<String> lBookDetails = arrBookDetails.get(j);
            //Row value layout
         String book = lBookDetails.get(10);
            v1 = vii.inflate(R.layout.sub_bottomthubnail, null);

                TextView txt = (TextView) v1.findViewById(R.id.txtg1);
                txt.setText( book);
                txt.setTypeface(tface, Typeface.NORMAL);
                 tblRow.addView(v1, j);
    }
        SubCAtLyt.addView(tblRow);


text:
Q: Code printing unexpected results For some reason, Mercury and Venus print Infinity in the weight field. Can anyone see the problem? Does this code work for you guys? All the other planets seem to work fine. Thanks in advance!
import java.util.Scanner;

public class Weight
{

    static double getGravity(String name) throws IOException
    {

        String[] names = {"Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune", "Pluto"};
        double[] radii = {2439.7, 6051.9, 6378, 3402.5, 71492, 60270, 25562, 24774, 1195};
        double[] masses = {3.3022 * Math.pow(10,23), 4.8685 * Math.pow(10,24), 5.9736 * Math.pow(10,24), 6.4185 * Math.pow(10,23), 1.8986 * Math.pow(10,27), 5.6846 * Math.pow(10,26), 8.6810 * Math.pow(10,25), 1.0243 * Math.pow(10,26), 1.312 * Math.pow(10,22)};
        int i = java.util.Arrays.asList(names).indexOf(name);

        return 6.67 * Math.pow(10, -11) * masses[i] / Math.pow(radii[i]*1000, 2);

    }

    static double convertWeight(double originalWeight, double currentGravity, double newGravity)
    {
        return originalWeight * (newGravity / currentGravity);
    }

    static void printResults(String name, double gravity, double weight)
    {
        System.out.printf("%-10s %-8.1f %-8.1f\r\n", name, gravity, weight);
    }

    public static void main(String[] args) throws IOException
    {

        Scanner in;
        System.out.print("Enter your weight in lbs: ");
        in = new Scanner(System.in);
        double earthWeight = in.nextDouble();

        String[] names = {"Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune", "Pluto"};
        //PLUTO IS NOT A PLANET!

        double[] gravity = new double[names.length];
        double[] weight = new double[names.length];
        System.out.printf("%-10s %-8s %-8s\r\n============================================\r\n", "Planet", "Gravity", "Weight (lbs) ");
        for(int i=0; i<gravity.length; i++)
        {
            gravity[i] = getGravity(names[i]);
            weight[i] = convertWeight(earthWeight, gravity[2], gravity[i]);
            printResults(names[i], gravity[i], weight[i]);
        }

    }
}

A: gravity[2] has to be set before looping or you divide by 0 until Earth.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Window based averages based on ranges within another table I have a table that has positions like so:
create or replace table data (
  pos int not null,
  val float not null,
  constraint data_pk primary key (pos)
);

And, a ranges type table like so:
create or replace table ranges (
  label varchar(32) not null,
  left int not null,
  right int not null,
  constraint ranges_pk primary key (label)
);

with ranges like
        ('alpha', 11, 13),
        ('bravo', 11, 14),
        ('charlie', 11, 15),
        ('echo', 12, 18),
        ('delta', 12, 19),
        ('foxtrot', 13, 20)

for each label, I need to lookup every possible 3 subrange within the "data" table, take these 3 subrange averages, and then average them...
I couldn't think of a good way to describe what I'm after, so I thought I'd show what I'd expect for 'charlie':
The results for charlie in the select should be:
    ('charlie', 40.111), -- avg(avg(data[pos=11], data[pos=12], data[pos=13]), avg(data[pos=12], data[pos=13], data[pos=14]), avg(data[pos=13], data[pos=14], data[pos=15]))
                         -- -> avg(avg(31, 37, 41), avg(37, 41, 43), avg(41, 43, 47))
                         -- -> avg(36.333, 40.333, 43.667) -> 40.111

(for data like)
insert into data (pos, val) values
    (1, 2), (2, 3), (3, 5), (4, 7), (5, 11), (6, 13), (7, 17), (8, 19),
    (9, 23), (10, 29), (11, 31), (12, 37), (13, 41), (14, 43), (15, 47), (16, 53),
    (17, 59), (18, 61), (19, 67), (20, 71), (21, 73), (22, 79), (23, 83), (24, 89),
    (25, 97), (26, 101), (27, 103), (28, 107), (29, 109), (30, 113), (31, 127), (32, 131),
    (33, 137), (34, 139), (35, 149), (36, 151), (37, 157), (38, 163), (39, 167), (40, 173),
    (41, 179), (42, 181), (43, 191), (44, 193), (45, 197), (46, 199), (47, 211), (48, 223),
    (49, 227), (50, 229), (51, 233), (52, 239), (53, 241), (54, 251);

Is there a way to do this within Snowflake SQL? Or must I resort to python to do this? If it helps I made a gist with more data..
Thanks!

A:
Is there a way to do this within Snowflake SQL? Or must I resort to python to do this?

SQL language is expressive enough to handle such case.
Key point here is to use windowed average with windows size of 3 and then average moving averages:
WITH cte AS (
 SELECT r.label, r.left, r.right, d.val,
        AVG(d.val) OVER(PARTITION BY r.label ORDER BY d.pos ROWS
                        BETWEEN 2 PRECEDING AND CURRENT ROW) AS r
 FROM ranges r
 JOIN data d
   ON d.pos BETWEEN r.left AND r.right
  QUALIFY ROW_NUMBER() OVER(PARTITION BY r.label ORDER BY d.pos) > 2
)
SELECT label, AVG(r) AS output
FROM cte
GROUP BY label
ORDER BY label;

Output:

Intermediate step to ilustrate:
WITH cte AS (
 SELECT r.label, r.left, r.right, d.val,
        AVG(d.val) OVER(PARTITION BY r.label ORDER BY d.pos
                        ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) AS r
 FROM ranges r
 JOIN data d
   ON d.pos BETWEEN r.left AND r.right
  QUALIFY ROW_NUMBER() OVER(PARTITION BY r.label ORDER BY d.pos) > 2
)
SELECT *
FROM cte
ORDER BY label, r;

Output:

A: Here is a step by step answer:
WITH data(pos, val) AS (
    SELECT * FROM VALUES
      (1, 2), (2, 3), (3, 5), (4, 7), (5, 11), (6, 13), (7, 17), (8, 19),
      (9, 23), (10, 29), (11, 31), (12, 37), (13, 41), (14, 43), (15, 47), (16, 53),
      (17, 59), (18, 61), (19, 67), (20, 71), (21, 73), (22, 79), (23, 83), (24, 89),
      (25, 97), (26, 101), (27, 103), (28, 107), (29, 109), (30, 113), (31, 127), (32, 131),
      (33, 137), (34, 139), (35, 149), (36, 151), (37, 157), (38, 163), (39, 167), (40, 173),
      (41, 179), (42, 181), (43, 191), (44, 193), (45, 197), (46, 199), (47, 211), (48, 223),
      (49, 227), (50, 229), (51, 233), (52, 239), (53, 241), (54, 251)
), codes(name,s_val, e_val) AS (
     SELECT * FROM VALUES
        ('alpha', 11, 13),
        ('bravo', 11, 14),
        ('charlie', 11, 15),
        ('echo', 12, 18),
        ('delta', 12, 19),
        ('foxtrot', 13, 20)
), ranges as (
    SELECT row_number() over (order by null)-1 as seq
    FROM table(generator(rowcount => 200))
), boost_codes AS (
    select c.name
      ,c.s_val + r.seq + 0 as b1
      ,c.s_val + r.seq + 2 as b3
    from codes as c
    join ranges as r
      ON r.seq <= (e_val - s_val - 2)
), almost_there AS (
    select
       bc.name
       ,avg(d.val) as partial
    from boost_codes as bc
    join data as d ON d.pos between bc.b1 and bc.b3
    GROUP BY 1, bc.b1
)
SELECT name
    ,round(avg(partial),3) as output
FROM almost_there
GROUP BY 1
ORDER BY 1;

which gives:

NAME
OUTPUT

alpha
36.333

bravo
38.333

charlie
40.111

delta
50.778

echo
48.467

foxtrot
55.111


text:
Q: How to secure Angular & Spring Application We have developed one application with Angular 5 as frontend and Spring Boot as backend.
First page is the login page, which invokes a rest api to authenticate with LDAP at backend.
We are using OAuth implementation with JWT. So when the user logins, the credentials username and password are via. POST request in body to the rest api for auth.
In headers we are sending clientId and secret for Oauth.
The issue is that the credentials are getting exposed in the request and can be seen in the browsers developer options.
I need a way to mask/encrypt these credentials.

A: You can use the cypto-js library for encrypting your password from your angular application.
Installation :
npm install crypto-js

Usage :
var AES = require("crypto-js/aes");
var SHA256 = require("crypto-js/sha256");
var MD5 = require("crypto-js/md5");
console.log(AES("YOUR PASSWORD"));//AES ENCRYPTION
console.log(SHA256("YOUR PASSWORD"));//SHA256 ENCRYPTION
console.log(MD5("YOUR PASSWORD"));//MD5 ENCRYPTION

Thanks hope this helps!

A: Well, the password being exposed in the request in the network tab is quite "normal" - Your API needs to read the password after all and check if it is valid.
There are still a couple of things you can do:

*

*You definitely should communicate over https and can use several additional security headers as well

*You can Hash the password in the browser side and treat the hash as it would be the user password

*

*Changing the hash function in the client is nearly impossible since it requires all users to re-new their password

*You can't do any API side password strength verification

*You can encrypt the password in the browser side and decrypt it in the API.

*

*You still should hash the password in your API, and do NOT store the encrypted password from the client (since the encryption is visible in the source code to the user)

I actually don't like the Hash variant, since you loose the control over password strength, and somebody theoretically can use the API and create a user with password "Test" or something similar.
The second approach sure does help you so it is not visible in the Network tab. But just be aware that if someone really cares he can lookup the encryption in your source code and still decrypt it in the request if he has access to it


text:
Q: Proper way to mock MIMEMessage? I want to actually verify the fields set on the message, like the body, subject, from, etc…  I've tried doing an argument captor as well which didn't work and when I debug the code, the message is always showing null fields when it gets the javaMailSender.send(message) line.
Are there best practices in mocking MIMEMessage?
//EmailService.java

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

@Slf4j
public class EmailService {
    private JavaMailSender javaMailSender;

    @Autowired
    public EmailService(JavaMailSender javaMailSender) {
        this.javaMailSender = javaMailSender;
    }

    public void sendEmail() {
        MimeMessage message = javaMailSender.createMimeMessage();
        String body = "<html>\n" +
            "<p> This the body </p>\n" +
            "<br>\n";
        try {
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(message, true);
            mimeMessageHelper.setSubject("subject");
            mimeMessageHelper.setTo("stack@overflow.com");
            mimeMessageHelper.setFrom("overflow@stack.com");
            mimeMessageHelper.setText(body, true);

            javaMailSender.send(message);

        } catch (MessagingException e) {
            log.error("error");
        }`enter code here`
    }
}

Below is the test
//EmailServiceTest.java

import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.springframework.mail.javamail.JavaMailSender;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.IOException;

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.*;
import static org.mockito.MockitoAnnotations.initMocks;

public class EmailServiceTest {
    private EmailService emailService;

    @Mock
    private JavaMailSender javaMailSender;

    @Mock
    private MimeMessage message;

    @Before
    public void setUp() throws IOException {
        initMocks(this);

        emailService = new EmailService(javaMailSender);
    }

    @Test
    public void sendEmail_sendsEmailWithCorrectContent() throws MessagingException {
        ArgumentCaptor<MimeMessage> mimeMessageArgumentCaptor = ArgumentCaptor.forClass(MimeMessage.class);
        when(javaMailSender.createMimeMessage()).thenReturn(message);

        doNothing().when(javaMailSender).send(message);

        emailService.sendEmail();

        verify(javaMailSender, times(1)).send((mimeMessageArgumentCaptor.capture()));
        assertEquals("subject", mimeMessageArgumentCaptor.getValue().getSubject());
    }

}

A: It's generally easier to do this kind of testing using an integration test. Emails are often built using a template library such as freemarker, so an integration test is valuable in being able to verify that your template is correct as well.
You could do unit testing by using PowerMock to create a mock MimeMessageHelper, but PowerMock can sometimes be slow at keeping up with changes to other testing libraries, and such tests often end up brittle and of little value. For example, you could verify that setSubject() was called on mimeMessageHelper, but does that produce the outcome that you really want to test (that the subject is set on message)?


text:
Q: Class 'org.springframework.web.jsf.el.SpringBeanFacesELResolver' is missing a runtime dependency I have a web application which up until yesterday was working just fine. It uses Maven, Spring, JSF, Primefaces, Eclipse (Mars), Tomcat 8 and jdk 8. Here is my pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>PlantPlaces</groupId>
    <artifactId>PlantPlaces</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>

    <repositories>
        <repository>
            <id>prime-repo</id>
            <name>PrimeFaces Maven Repository</name>
            <url>http://repository.primefaces.org</url>
            <layout>default</layout>
        </repository>

        <repository>
            <id>JBoss repository</id>
            <url>http://repository.jboss.com/maven2/</url>
        </repository>
    </repositories>

    <build>
        <sourceDirectory>src</sourceDirectory>
        <plugins>
            <plugin>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.6</version>
                <configuration>
                    <warSourceDirectory>WebContent</warSourceDirectory>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.5.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <dependencies>
        <dependency>
            <groupId>org.primefaces</groupId>
            <artifactId>primefaces</artifactId>
            <version>4.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.2.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>3.0.4.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>javax.inject</groupId>
            <artifactId>javax.inject</artifactId>
            <version>1</version>
        </dependency>
        <dependency>
            <groupId>org.primefaces.themes</groupId>
            <artifactId>all-themes</artifactId>
            <version>1.0.10</version>
        </dependency>
        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-all</artifactId>
            <version>1.9.5</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.10</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.sun.faces</groupId>
            <artifactId>jsf-api</artifactId>
            <version>2.2.7</version>
        </dependency>
        <dependency>
            <groupId>com.sun.faces</groupId>
            <artifactId>jsf-impl</artifactId>
            <version>2.2.7</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.0.1</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
        </dependency>

        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>

        <!-- MySQL database driver -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.9</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>4.3.10.Final</version>
        </dependency>

        <!-- EL -->
        <dependency>
            <groupId>org.glassfish.web</groupId>
            <artifactId>el-impl</artifactId>
            <version>2.2</version>
        </dependency>

    </dependencies>

</project>

I don't know why it stopped working but the full error that I keep getting is this:

Cause: Class
  'org.springframework.web.jsf.el.SpringBeanFacesELResolver' is missing
  a runtime dependency: java.lang.NoClassDefFoundError:
  javax/el/ELResolver

I have tried many different pom configurations but nothing eliminates that error. Kindly assist

A: I discovered that the issue was Tomcat 8 (v8.0.38). I switched to Tomcat 7 and modified my Pom.xml. I also modified my version of facelets version
 (from 2.2 to 2.1 in the faces-config.xml) and the deployment descriptor version from 3.1 to 2.5. Finally, I also changed the Java version from 1.8 to 1.7 - though the webapp is compiled based on java 1.6. Below is a sample of the new Pom.xml. It may still have errors since I have been trying out so many suggestions that I found online but it works:
<dependencies>

    <!-- Spring framework -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>3.1.2.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>3.1.2.RELEASE</version>
    </dependency>

    <!-- JSR-330 -->
    <dependency>
        <groupId>javax.inject</groupId>
        <artifactId>javax.inject</artifactId>
        <version>1</version>
    </dependency>

    <!-- JSF -->
    <dependency>
        <groupId>com.sun.faces</groupId>
        <artifactId>jsf-api</artifactId>
        <version>2.1.13</version>
    </dependency>
    <dependency>
        <groupId>com.sun.faces</groupId>
        <artifactId>jsf-impl</artifactId>
        <version>2.1.13</version>
    </dependency>

    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency>

    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>servlet-api</artifactId>
        <version>2.5</version>
    </dependency>

    <dependency>
        <groupId>javax.servlet.jsp</groupId>
        <artifactId>jsp-api</artifactId>
        <version>2.1</version>
    </dependency>

    <!-- EL -->
    <dependency>
        <groupId>org.glassfish.web</groupId>
        <artifactId>el-impl</artifactId>
        <version>2.2</version>
    </dependency>

    <!-- Tomcat 6 need this -->
    <dependency>
        <groupId>com.sun.el</groupId>
        <artifactId>el-ri</artifactId>
        <version>1.0</version>
    </dependency>

    <dependency>
        <groupId>org.primefaces</groupId>
        <artifactId>primefaces</artifactId>
        <version>4.0</version>
    </dependency>

    <dependency>
        <groupId>org.primefaces.themes</groupId>
        <artifactId>all-themes</artifactId>
        <version>1.0.10</version>
    </dependency>

    <!-- MySQL database driver -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.9</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>4.3.10.Final</version>
    </dependency>

    <!-- Logging -->
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.17</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/com.rabbitmq/amqp-client -->
    <dependency>
        <groupId>com.rabbitmq</groupId>
        <artifactId>amqp-client</artifactId>
        <version>3.6.6</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
    <dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
        <version>2.5</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/commons-cli/commons-cli -->
    <dependency>
        <groupId>commons-cli</groupId>
        <artifactId>commons-cli</artifactId>
        <version>1.2</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/net.coobird/thumbnailator -->
    <dependency>
        <groupId>net.coobird</groupId>
        <artifactId>thumbnailator</artifactId>
        <version>0.4.8</version>
    </dependency>

</dependencies>

<build>
    <finalName>plantplaces</finalName>

    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>2.3.1</version>
            <configuration>
                <source>1.6</source>
                <target>1.6</target>
            </configuration>
        </plugin>
    </plugins>
</build>


text:
Q: Dimension of $\text{Sym}^2(V)$ and $\text{Alt}^2(V)$ Is there something what we can say about the dimensions of $$\text{Sym}^2(V)=\text{span}\{x\otimes y+y\otimes x| x,y\in V\}$$ and $$\text{Alt}^2(V)=\text{span}\{x\otimes y-y\otimes x| x,y\in V\}?$$
Since these are subspaces of $V\otimes V$ the dimension must be less or equal to $n^2$, where $n$ is the dimension of $V$.
My aim is to show this with a dimension argument via the dimension formula, that $\text{Sym}^2(V)\cap\text{Alt}^2(V)=0$. Maybe this is possible with an other argument as well.

A: This is only valid when the characteristic of the field is not $2$.
Consider the map $\Phi:V\otimes V\to V\otimes V$ defined
by $a\otimes b\mapsto b\otimes a$. Then $\Phi^2$ is the identity,
and $\text{Sym}^2(V)$ and $\text{Alt}^2(V)$ are the $+1$ and $-1$
eigenspaces of $\Phi$. Then $V\otimes V$ is the direct sum of
these eigenspaces.
All of this assumes that we are not
in characteristic $2$.


text:
Q: How to change the imagealpha for a multi-select drag and drop operation in Flex Here's the code that allows multi-select list to drag into a tree area.  What I would like to do is to change the alpha of the image that gets dragged around.  I've done some research but most of the discussions out there talk about how to change the dragged image.  What I want to do is simply change the default alpha of the dragged item from 0.5 to say 0.2.  Also this solution should be able to handle multiple select dragging.  Thank you.
Below is a simple example of drag and drop that I would like to modify to allow for the alpha change of the draged item.
<?xml version="1.0" encoding="utf-8"?>

<s:layout>
    <s:VerticalLayout/>
</s:layout>

<fx:Declarations>
    <fx:XML id="treeData" xmlns="">
        <root>
            <node label="Massachusetts" type="state" data="MA">
                <node label="Boston" type="city" >
                    <node label="Smoke House Grill" type="restaurant" />
                    <node label="Equator" type="restaurant" />
                    <node label="Aquataine" type="restaurant" />
                    <node label="Grill 23" type="restaurant" />
                </node>
                <node label="Provincetown" type="city" >
                    <node label="Lobster Pot" type="restaurant" />
                    <node label="The Mews" type="restaurant" />
                </node>
            </node>
            <node label="California" type="state" data="CA">
                <node label="San Francisco" type="city" >
                    <node label="Frog Lane" type="restaurant" />
                </node>
            </node>
        </root>
    </fx:XML>
    <fx:Array id="listData">
        <fx:String>Johnny Rocket's</fx:String>
        <fx:String>Jet Pizza</fx:String>
        <fx:String>Steve's Greek</fx:String>
        <fx:String>Sonsie</fx:String>
        <fx:String>The Border Cafe</fx:String>
    </fx:Array>
</fx:Declarations>

<fx:Script>
    <![CDATA[
        import mx.events.DragEvent;
        import mx.managers.DragManager;
        import mx.core.DragSource;
        import mx.core.UIComponent;
        import mx.controls.Tree;
        /**
         * Called as soon as the dragProxy enters the target. You can add logic
         * to determine if the target will accept the drop based on the
         * dragInitiator, the data available in the dragSource, or whatever.
         * Here the drop is blindly accepted.
         */
        private function onDragEnter( event:DragEvent ) : void
        {
            DragManager.acceptDragDrop(UIComponent(event.currentTarget));
        }
        /**
         * Called while the dragProxy is over the drop target. You can
         * use this function to determine the type of feedback to show.
         * Because the List is set to allow MOVE (the item is deleted
         * once dropped), different feedback possibilities are given.
         *
         * Also, for this application, the Tree control node the dragProxy is
         * over is selected. As the dragProxy moves, the Tree control's
         * selection changes.
         *
         * A complexity in this application is that the drop is being allowed
         * only over nodes whose type is NOT 'state'.
         * The feedback is removed.
         */
        private function onDragOver( event:DragEvent ) : void {
            var dropTarget:Tree = Tree(event.currentTarget);
            var r:int = dropTarget.calculateDropIndex(event);
            tree.selectedIndex = r;
            var node:XML = tree.selectedItem as XML;
            if ( node.@type == "state" ) {
                DragManager.showFeedback(DragManager.NONE);
                return;
            }
            if (event.ctrlKey)
                DragManager.showFeedback(DragManager.COPY);
            else if (event.shiftKey)
                DragManager.showFeedback(DragManager.LINK);
            else {
                DragManager.showFeedback(DragManager.MOVE);
            }
        }
        /**
         * Called when the dragProxy is released
         * over the drop target. The information in the dragSource
         * is extracted and processed.
         *
         * The target node is determined and
         * all of the data selected (the List has allowMultipleSection
         * set) is added.
         */
        private function onDragDrop( event:DragEvent ) : void {
            var ds:DragSource = event.dragSource;
            var dropTarget:Tree = Tree(event.currentTarget);
            var items:Array = ds.dataForFormat("items") as Array;
            var r:int = tree.calculateDropIndex(event);
            tree.selectedIndex = r;
            var node:XML = tree.selectedItem as XML;
            var p:*;
            /* If the selected node has children (it is type==city),
            then add the items at the beginning. */
            if ( tree.dataDescriptor.hasChildren(node) ) {
                p = node;
                r = 0;
            } else {
                p = node.parent();
            }
            for (var i:Number=0; i < items.length; i++) {
                var insert:XML = <node />;
                insert.@label = items[i];
                insert.@type  = "restaurant";
                tree.dataDescriptor.addChildAt(p, insert, r+i);
            }
        }
        /**
         * Called when the drag operation completes, whether
         * successfully or not. The tree is cleared of its
         * selection.
         */
        private function onDragComplete( event:DragEvent ) : void {
            tree.selectedIndex = -1;
        }
    ]]>
</fx:Script>

<s:Panel x="48" y="125" width="447" height="351" title="Drag onto Tree">
    <mx:Tree width="186" left="10" top="10" bottom="10" id="tree"
             labelField="@label"
             dataProvider="{treeData.node}"
             dropEnabled="false"
             dragMoveEnabled="false"
             dragEnter="onDragEnter(event)"
             dragOver="onDragOver(event)"
             dragDrop="onDragDrop(event)">
    </mx:Tree>
    <mx:List width="188" height="206" right="10" bottom="10" id="list"
             allowMultipleSelection="true"
             dataProvider="{listData}"
             dragEnabled="true"
             dragMoveEnabled="true"
             dragComplete="onDragComplete(event)">
    </mx:List>
    <s:Label x="229" y="10" text="Drag from the list below to the tree"
             width="188" height="39"/>
    <s:Label x="229" y="69" text="restaurants"/>
</s:Panel>

A: First of all -- I'd strongly recommend that you use the spark List controls rather than the MX controls.  The spark controls behave much more predictably.
The following applies to the spark controls -- it may work with the mx controls, but YMMV.
You set the alpha of the proxy when you call DragManager.doDrag(...) (see apache livedocs.
The list components call DragManager.doDrag() for you when you set dragEnagled="true".  You can override this, and call it yourself, by handling the dragStart event.
So, given a spark list control like this:
<s:List
    id="list"
    dataProvider="{listData}"
    allowMultipleSelection="true"
    dragEnabled="true"
    dragMoveEnabled="true"
    dragComplete="onDragComplete(event)"

    dragStart="list_dragStartHandler(event)" />

Your dragStart handler might look like this:
protected function list_dragStartHandler(event:DragEvent):void
{
    if( event.dragSource ) {
        // under some conditions, this event fires multiple times,
        // we only care about it, if the dragSource isn't set yet.
        return;
    }
    event.preventDefault();

    // create the drag source, and stuff it into the event
    //
    var dragSource:DragSource = new DragSource();
    event.dragSource = dragSource;

    // let the spark list control add the default data formats
    list.addDragData(dragSource);

    // you can add your own data formats here
    // by calling `dragSource.addHandler(...)`

    // now, tell DragManager to initiate the drag
    //
    DragManager.doDrag(
        event.dragInitiator, dragSource, event,
        list.createDragIndicator(),
        0, 0,        /* offsets: x,y */
        0.2,         /* imageAlpha */
        list.dragMoveEnabled
    );
}

Note the imageAlpha is the next-to-last parameter of the call to DragManager.doDrag(...)


text:
Q: How to click a link by text in Selenium web driver java I have many links in my page.One with text "Add policyhoder" ,one with text " Add" only and another "Add PP". I need to click link by text  .I am using below code to click link having text as "Add" only but it is clicking very first link having "Add" in its text i.e. ""Add PP" available on screen.Please can u help
Driver.findElement(By.linkText("Add"));

My requirement is to click a link with exact text match . for example "Add" here

<input id="hidPoClaim" type="hidden" onblur="ResetScript(this);" onfocus="HighlightScript(this);" value=" PolicySummary " callfunction="" size="" name="/Root/ACORD/InsuranceSvcRs/com.c_HomePolicyInquiryRs/co.cc_AvailableFunctions[com._FunctionName='PoSummary' and com.csc_FunctionName[@Action='ShowPolicyClaims']]">

Policy Claims History:

**Add**

</table

Thanks
Dev

A: If it the there are 2 elements with the word "Add", Then try something like this:
List<WebElement> list = driver.findElements(By.linkText("Add"));
list.get(1).click();

To find the element by searching for the exact text, then using xpath will be more helpful.
// For "Add" link, according to the HTML you've added to the question
driver.findElement(By.xpath("//a[text()='**Add**']")).click();

A: I assume because when you click on first link it opens that link page in same tab and can not find second link element as page changed , so you have to open that link page in new tab in.
I think your code would be :
String Newtab = Keys.chord(Keys.CONTROL,Keys.RETURN);
driver.findElement(By.linkText("Add policyhoder")).sendKeys(Newtab);

driver.findElement(By.linkText("Add")).click();

Now above code will work for you.

A: you can try using
driver.findElement(By.xpath("//a[text()='Add']"));

This would match exact text for you


text:
Q: sound monitoring using python I'm trying to write a script using Python that will check if another program on my computer makes a sound.  Can't seem to find a clear solution for this.  Any help is appreciated.
Thanks!

A: Unfortunately I don't think what you want exists, but you may have some luck looking through this list: http://wiki.python.org/moin/PythonInMusic


text:
Q: Standard C library in mingW I have installed mingW to use gcc, platform windows 7. I am trying to locate the standard C library libc.a in mingW folder. no luck.. is it stored in some other name?

A: MinGW does not build against glibc, it builds against msvcrt. As such, it uses libmsvcrtXX.a instead.


text:
Q: Hide HTML code temporarily and display them later I am trying to remove all HTML tags from a textarea-tag (TEMPORARILY), but then display the textarea value after that on the page.
<textarea>Test
</textarea>

Show textarea here:

My jQuery
$("#show").html($("textarea").val());

http://jsfiddle.net/vQD5w/
That is how I show the textarea content at the moment, and that is how it is going to look in the end. Meanwhile I want to hide the HTML code from the textarea, so what is inside the textarea does not look ugly and unreadable to the common PC user. Textarea should therefore only contain "Test" (no quotations).
So basically I want to escape all HTML tags, elements, and everything related to HTML INSIDE the textarea-tag, but use it later on.

A: You could use regular expressions to strip out the tags, barring that you aren't trying to parse it.
$("#show").html($("textarea").val());
var text = $('textarea').val();
$('textarea').val(text.replace(/(<([^>]+)>)/ig,""));

Example: http://jsfiddle.net/brandonscript/ffC4q/

A: This is what you want to do. Put the value of the textarea in the show span. Then get rid of the html tags from the textarea with a regular expression.
$inner = $("textarea").val();
$("#show").text($inner);
$('textarea').val(text.replace(/(<([^>]+)>)/ig,""));

As shown in this JSFiddle

A: You can achieve the desired result using a contenteditable div instead of a textarea.

Test

And then you get the html instead of the val()
$("#show").html($("div").html());

you can put a border around the div if you want it to look like a text area.
http://jsfiddle.net/EnKLA/

A: You can do it by replacing html tags with regex:
HTML:
<textarea id="textArea">Test</textarea>

Show textarea here:

JS:
var textWOHTML = $("textarea").val().replace(/<(.|\n)*?>/, '').replace(/<\/(.|\n)*?>/, '');
var textWithHTML = $("textarea").val();
$('#textArea').val(textWOHTML);
$("#show").html(textWithHTML);

Here is the fiddle: http://jsfiddle.net/vQD5w/2/

A: Since I clearly misunderstood his exact need, I've removed my suggestion!


text:
Q: Django smart_str 'NoneType' object has no attribute In django, I want to download the data to excel using the smart_str, but some record of user dont have data or blank some field like in the error below, how can i do with smart_str which should be unnecessary or error free if no data can be detected?
def downloadcv(request):
    response = HttpResponse(content_type='text/csv')
    # decide the file name
    response['Content-Disposition'] = 'attachment; filename="StudentEnrollmentRecord.csv"'

    writer = csv.writer(response, csv.excel)
    response.write(u'\ufeff'.encode('utf8'))
    writer.writerow([
       smart_str(u"Guardians_Fullname"),
       smart_str(u"Guardians_Address"),
       smart_str(u"Contact_Number"),
    ])
    reports = StudentsEnrollmentRecord.objects.filter(School_Year=yearid).order_by('Education_Levels','-Date_Time')
    for report in reports:
        last_name = report.Student_Users.Parent_Users.Guardian_LastName or ""
        first_name = report.Student_Users.Parent_Users.Guardian_FirstName or ""
        initial = report.Student_Users.Parent_Users.Guardian_Middle_Initial or ""
        writer.writerow([
        smart_str(last_name, first_name, initial),
    return response if response is not None else 'None'

this is the error i get

A: You can make use of a try-catch exception handler
Give this a try
try:
   last_name = report.Student_Users.Parent_Users.Guardian_LastName
except AttributeError:
   last_name = ""

NB: You may have to do the same for the rest of fields also


text:
Q: ORA-19228: XPST0008 - undeclared identifier in oracle sql I have xml string which i have mentioned below and i want to extract code from xml string. I have written below select query to extract the value from <ax2140:code>0</ax2140:code> which is 0 but i am getting error as
ORA-19228: XPST0008 - undeclared identifier: prefix 'ax2140' local-name 'ax2140:code'
19228. 00000 -  "XPST0008 - undeclared identifier: prefix '%s' local-name '%s'"

Here is my xml string-
<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
   <soapenv:Body>
      <ns:placeShopOrderResponse xmlns:ns="http://service.soap.CDRator.com">
         <ns:return xmlns:ax2127="http://data.soap.CDRator.com/xsd"
         xmlns:ax2129="http://webshop.data.soap.CDRator.com/xsd"
         xmlns:ax2130="http://core.data.soap.CDRator.com/xsd"
         xmlns:ax2133="http://signup.data.soap.CDRator.com/xsd"
         xmlns:ax2134="http://core.signup.data.soap.CDRator.com/xsd"
         xmlns:ax2139="http://result.service.soap.CDRator.com/xsd"
         xmlns:ax2140="http://core.result.service.soap.CDRator.com/xsd"
         xmlns:ax2147="http://webshop.result.service.soap.CDRator.com/xsd"
         xmlns:ax2148="http://mandate.result.service.soap.CDRator.com/xsd"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="ax2147:PlaceShopOrderResultDTO">
            <ax2130:id xsi:nil="true" />
            <ax2140:code>0</ax2140:code>
            <ax2140:description>OK</ax2140:description>
               <ax2127:statusId>1</ax2127:statusId>
               <ax2127:subscriptionCondition xsi:type="ax2127:SubscriptionStatusDTO">
                  <ax2130:id xsi:nil="true" />
                  <ax2140:code>0</ax2140:code>
                  <ax2140:description>OK</ax2140:description>
                  <ax2130:imsi xsi:nil="true" />
                  <ax2130:phoneNumber>NO_NUMBER</ax2130:phoneNumber>
                  <ax2127:imei xsi:nil="true" />
                  <ax2127:simCard xsi:nil="true" />
               </ax2127:teleService>
            </ax2147:subscriptions>
         </ns:return>
      </ns:placeShopOrderResponse>
   </soapenv:Body>
</soapenv:Envelope>

Here is my select query:
SELECT ID,xt_code.CODE
FROM TEMP_SOAP_MONITORING_MSP sm
CROSS JOIN XMLTable(XMLNAMESPACES (
      'http://core.result.service.soap.CDRator.com/xsd' as "ax2140_code"
    ),
    'for $i in //ax2140:code return $i'
    passing XMLType(sm.RESPONSE_XML)
    columns "CODE" VARCHAR2(50) path '/') xt_code;

A: Use "ax2140" instead of "ax2140_code" in the query.


text:
Q: Django template variable not recognized in script tag but recognized in regular h1 tag. what could cause that? <script>
    var my_data = {{ passed_data }}
</script>

<body>
    <h1>{{ passed_data }}</h1>
</body>

This is the basic idea behind the code. I suspect it may be a scope issue

A: Add quotes to the JS:
<script>
    var my_data = "{{ passed_data }}"
<script>


text:
Q: Run a linux docker container on Windows Server 2022 I have a Windows Server 2022 running on GCP. I've installed docker as described here: https://cloud.google.com/compute/docs/containers#docker_on_windows
Namely, I did this:
Install-Module -Name DockerMsftProvider -Repository PSGallery -Force
Install-Package -Name docker -ProviderName DockerMsftProvider
Restart-Computer -Force

However, when I try to run a linux image, I get
PS C:\Windows\system32> docker run busybox ls
Unable to find image 'busybox:latest' locally
latest: Pulling from library/busybox
docker: no matching manifest for windows/amd64 10.0.20348 in the manifest list entries.
See 'docker run --help'.

PS C:\Windows\system32> docker run --rm --platform linux alpine ls
Unable to find image 'alpine:latest' locally
docker: Error response from daemon: unsupported os linux.
See 'docker run --help'.

What am I doing wrong?
Edit. I can't enable hyper-V on GCP. My processor is Intel(R) Xeon(R) CPU @ 2.80GHz   2.80 GHz should't it allow nested virtualization
Screenshot
Looks like I need to enable nested virtualization in gcp. For that, I need to set enableNestedVirtualization field to true. There are descriptions on how to do it with gcloud api, but no way I can get my customer to do that. Any way to do it either in the WebUI or the VPS itself?
Edit 2. Does this mean I can't run a linux docker container from Windows? Or is docker a special case?

L1 VMs have the following restrictions:
You must run Linux-based OSes; you can't use Windows Server images.

https://cloud.google.com/compute/docs/instances/nested-virtualization/overview

A: So, a few things about what you are trying to do:

*

*Linux containers on Windows (either client 10/11 or Server) are not supported in production. You can run it for development/testing purposes.

*Linux containers require WSL to work on Windows. Specifically, for Windows Server 2022, WSL2 is required. I blogged about this here: https://techcommunity.microsoft.com/t5/itops-talk-blog/using-wsl-2-on-windows-server-2022-to-run-linux-containers/ba-p/3624745

*WSL 2 essentially runs a Linux VM and exposes the CLI and services. For that to work on any cloud, you need nested virtualization enabled.


text:
Q: Add Single Table Inheritance (STI) to existing models I currently have multiple tables that are very similar. I should probably have created them with STI.
TypeOne < ActiveRecord::Base
TypeTwo < ActiveRecord::Base
TypeThree < ActiveRecord::Base

TypeOne(id: integer, parent_id: integer, created_at: datetime, updated_at: datetime)
TypeTwo(id: integer, parent_id: integer, created_at: datetime, updated_at: datetime)
TypeThree(id: integer, parent_id: integer, created_at: datetime, updated_at: datetime)

I am now trying to add STI to these. I created a BaseModel and added a type to that model.
BaseModel(id: integer, parent_id: integer, created_at: datetime, updated_at: datetime, type: string)

I also ran a migration and added to all of the types, a type column.
class AddTypeToTables < ActiveRecord::Migration
  def change
    add_column :type_ones, :type, :string
    add_column :type_twos, :type, :string
    add_column :type_threes, :type, :string
  end
end

I want to combine all of the type tables into a STI. There is existing data in the models. If I were to combine them into a single table, I imagine the id's for the respective tables would conflict. For example:
#<TypeOne id: 4, parent_id: 1, created_at: "2015-05-08 18:39:09", updated_at: "2015-09-07 19:42:03">

#<TypeTwo id: 4, parent_id: 1, created_at: "2015-04-08 17:48:59", updated_at: "2015-09-07 14:17:48">

If I try to use becomes, it appears to change the class, but I cannot find the record in the BaseModel
TypeOne.last.becomes!(BaseModel)
#<BaseModel id: 4, parent_id: 1, created_at: "2015-05-08 18:39:09", updated_at: "2015-09-07 19:42:03">

BaseModel.all
=> []

I have also tried to change the type column of the inherited table to the basemodel
to = TypeOne.first
to.type = "BaseModel"
to.save

BaseModel.all
=> []

I have tried to change the classes for each to be a child of the BaseModel
TypeOne < BaseModel
TypeTwo < BaseModel
TypeThree < BaseModel

When I do this, I lose the connection to the existing data and each of the models appear empty.
How can I combine the existing tables?

A: As you've tagged it with PostgreSQL I'll include how to do what I suggested in my comment as an answer:
INSERT INTO base_model SELECT * FROM type_one ORDER BY id ASC;
INSERT INTO base_model SELECT * FROM type_two ORDER BY id ASC;
INSERT INTO base_model SELECT * FROM type_three ORDER BY id ASC;

To safely do this on a production dataset, put the SQL in a migration in db/migrate (i.e. in a file like db/migrate/20150907185938_integrate_tables.rb) and test it on your local database first. This should get you pretty close:
class IntegrateTables < ActiveRecord::Migration
  def up
    execute "INSERT INTO base_model SELECT * FROM type_one ORDER BY id ASC;"
    execute "INSERT INTO base_model SELECT * FROM type_two ORDER BY id ASC;"
    execute "INSERT INTO base_model SELECT * FROM type_three ORDER BY id ASC;"
  end

  def down
    raise ActiveRecord::IrreversibleMigration, "It is unclear where original data stops and inserted data begins, can't migrate down"
  end
end

Please mark this answer as accepted if it worked for you :)


text:
Q: transform char to numeric data in mutate assign to data frame variable Problem context: replace a chr variable in data frame by retaining the chr values in data frame using mutate case_when to conditionally inspect (case_when) to determine value for mutated result.
The target is a variable named: length_of_service
conditional data for case_when is:
"< 1 year", "2 years", "3 years", "4 years", "5 years", "6 years", "7 years", "8 years", "9 years", "10+ years"
Attempted effort code: I can build a data frame with one variable, length_of_service, transform the character string of year(s) to an equivalent numeric, then mutate the variable inside this data frame, then cbind() the df_length data frame with the original data frame. I do not wish to overwrite the original length_of_services inside the original data frame until the mutate / case_when() clause is executed. Then I can replace with the cbind() to combine data frames. I welcome suggestions to problem approach solution.
df_length <- data.frame(length_of_service = numeric())
df_length %>%
   mutate(df$length_of_service == case_when(
          df$length_of_service == "< 1 year" ~ 0.99,
          df$length_of_service == "2 years" ~ 2,
          df$length_of_service == "3 years" ~ 3,
          df$length_of_service == "4 years" ~ 4,
          df$length_of_service == "5 years" ~ 5,
          df$length_of_service == "6 years" ~ 6,
          df$length_of_service == "7 years" ~ 7,
          df$length_of_service == "8 years" ~ 8,
          df$length_of_service == "9 years" ~ 9,
          df$length_of_service == "10+ years" ~ 10,
          TRUE ~ "NA"
   )

Result / Error:
Error: must be a double vector, not a character vector

A: case_when expects value to be returned of same type so return NA_real instead of "NA".
library(dplyr)

df %>%
  mutate(length_of_service_new = case_when(
             length_of_service == "< 1 year" ~ 0.99,
             length_of_service == "2 years" ~ 2,
             length_of_service == "3 years" ~ 3,
             length_of_service == "4 years" ~ 4,
             length_of_service == "5 years" ~ 5,
             length_of_service == "6 years" ~ 6,
             length_of_service == "7 years" ~ 7,
             length_of_service == "8 years" ~ 8,
             length_of_service == "9 years" ~ 9,
             length_of_service == "10+ years" ~ 10,
             TRUE ~ NA_real_))

I would however do,
df %>%
 mutate(year = readr::parse_number(length_of_service),
        length_of_service_new = replace(year, year == 1, 0.99))

which should return the same output as the above case_when output.

A: Base R solution:
years <-
  as.numeric(gsub("[A-Za-z]|[[:punct:]]|\\s+", "", df$length_of_service))

df$length_of_service_new <-
  ifelse(years == 1, .99, ifelse(years > 10, 10, years))

# Data:

df <- data.frame(
  length_of_service =
    c(
      "< 1 year",
      "2 years",
      "3 years",
      "4 years",
      "5 years",
      "6 years",
      "7 years",
      "8 years",
      "9 years",
      "10+ years",
      "11 years"
    )
)


text:
Q: Validation error not showing in right place I have appended a select box dynamically inside a td tag using jquery and assigned that class required-entry but when i submit form validation not showing on the right place.
this is my appended code.
var addrow = '
<select onchange="getPrice(this)" id="selectbox-'+counter+'" name="pid[]" customerid="'+customer+'" class="required-entry required-entry select">';
        addrow +='<option value="">select product</option>';
        for (i = 0; i < valueArray.length; i++) {
           addrow +='<option value="'+valueArray[i]+'">'+textArray[i]+'</option>';
         }
        addrow +='</select>	<input type="number" id="qty-box-'+counter+'" class="qty-box" max="1000" min="1" value="1" name="itemqty[]" onchange="qtyUpdate(this)" customerid="'+customer+'">

	<input id ="delsku-'+counter+'" type="checkbox" value="" name="deletesku[]"/>
';

        jQuery("#items-table").append(addrow);

add errors are showing together i want error just below of selectbox


text:
Q: Create user control fields based on bound properties I am creating a user control that I would like to be able to generate the form entry fields based on what custom data object the form is bound to. Basically, I have a drop-down box that allows the user to pick what type of data object they are working with (user, address, etc.) That choice will bind the user control to the related data object. No big deal there. I am stuck, however, on how to generate the form fields based on the properties of the object. I feel like I have seen examples of this in WPF but am not able to find them now. All form fields will be simple label, textbox combinations in a stackpanel.
I know more detial will probably be required. Let me know what specifically you would like to know. Any help of direction is greatly appreciated.
Best,
Ryan

A: It sounds like you are looking for something which runtime generated, but check out the Xaml Power Toys, which will do this at design time


text:
Q: Web service authentication issue - using openam j2ee agent 3 I am new to openAM. I am trying to use openAM (954) to secure my web service using J2EE agent 3.0. I have deployed my webservice (using CXF) on Glass fish 3.1.x.
I have created necessary configuration given in URL http://docs.oracle.com/cd/E19575-01/820-4803/ghuqg/index.html
I want to authenticate using user id and password. I am passing this information (userid/password) using SOAP header. But when I try to access my web service in browser it gives access forbidden message.
Are there any additional configurations required? Please let me know, I am not able to find any other information on this anywhere.
Following is the request we are sending. I am not sure about UsernameToken wsu:Id whether it is correct? How do we get this value from OpenAM dynamically at each time when we send the request.

        <wsse:Security soapenv:mustUnderstand="1" xmlns:wsse="HTTPdocs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">

        <wsse:UsernameToken wsu:Id="UsernameToken-27777511" xmlns:wsu="HTTPdocs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">

        <wsse:Username>amadmin</wsse:Username>

        <wsse:Password Type="HTTPdocs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">Amit4001</wsse:Password>

        </wsse:UsernameToken>

        </wsse:Security>

  <demo:greetPerson>

     <!--Optional:-->

     <arg0>Ashish</arg0>

  </demo:greetPerson>

Please help me solve this issue.

A:
I want to authenticate using user id and password. I am passing this information (userid/password) using SOAP header. But when I try to access my web service in browser it gives access forbidden message.

I'm currently struggling to learn OpenAM as well and I think your specific problem is that you have not yet set up a policy (not a policy agent) after users have successfully authenticated.
If you haven't try the following steps:
Navigate to Access Control -> YourRealm -> Policies -> New Policy

Name: yourpolicyname
Rules (click new):

Name: URLPolicy
Resource Name: http:// your-webservice-url/*
Check allow get and post
Name: GetUrlPolicy
Resource Name: http:// your-webservice-url /* ? *
Check allow get and post

Subjects (click new)
Type = OpenAM Identity Subject
Name: UserAccess
Add users you want to be able to authenticate
You have to add in the * ? * if you have any GET parameters in your web page.

Hope that helps, I know the documentation around is terrible.

A: For your agent policy, in the Global tab: General section > Agent Filter Mode, remove ALL and add SSO_ONLY (leave Map Key blank and Map Value as SSO_ONLY). Note that this configuration isn't hot-swappable, so OpenAM has to be restarted to apply.
Here is a procedure for installing the agent on the server you want to protect:
http://openam.forgerock.org/openam-documentation/openam-doc-source/doc/jee-install-guide/index/chap-glassfish.html
Here is a good procedure for configuring the agent policy centrally on the OpenAM server:
http://openam.forgerock.org/openam-documentation/openam-doc-source/doc/admin-guide/index/chap-agents.html#create-agent-profiles
You might want to also control which URIs (webapps) to protect instead of the entire website. To do that, in the agent policy:

*

*Application tab: Not Enforced URI Processing section > add the URI to protect, for example: /application1/*

*Application tab: Not Enforced URI Processing section > check the "Invert Not Enforced URIs" checkbox so that it will actually enforce the "Not Enforced URI" values


text:
Q: c# htmlagility Select specifics nodes depending on the innertext I have multiple labels inside a div. Those labels have a class which names either "Return" or "Going" like :

I want to get two IEnumerable of the labels one going and one return;
something like
var going = node.SelectNodes("label").Where(item => item.InnerHtml == "going");
var return= node.SelectNodes("label").Where(item => item.InnerHtml == "return");

A: You might want to use this method:
public static bool HasClass(this HtmlNode node, params string[] classValueArray)
{
    var classValue = node.GetAttributeValue("class", "");
    var classValues = classValue.Split(' ');
    return classValueArray.All(c => classValues.Contains(c));
}
//use it like this
doc.DocumentNode.Descendants("label").Where(_ => _.HasClass("going"))


text:
Q: Xamarin Forms Resize Image inside Listview How can I set the size of the image inside of a list view. Currently I have several lists that have icons but I don't see any options for changing the aspect ratio or size of the image so it just gets blown up to the height of the list item.
all the images are from the Drawable folder
        var cell = new DataTemplate(typeof(MenuTextCell));
        cell.SetBinding(TextCell.TextProperty, "Title");
        cell.SetBinding(ImageCell.ImageSourceProperty, "IconSource");
        cell.SetValue(BackgroundColorProperty, Color.Transparent);
        cell.SetValue(TextCell.TextColorProperty, Color.FromHex("262626"));

I am using a custom renderer
public class MenuTextCellRenderer : ImageCellRenderer
    {
        protected override View GetCellCore (Cell item, View convertView, ViewGroup parent, Context context)
        {
            var cell = (LinearLayout)base.GetCellCore (item, convertView, parent, context);
            cell.SetPadding(20, 10, 0, 10);
            cell.DividerPadding = 50;

            var div = new ShapeDrawable();
            div.SetIntrinsicHeight(1);
            div.Paint.Set(new Paint { Color = Color.FromHex("b7b7b7").ToAndroid() });

            if (parent is ListView)
            {
                ((ListView)parent).Divider = div;
                ((ListView)parent).DividerHeight = 1;
            }

            var icon = (ImageView)cell.GetChildAt(0);

            var label = (TextView)((LinearLayout)cell.GetChildAt(1)).GetChildAt(0);
            label.SetTextColor(Color.FromHex("262626").ToAndroid());
            label.TextSize = Font.SystemFontOfSize(NamedSize.Large).ToScaledPixel();
            label.TextAlignment = TextAlignment.Center;
            label.Text = label.Text.ToUpper();

            var secondaryLabel = (TextView)((LinearLayout)cell.GetChildAt(1)).GetChildAt(1);
            secondaryLabel.SetTextColor(Color.FromHex("262626").ToAndroid());
            secondaryLabel.TextSize = Font.SystemFontOfSize(NamedSize.Large).ToScaledPixel();
            label.TextAlignment = TextAlignment.Center;

            return cell;
        }

A: You are now dealing with an Android ImageView.
You have your reference via var icon = (ImageView)cell.GetChildAt(0).
You can now customize it via methods such as .setScaleType() for aspect ratio related, and use .layout() to change the position / size.

A: Try something like this on your ListView.ItemTemplate, instead of using the imagecell. You can also write your custom cell.
<DataTemplate>
<ViewCell>
    <StackLayout VerticalOptions="FillAndExpand" Orientation="Horizontal" Padding="10">
        <Image Aspect="AspectFill" HeightRequest ="20" WidthRequest="20" Source="{Binding IconSource}" />
        <Label Text="{Binding Title}" YAlign="Center" Font="Medium" />
    </StackLayout>
</ViewCell>


text:
Q: Is Python's "with" monadic? Like many a foolhardy pioneer before me, I'm endeavoring to cross the trackless wasteland that is Understanding Monads.
I'm still staggering through, but I can't help noticing a certain monad-like quality about Python's with statement.  Consider this fragment:
with open(input_filename, 'r') as f:
   for line in f:
       process(line)

Consider the open() call as the "unit" and the block itself as the "bind".  The actual monad isn't exposed (uh, unless f is the monad), but the pattern is there.  Isn't it?  Or am I just mistaking all of FP for monadry?  Or is it just 3 in the morning and anything seems plausible?
A related question: if we have monads, do we need exceptions?
In the above fragment, any failure in the I/O can be hidden from the code.  Disk corruption, the absence of the named file, and an empty file can all be treated the same.  So no need for a visible IO Exception.
Certainly, Scala's Option typeclass has eliminated the dreaded Null Pointer Exception.  If you rethought numbers as Monads (with NaN and DivideByZero as the special cases)...
Like I said, 3 in the morning.

A: Haskell has an equivalent of with for files, it's called withFile. This:
with open("file1", "w") as f:
    with open("file2", "r") as g:
        k = g.readline()
        f.write(k)

is equivalent to:
withFile "file1" WriteMode $ \f ->
  withFile "file2" ReadMode $ \g ->
    do k <- hGetLine g
       hPutStr f k

Now, withFile might look like something monadic. Its type is:
withFile :: FilePath -> IOMode -> (Handle -> IO r) -> IO r

right side looks like (a -> m b) -> m b.
Another similarity: In Python you can skip as, and in Haskell you can use >> instead of >>= (or, a do block without <- arrow).
So I'll answer this question: is withFile monadic?
You could think that it can be written like this:
do f <- withFile "file1" WriteMode
   g <- withFile "file2" ReadMode
   k <- hGetLine g
   hPutStr f k

But this doesn't type check. And it cannot.
It's because in Haskell the IO monad is sequential: if you write
do x <- a
   y <- b
   c

after a is executed, b is executed and then c. There is no "backtrack"
to clean a at the end or something like that. withFile, on the other hand,
has to close the handle after the block is executed.
There is another monad, called continuation monad, which allows to do such
things. However, you have now two monads, IO and continuations, and using effects of two monads at once requires using monad transformers.
import System.IO
import Control.Monad.Cont

k :: ContT r IO ()
k = do f <- ContT $ withFile "file1" WriteMode
       g <- ContT $ withFile "file2" ReadMode
       lift $ hGetLine g >>= hPutStr f

main = runContT k return

That's ugly. So the answer is: somewhat, but that requires dealing with a lot of  subtleties that make the issue rather opaque.
Python's with can simulate only a limited bit of what monads can do - add entering and finalization code. I don't think you can simulate e.g.
do x <- [2,3,4]
   y <- [0,1]
   return (x+y)

using with (it might be possible with some dirty hacks). Instead, use for:
for x in [2,3,4]:
    for y in [0,1]:
        print x+y

And there's a Haskell function for this - forM:
forM [2,3,4] $ \x ->
  forM [0,1] $ \y ->
    print (x+y)

I recommed reading about yield which bears more resemblance to monads than with:
http://www.valuedlessons.com/2008/01/monads-in-python-with-nice-syntax.html

A related question: if we have monads, do we need exceptions?

Basically no, instead of a function that throws A or returns B you can make a function that returns Either A B. The monad for Either A will then behave just like exceptions - if one line of code will return an error, the whole block will.
However, that would mean that division would have type Integer -> Integer -> Either Error Integer and so on, to catch division by zero. You would have to detect errors (explicitly pattern match or use bind) in any code that uses division or has even slightest possibility of going wrong. Haskell uses exceptions to avoid doing this.

A: I have thought unnecessarily long about this and I believe the answer is "yes, when it's used a certain way" (thanks outis :),
but not for the reason I thought before.
I mentioned in a comment to agf's answer, that >>= is just continuation passing style —
give it a producer and a callback and it "runs" the producer and feeds it to the
callback. But that's not quite true. Also important is that >>= has to run
some interaction between the producer and the result of the callback.
In the case of the List monad, this would be concatenating lists. This
interaction is what makes monads special.
But I believe that Python's with does do this interaction, just not in the
way you might expect.
Here's an example python program employing two with statements:
class A:

    def __enter__(self):
        print 'Enter A'

    def __exit__(self, *stuff):
        print 'Exit A'

class B:

    def __enter__(self):
        print 'Enter B'

    def __exit__(self, *stuff):
        print 'Exit B'

def foo(a):
    with B() as b:
        print 'Inside'

def bar():
    with A() as a:
        foo(a)

bar()

When run the output is:
Enter A
Enter B
Inside
Exit B
Exit A

Now, Python is an imperative language, so instead of merely producing data, it
produces side-effects. But you can think of those side-effects as being data
(like IO ()) — you can't combine them in all the cool ways you could combine
IO (), but they're getting at the same goal.
So what you should focus on is the sequencing of those operations — that is,
the order of the print statements.
Now compare the same program in Haskell:
data Context a = Context [String] a [String]
    deriving (Show)

a = Context ["Enter A"] () ["Exit A"]
b = Context ["Enter B"] () ["Exit B"]

instance Monad Context where
    return x = Context [] x []
    (Context x1 p y1) >>= f =
        let
            Context x2 q y2 = f p
        in
            Context (x1 ++ x2) q (y2 ++ y1)

foo :: a -> Context String
foo _ = b >> (return "Inside")

bar :: () -> Context String
bar () = a >>= foo

main = do
    print $ bar ()

Which produces:
Context ["Enter A","Enter B"] "Inside" ["Exit B","Exit A"]

And the ordering is the same.
The analogy between the two programs is very direct: a Context has some
"entering" bits, a "body", and some "exiting" bits. I used String instead of
IO actions because it's easier — I think it should be similar with IO actions (correct me if it's not).
And >>= for Context does exactly what with in Python does: it runs the
entering statements, feeds the value to the body, and runs the exiting
statements.
(There's another huge difference which is that the body should depend on the
entering statements. Again I think that should be fixible).

A: It's almost too trivial to mention, but the first problem is that with isn't a function and doesn't take a function as an argument. You can easily get around this by writing a function wrapper for with:
def withf(context, f):
    with context as x:
        f(x)

Since this is so trivial, you could not bother to distinguish withf and with.
The second problem with with being a monad is that, as a statement rather than an expression, it doesn't have a value. If you could give it a type, it would be M a -> (a -> None) -> None (this is actually the type of withf above). Speaking practically, you can use Python's _ to get a value for the with statement. In Python 3.1:
class DoNothing (object):
    def __init__(self, other):
        self.other = other
    def __enter__(self):
        print("enter")
        return self.other
    def __exit__(self, type, value, traceback):
        print("exit %s %s" % (type, value))

with DoNothing([1,2,3]) as l:
    len(l)

print(_ + 1)

Since withf uses a function rather than a code block, an alternative to _ is to return the value of the function:
def withf(context, f):
    with context as x:
        return f(x)

There is another thing preventing with (and withf) from being a monadic bind. The value of the block would have to be a monadic type with the same type constructor as the with item. As it is, with is more generic. Considering agf's note that every interface is a type constructor, I peg the type of with as M a -> (a -> b) -> b, where M is the context manager interface (the __enter__ and __exit__ methods). In between the types of bind and with is the type M a -> (a -> N b) -> N b. To be a monad, with would have to fail at runtime when b wasn't M a. Moreover, while you could use with monadically as a bind operation, it would rarely make sense to do so.
The reason you need to make these subtle distinctions is that if you mistakenly consider with to be monadic, you'll wind up misusing it and writing programs that will fail due to type errors. In other words, you'll write garbage. What you need to do is distinguish a construct that is a particular thing (e.g. a monad) from one that can be used in the manner of that thing (e.g. again, a monad). The latter requires discipline on the part of a programmer, or the definition of additional constructs to enforce the discipline. Here's a nearly monadic version of with (the type is M a -> (a -> b) -> M b):
def withm(context, f):
    with context as x:
        return type(context)(f(x))

In the final analysis, you could consider with to be like a combinator, but a more general one than the combinator required by monads (which is bind). There can be more functions using monads than the two required (the list monad also has cons, append and length, for example), so if you defined the appropriate bind operator for context managers (such as withm) then with could be monadic in the sense of involving monads.

A: Yes.
Right below the definition, Wikipedia says:

In object-oriented programming terms, the type construction would correspond to the declaration of the monadic type, the unit function takes the role of a constructor method, and the binding operation contains the logic necessary to execute its registered callbacks (the monadic functions).

This sounds to me exactly like the context manager protocol, the implementation of the context manager protocol by the object, and the with statement.
From @Owen in a comment on this post:

Monads, at their most basic level, are more or less a cool way to use continuation-passing style: >>= takes a "producer" and a "callback"; this is also basically what with is: a producer like open(...) and a block of code to be called once it's created.

The full Wikipedia definition:

A type construction that defines, for every underlying type, how to obtain a corresponding monadic type. In Haskell's notation, the name of the monad represents the type constructor. If M is the name of the monad and t is a data type, then "M t" is the corresponding type in the monad.

This sounds like the context manager protocol to me.

A unit function that maps a value in an underlying type to a value in the corresponding monadic type. The result is the "simplest" value in the corresponding type that completely preserves the original value (simplicity being understood appropriately to the monad). In Haskell, this function is called return due to the way it is used in the do-notation described later. The unit function has the polymorphic type t→M t.

The actual implementation of the context manager protocol by the object.

A binding operation of polymorphic type (M t)→(t→M u)→(M u), which Haskell represents by the infix operator >>=. Its first argument is a value in a monadic type, its second argument is a function that maps from the underlying type of the first argument to another monadic type, and its result is in that other monadic type.

This corresponds to the with statement and its suite.
So yes, I'd say with is a monad. I searched PEP 343 and all the related rejected and withdrawn PEPs, and none of them mentioned the word "monad". It certainly applies, but it seems the goal of the with statement was resource management, and a monad is just a useful way to get it.


text:
Q: Why does this simple floated definition list not work in IE7, and how do I fix it? This is a very simple dl.
HTML

Edition

200

Ratio

3:1

Location

Great ocean road, Victoria

FStop

F-32

Exposure

3 minutes 40 seconds

CSS
#photo-attributes {
  margin: 1em 0;
  overflow: hidden;
}

#photo-attributes dt {
  width: 10em;
  float: left;
  clear: left;
  font-weight: bold;
}

#photo-attributes dd {
  float: left;
}

It works as expected in everything except IE7. The dd float left on one line. I can't recall what bug this is in IE7.
How do I fix this? Thanks

A: This is related to the haslayout bug. But after all, the dd does not need to be floated left. Remove it.

A: IE7-specific markup (note float removed and trigger hasLayout):
#photo-attributes dd {
    zoom: 1;
}

If you remove the float for all browsers and don't trigger hasLayout for IE7, then you might not get the result you expect if the dd happens to have a line break/is "taller" than the dt to its left.

A: Definition lists are sometimes a pain to figure out but i've blogged on a very simple fix which does away with floats and works in most common browsers. It involves using the display: inline-block style which make the element behave as an inline element but forces it to have block level styling.
http://www.qasimalyas.co.uk/definition-lists-making-them-behave/

A: I was doing something similar and the above answers were not working. I ended up defining the  as display: block; float: none; and seemed to work fine for IE7.


text:
Q: Maximize[Cos[x - 1], x] is not evaluated No explanation needed:
Maximize[Cos[x + 1], x]
Maximize[Cos[x - 1], x]

producing
{1, {x -> -1 + 2 π}}
Maximize[Cos[1 - x], x]

Needless to say, this is pretty amusing.
Does anyone know why this is happening? I am using V10.0.2 Windows 7 64-bit, although I also verified it to occur on V10.0.1 Mac Snow Leopard (I haven't tested V9 and older).
Backstory
I was showing my friend how Mathematica works, and wanted to show him that the maximum of $\cos(f\,t−k\,x)$ was $1$ (he was taking an intro physics class). I applied Maximize to it, thinking I would get the answer. Hilarity ensued.
It didn't take long to find a significantly shorter minimal example.

A: For a periodic function, specify a period or use Solve or Reduce for a general solution.
f1[x_] = Cos[x + 1];

Maximize[{f1[x], -Pi <= x <= Pi}, x]

{1, {x -> -1}}

Maximize[{f1[x], 0 <= x <= 2 Pi}, x]

{1, {x -> -1 + 2*Pi}}

{f1[x] /. #, #} &@Solve[{f1'[x] == 0, f1''[x] < 0}, x][[1]] //
 Simplify[#, Element[C[1], Integers]] &

{1, {x -> -1 + 2*Pi*C[1]}}

f2[x_] = Cos[x - 1];

Maximize[{f2[x], -Pi <= x <= Pi}, x]

{1, {x -> 1}}

Maximize[{f2[x], 0 <= x <= 2 Pi}, x]

{1, {x -> 1}}

{f2[x] /. #, #} &@Solve[{f2'[x] == 0, f2''[x] < 0}, x][[1]] //
 Simplify[#, Element[C[1], Integers]] &

{1, {x -> 1 - 2*Pi*C[1]}}

A: Oh boy, it's hard to fix this at the top level.  It should be easy for WRI to fix, though.  I hope you've reported it.  If we fix Periodic`PeriodicFunctionPeriod to return nonnegative periods, Maximize will work properly.  The internal code has somewhat complicated pattern constraints on the definitions. I couldn't get the Villegas-Gayley technique to work, so I added an Abs* a real-only version of absolute value to the top-level internal function.
Block[{Periodic`PeriodicFunctionPeriod},

 Periodic`PeriodicFunctionPeriod[Periodic`PeriodicFunctionDump`expr__] /;
   Periodic`Private`PDValidExpressionQ[{Periodic`PeriodicFunctionDump`expr}] :=
  Block[{Periodic`PeriodicFunctionDump`res},
   Periodic`PeriodicFunctionDump`res =
    Periodic`PeriodicFunctionDump`periodicFunctionPeriod[Periodic`PeriodicFunctionDump`expr];
   If[Quiet[TrueQ[# < 0]], -#, #] &@ Periodic`PeriodicFunctionDump`res /;   (* <-- the "fix" *)
    FreeQ[Periodic`PeriodicFunctionDump`res, $Failed]];

 Maximize[Cos[1 - x], x]
 ]
(*
  {1, {x -> 1}}
*)

I cannot be sure that such a fix won't break something.  It could be that a "negative period" is a sign of something that is used somewhere inside Mathematica.  Mathematically speaking, the period should be a positive number.

The problem, as I mentioned in a comment, is that negative coefficients on x results in a negative period:
Periodic`PeriodicFunctionPeriod[Cos[1 - x], x]
(*  -2 π  *)

Maximize checks that the period is between 0 and Infinity.  (So Maximize is assuming the mathematical notion of period.)  Since it's not, the period is discarded and the equation for the critical points is solved using Reduce without the constraint of the period.  Reduce produces the indeterminate result:
Reduce[D[Cos[1 - x], x] == 0, x, Reals, WorkingPrecision -> ∞]
(*  C[1] ∈ Integers && (x == 1 - 2 π C[1] || x == 1 - π - 2 π C[1])  *)

ToRules is applied to this. Maximize assumes that if it does not evaluate to rules, then the problem has not been solved.  ToRules returns unevaluated.  In any case that's the nature of the bug.  It looks easy to fix (for WRI).

Update note -- I just realized my comment shows that it is possible to have complex-imaginary periods. This might lead to a case where the original fix of applying Abs to the period would mess things up.  I changed the fix so that only negative real numbers have their sign changed.


text:
Q: EF - Doing 'Include' on navigation properties when data is retrieved through a SP When using LINQ to retrieve data we can also get its navigation properties with an include as follows:
IQueryable<Location> locations = from c in ClientContext.Locations.Include("LocationType") select c;
        return locations;

How can we do the same, when we call a SP through the EF? I have a function import which returns the same object as the above query does:
return (IQueryable<Location>)ClientContext.GetLocationsPerUser(userId, getSubLocations);

How can I attach the LocationType entity to the above set? Is it possible or will I have to expose it from the SP itself?


text:
Q: Setting an environment variable in /etc/environment doesn't work but export does? So I'm trying to set an environment variable called "NODE_PATH",
It works by using:
export NODE_PATH=/home/myname/node

So I thought I'd set it up permanently and found that it needs to be done in the /etc/environment file.
After doing that and rebooting the machine, I ran:
echo $NODE_PATH

And the output is correct, yet node.js doesn't seem to like it.
But then, if I set it again using export, everything works fine.
I'd love to receive any input about the matter, is there a different functionality between the two that I'm not aware of?

A: Close the console you're using then open it again, worked for me.


text:
Q: Is functional promise chaining possible with TypeScript? It seems that in JavaScript one can do:
function extendPromise(promise) {
    return promise.then(new Promise(() => {}));
}

But if I add types, like
function extendTypeScriptPromise(promise: Promise<void>) {
    return promise.then(new Promise<void>(() => {}));
}

then the TypeScript compiler says:
error TS2345: Argument of type 'Promise<void>' is not assignable to parameter of type '((value: void) => void | PromiseLike<void>) | null | undefined'.
  Type 'Promise<void>' is not assignable to type '(value: void) => void | PromiseLike<void>'.
    Type 'Promise<void>' provides no match for the signature '(value: void): void | PromiseLike<void>'.

Why isn't a Promise<void> considered PromiseLike ?

A: Your JavaScript code is not quite how it should look like. The argument of Promise.then() must be a function, not a Promise.
This function can return a new Promise, void or a value (that is not a Promise) that is used to resolve the Promise whose .then() method is called. Apparently, in your code it must return a new Promise.
The correct JavaScript code is:
function extendPromise(promise) {
    return promise.then(() => new Promise(() => {}));
}

and the corresponding TypeScript code is:
function extendTypeScriptPromise(promise: Promise<void>) {
    return promise.then(() => new Promise<void>(() => {}));
}


text:
Q: Internal error when calling cakePHP app from network I have a CakePHP application running on a Apache server wich is currently working on the local loop. However when I call it with its network IP it throws an internal error. I mean:
When I call
   localhost/myApp

everything works fine.
However:
 192.168.x.x/myApp

Throws error 500:
Fatal Error
 Error: Call to undefined function curl_init()

Any idea or clue what could be wrong here?


text:
Q: Numpy rounding issue Can someone explain to me why is numpy round acting strange with this exact number rounding:
df = pd.DataFrame({'c': [121921117.714999988675115, 445, 22]})
df = np.round(df['c'], 8)

Result:
121921117.71499997
445.0
22.0

Expected:
121921117.71499999
445.0
22.0

It's obvious that the first number is not rounded well, any ideas?
EDIT:
Since I'm focused here on the precision, not so much on the performance, I've used python round function to solve this problem:
df.applymap(round, ndigits=8)

A: Check the small print 2 in the documentation of round aka around.
The short answer is that round "uses a fast but sometimes inexact algorithm" and to use format_float_positional if you want to see
the correct result.

>>> import pandas as pd
>>> df = pd.DataFrame({'c': [121921117.714999988675115, 445, 22]})
>>> df["c"][0]
121921117.71499999
>>> round(df["c"][0],8)
121921117.71499997
>>> np.format_float_positional(df["c"][0],8)
'121921117.71499999'


text:
Q: Only bulleted list shown when using 'simplexml_load_file()' in PHP to read RSS Feeds I only see bulleted list on a page when loading this script to read RSS feeds. What am I not doing right?

<title>RSS Feed Test</title>

<?php
    function fetchFeeds($url){
    $feed = simplexml_load_file($url);
    echo "
";
    foreach($feed->channel->item as $itementry){
    echo "
link' title='$itementry->title'.$itementry->title"."
";
    }
    echo "
";
    }
    echo fetchFeeds("http://rss.cnn.com/rss/cnn_topstories.rss");
    ?>

A: First off, you are not calling the proper rss url. That is just the homepage of the RSS feeds. You need to select one first. In this example, Top Stories is selected. Consider this example:
<?php

// top stories RSS
$rss_url = 'http://rss.cnn.com/rss/edition.rss';
$xml = simplexml_load_file($rss_url);
$title = (string) $xml->channel->title; // typecast the title
$items = array();
for($i = 0, $size = count($xml->channel->item); $i < $size; $i++) {
    // also one way to extract is to convert it to this
    // each item will become an array
    $items[] = json_decode(json_encode($xml->channel->item[$i]), true);
}

?>

<?php echo $title; ?>

<?php foreach($items as $key => $value): ?>

<?php echo $value['title']; ?>

<a href="<?php echo $value['link']; ?>"><?php echo $value['link']; ?>

<?php echo $value['description']; ?>

<?php echo $value['pubDate']; ?>

<?php endforeach; ?>

Sample Output


text:
Q: Activity's background become black when i entered in activity or onLongPress of Listview I am trying to implement one ListView in activity. In my XML there is a ListView to fill that ListView data I have invoked one WebService in AsynkTask. I have used BaseAdapter to set that ListView. Now, Whenever I came on that activity the background becomes black for fraction seconds of time and than disappear. Same things happened when I longpress on ListView. The screen shot had attached with this question as well as following are the code that I have implemented.
Main Activity's XML :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:background="@color/white"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.agraeta.user.btl.ComboOfferListActivity">

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="5dp"
    android:background="@color/strip_bg"
    android:textColor="@color/white"
    android:gravity="center"
    android:textSize="17sp"
    android:text="COMBO OFFERS"/>

<ListView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:scrollingCache="false"
    android:cacheColorHint="@color/white"
    android:id="@+id/list_comboOffers"
    android:background="@color/white"
    android:divider="@android:color/transparent"
    android:dividerHeight="5dp"/>

</LinearLayout>

Java File Of Main Activity :
public class ComboOfferListActivity extends AppCompatActivity implements Callback<ComboOfferData> {

ListView list_comboOffers;
ComboOfferListAdapter offerListAdapter;
List<ComboOfferItem> offerItemList=new ArrayList<>();
AdminAPI adminAPI;
Custom_ProgressDialog dialog;

String userID="";
String roleID="";
AppPrefs prefs;

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

    prefs=new AppPrefs(this);
    adminAPI=ServiceGenerator.getAPIServiceClass();
    dialog=new Custom_ProgressDialog(this,"Please Wait...");
    dialog.setCancelable(false);

    userID=prefs.getUserId();
    roleID=prefs.getUserRoleId();

    if(roleID.equals(C.ADMIN) || roleID.equals(C.COMP_SALES_PERSON) || roleID.equals(C.DISTRIBUTOR_SALES_PERSON)){
        roleID=prefs.getSubSalesId();
        userID=prefs.getSalesPersonId();
    }

    fetchIDs();
    setActionBar();
}

private void fetchIDs() {
    list_comboOffers=(ListView) findViewById(R.id.list_comboOffers);
    offerListAdapter=new ComboOfferListAdapter(offerItemList,ComboOfferListActivity.this);
    list_comboOffers.setAdapter(offerListAdapter);
    list_comboOffers.setCacheColorHint(Color.TRANSPARENT);
    list_comboOffers.requestFocus(0);
    list_comboOffers.setScrollingCacheEnabled(false);

    dialog.show();

    Log.e("UR",userID+"-->"+roleID);

    Call<ComboOfferData> offerDataCall=adminAPI.comboOfferDataCall(userID,roleID);
    offerDataCall.enqueue(this);

}

private void setActionBar() {

    // TODO Auto-generated method stub
    ActionBar mActionBar = getSupportActionBar();
    mActionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
    mActionBar.setCustomView(R.layout.actionbar_design);

    View mCustomView = mActionBar.getCustomView();
    ImageView image_drawer = (ImageView) mCustomView.findViewById(R.id.image_drawer);
    ImageView img_home = (ImageView) mCustomView.findViewById(R.id.img_home);
    ImageView img_notification = (ImageView) mCustomView.findViewById(R.id.img_notification);
    FrameLayout unread = (FrameLayout) mCustomView.findViewById(R.id.unread);

    image_drawer.setImageResource(R.drawable.ic_action_btl_back);

    img_home.setVisibility(View.GONE);
    img_notification.setVisibility(View.GONE);
    unread.setVisibility(View.GONE);

    image_drawer.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onBackPressed();
        }
    });

    mActionBar.setCustomView(mCustomView);
    mActionBar.setDisplayShowCustomEnabled(true);
}

@Override
public void onResponse(Call<ComboOfferData> call, Response<ComboOfferData> response) {
    dialog.dismiss();
    offerItemList.clear();
    ComboOfferData offerData=response.body();
    if(offerData.isStatus()){
        offerItemList.addAll(offerData.getOfferItemList());
    }
    else {
        Globals.Toast2(this,offerData.getMessage());
    }

    Log.e("Size","-->"+offerItemList.size());

    offerListAdapter.notifyDataSetChanged();
}

@Override
public void onFailure(Call<ComboOfferData> call, Throwable t) {
    dialog.dismiss();
    Globals.showError(t,this);
}

@Override
public void onBackPressed() {
    finish();
}
}

Adapter Class :
public class ComboOfferListAdapter extends BaseAdapter {

List<ComboOfferItem> offerItemList=new ArrayList<>();
Activity activity;
LayoutInflater inflater;

public ComboOfferListAdapter(List<ComboOfferItem> offerItemList, Activity activity) {
    this.offerItemList = offerItemList;
    this.activity = activity;
    inflater=activity.getLayoutInflater();
}

@Override
public int getCount() {
    return offerItemList.size();
}

@Override
public Object getItem(int position) {
    return offerItemList.get(position);
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    ViewHolder holder;
    if(convertView==null){

        holder=new ViewHolder();
        convertView=inflater.inflate(R.layout.layout_combooffer_list,parent,false);

        holder.img_offerThumb=(ImageView) convertView.findViewById(R.id.img_offerThumb);
        holder.txt_offerTitle=(TextView) convertView.findViewById(R.id.txt_offerTitle);
        holder.card_comboOffer = (CardView) convertView.findViewById(R.id.card_comboOffer);
        holder.layout_combo = (LinearLayout) convertView.findViewById(R.id.layout_combo);

        convertView.setTag(holder);
    }
    else {
        holder= (ViewHolder) convertView.getTag();
    }

    Picasso.with(activity).load(Globals.IMAGE_LINK+offerItemList.get(position).getImagePath())
            .into(holder.img_offerThumb);

    holder.txt_offerTitle.setText(offerItemList.get(position).getOfferTitle());

    holder.img_offerThumb.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(activity, ComboOfferActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.putExtra("combo_id", offerItemList.get(position).getOfferID());
            activity.startActivity(intent);
        }
    });

    holder.txt_offerTitle.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(activity, ComboOfferActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.putExtra("combo_id", offerItemList.get(position).getOfferID());
            activity.startActivity(intent);
        }
    });

    return convertView;
}

@Override
public void notifyDataSetChanged() {
    super.notifyDataSetChanged();

    Log.e("Called","-->"+offerItemList.size());
}

private class ViewHolder {
    ImageView img_offerThumb;
    TextView txt_offerTitle;
    CardView card_comboOffer;
    LinearLayout layout_combo;
}
}

Layout File For Adapter's View :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/white"
android:orientation="vertical">

<android.support.v7.widget.CardView
    android:id="@+id/card_comboOffer"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="5dp"
    android:orientation="vertical"
    cardBackgroundColor="#fff"
    app:cardCornerRadius="2dp"
    app:cardElevation="5dp"
    app:theme="@style/CardView.Dark">

    <LinearLayout
        android:id="@+id/layout_combo"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <ImageView
            android:id="@+id/img_offerThumb"
            android:layout_width="wrap_content"
            android:layout_height="150dp"
            android:layout_gravity="center"
            android:background="?attr/selectableItemBackgroundBorderless"
            android:clickable="true"
            android:scaleType="fitXY"/>

        <TextView
            android:id="@+id/txt_offerTitle"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="#f58634"
            android:padding="5dp"
            android:textColor="@color/white"
            android:layout_gravity="center"
            android:textSize="15sp"/>

    </LinearLayout>

</android.support.v7.widget.CardView>


text:
Q: How to get headers when url is called? [ Angular5 ] I want to get request headers when URL is called.
When user clicked link button, this button trigger to run angular application in a new window. and this button send user email, password and token in headers of request. I want to get request headers but I don't know how to get when URL is accessed. I searched and find to how to get headers when call api in service but no article how to get headers through angular routes.


text:
Q: Showing Existence of a Solution for Differential Equation I'm doing MIT OCW's Honors Differential Equations course (18.034) from 2009 as an independent study for school. I came across the following problem on Problem Set 2 and it confused me:

*Suppose that $f$ be a continuous bounded function for the entire real axis. If $f'$ is continuous,
then show that the nonzero solution of the initial value problem of $y' = yf\left(y\right)$ with $y\left(0\right) = y_0 \ne 0$
exists for all x. (You may need to assume the uniqueness theorem.

My first instinct was to rearrange then integrate, getting to $\int_{y_0}^y \frac{dt}{tf\left(t\right)} = x$. However, I do not know if the left side is integrable because the function $f$ may equal $0$ over the interval. Even if this is not the case, then suppose $\frac{1}{yf\left(y\right)}$ has antiderivative $H\left(y\right)$. Then, $H\left(y\right) = x + H\left(y_0\right) \implies y = H^{-1}(x + H\left(y_0\right))$. However, I wasn't sure if could assume that $H^{-1}$ is defined for all inputs, so with this uncertainty I wouldn't be able to determine from this that the solution exists for all x.
Eventually I looked at the solution given on OCW's website and was able to follow it for the most part. I know $f$ being bounded implies $|f| ≤ M$ for some nonnegative $M$. So $\frac{y'}{y} ≤ |f\left(y\right)| ≤ M$, or $\frac{d}{dx}(\ln |y|) ≤ M$. This implies that $\ln |y| - \ln |y_0| ≤ Mx$, so $|y\left(x\right)| ≤ |y_0|e^{Mx}$. Then, we consider the rectangle where $|x| ≤ a$ and $|y| ≤ |y_0|e^{Mx}$ for some positive $a$.
I am able to follow the given solution up until that point, but here is the part the confused me. Suppose the solution does not exist over the interval $|x| < a$. Then, $|y\left(a\right)| = |y_0|e^{Ma}$. After this, the solution finishes with "[t]his contradicts (??)." I thought the (??) may be a formatting error so I assume it means (1), which refers to $|y\left(x\right)| ≤ |y_0|e^{Mx}$; however, I don't see how the equality would contradict this inequality.
What exactly would the contradiction be here? Or, is there a better way to approach this problem?

A: You can use argument by contradiction to show. By the Picard theorem, there is $x_0>0$ such that the equation has a unique solution $y(x)$ in $[0,x_0]$. Extends this solution to the maximal interval $[0, x_0)$ (still use $x_0$). Now either $x_0=\infty$ or $x_0$ is finite. If $x_0=\infty$, it is done. Otherwise $x_0<\infty$ and then we must have
$$ \lim_{x\to x_0^-} |y(x)|=\infty. \tag 1$$
On the other hand, from the equation, we have
$$ \frac{y'}{y}=f(y) $$
which gives after integrating from $0$ from $x\in(0,x_0)$
$$ \ln|y(x)|-\ln|y_0|=\int_0^{x} f(y(t))dt\le \int_0^{x} |f(y(t))|dt\le Mx $$
where $f(x)$ is supposed to be bounded so that there is $M>0$ such that $|f(x)|\le M$. So
$$ |y(x)|\le|y_0| e^{Mx}. $$
Thus
$$\lim_{x\to x_0^-} |y(x)|\le |y_0| e^{Mx_0} $$
which is against (1).


text:
Q: Non-martingale with respected to the natural filtration, and satisfies $E[M_{n+1} | M_n]=M_n$ I am thinking about the exercise:
Exercise 5. Give an example of a random sequence ($M_n$)
such that $E[ M_{n+1} | M_n ] = M_n$ for all
$n\ge0$, but which is not a martingale w.r.t. the filtration $F_n = \sigma(M_0, \dots , M_n)$.
From Exercise 5 of Link :
http://www.math.bme.hu/~gabor/oktatas/SztoM/StModHW_2014.pdf


text:
Q: Music and sound effects don't play on win32 platform? (cocos2d-x) When I run my game on win32 platform, my sounds don't play. But sounds are playing normally in android platform.
I'm using:
auto audio = CocosDenshion::SimpleAudioEngine::getInstance();
audio->playEffect("sounds/jump.ogg");

How can fix this? thanks

A: According to cocos2d-x wiki,  .mid and .wav only supported on window desktop.
Sound Effects
|    Platform     |   supported sound effects formats   |
|-----------------|:-----------------------------------:|
| Android Supports|         .ogg , .wav format.         |
| iOS             |          .mp3, .wav, .caf           |
| Windows Desktop |         .mid and .wav only          |

Above file format table is for SimpleAudioEngine, currently I am using .ogg file on win32 desktop with new experimental AudioEngine
#include "audio/include/AudioEngine.h"

experimental::AudioEngine::play2d("sounds/jump.ogg", false, 1.0);


text:
Q: Can I do this with the :hover pseudo class? I'm familiar with the :hover psuedo class and using it for elements as well as the typical link setup we're all used to. What I am trying to do however is create a situation where hover over one element would change properties of another. For instance if I were to hover over .block1, #block2 would become visible. I would think the .css would look like something this...
.block1:hover div#block2
{
    visibility:visible;
}

but that's getting me nowhere. Thoughts? I know that I could probably use javascript to make this happen (make elements appear and disappear) but I would love to find a pure css solution to this.

A: The element you want to change has to be a child element of the one you are hovering over.
Example CSS:
#navButton div.text {
    display:none;
}

#navButton:hover div.text {
    display:block;
}

This will make the text div display if you hover over the element with id="navButton".
Otherwise, use a JQuery solution:
CSS:
#navButton div.text {
    display:none;
}

.hover {
    display:block;
}

Javascript:
$("#navButton").hover(
    function () {
        $("#navButton div.text").addClass("hover");
    },
    function () {
        $("#navButton div.text").removeClass("hover");
    }
);

Edit:
You can also do this for sibling elements in CSS if the hovered element precedes the element you want to modify. Like so:
#navButton + div.text {
    display:none;
}

#navButton:hover + div.text {
    display:block;
}

OR
#navButton ~ div.text {
    display:none;
}

#navButton:hover ~ div.text {
    display:block;
}

A: If that second element is a descendent of the first, then it will work.
jsFiddle.