问:
Making text width flexible with ttf font
I am inquiring about two things. First I am having an ttf file and it is located in my macair drive. I do not want to add that file into my project structure. How can i import the True_type font from it. I have tried various ways to import it my Java program. e.g. public class TextFixer {

    private static String[] names = { "iksswgrg.ttf" };  //this exists on my macair drive and i want to create font from it.

```<code>  private static Map<String, Font> cache = new ConcurrentHashMap<String, Font>(names.length);
  static {
    for (String name : names) {
      cache.put(name, getFont(name));
    }
  }
  public static Font getFont(String name) {
    Font font = null;
    if (cache != null) {
      if ((font = cache.get(name)) != null) {
        return font;
      }
    }
    String fName = "/fonts/" + name;
    try {
      InputStream is = TextFixer.class.getResourceAsStream(fName);
      font = new Font("ttf", 0, 16);
      //font = Font.createFont(Font.TRUETYPE_FONT, is);
    } catch (Exception ex) {
      ex.printStackTrace();
      System.err.println(fName + " not loaded.  Using serif font.");
      font = new Font("serif", Font.PLAIN, 24);
    }
    return font;
  }
</code>```

2nd part is I want to create a String by using Graphics. First I need to have width that is of 130mm. The height of the displayed box will be the tallest character in the provided string. The font size is between 8 and 16. I have an enterprise project which take care of the height and size of the ttf. The problem i face is: I do not want to use swing/javafx libraries. I want to use Graphics library of Java, use Graphics2D to have a rectangle. How can i set its width to be precisely 130mm? Then I want to make that width flexible with according to the Font. I want to draw a string and the string should get adjusted/being flexible in the provided width. I am able to draw a string through g.drawString() but I am unable to see it on console. As I do not want to use Jframe or any Swing/javaFX libraries.
I know this seems a bit long but I hope I have explained it well enough. I desperately need help. Please let me know if you guys can help me out here.
Thanks in advance

答:
First I am having an ttf file and it is located in my macair drive. I do not want to add that file into my project structure. How can i import the True_type font from it

This is more of a problem to do with "How do you reference a file on the file system" then "How do I load a font", because if you can solve the first, you can solve the second.

```<code>File fontFile = new File("some/relative/path/to/your/Font.tff");
</code>```

or

```<code>File fontFile = new File("/some/absolute/path/to/your/Font.tff");
</code>```

Personally, I like neither, as it it causes too much trouble (working directories, other systems, etc), I prefer to use embedded resources where possible or put the files in a common location.

For example {user.home}/AppData/Local/{application name} on Windows or on Mac you could use {user.home}/Library/Application Support/{application name}, then it doesn't matter where the program is executed from

Loading the font is relatively simple.  For my example, I placed the font file in the working directory of the program

```<code>System.out.println(new File("Pacifico.ttf").exists());
Font font = Font.createFont(Font.TRUETYPE_FONT, new File("Pacifico.ttf"));
</code>```

2nd part is I want to create a String by using Graphics. First I need to have width that is of 130mm. The height of the displayed box will be the tallest character in the provided string

This is much more complicated, as images are measured in pixels.  In order to know how many pixels make up a given distance, we need to know the DPI of the image.

its 72DPI

Okay then, from that, we can calculate the number of pixels we need

```<code>public static double cmToPixel(double cm, double dpi) {
    return (dpi / 2.54) * cm;
}
</code>```

130mm (13 cm) comes out to be 368.503937007874 @ 72dpi.

From this, we need to find the font point size for a given piece of text to fit within this range.

Now, there are a number of was you can do this, you could simply start at point 1 and perform a linear progression till you pass the range you're after.  It's not exactly fast and, as you increase the size, it can become a little error prone.

I've opted for more of a divide and conquer approach

```<code>protected static int widthOfText(String text, Font font, float fontSize, Graphics2D g2d) {
    font = font.deriveFont(fontSize);
    FontMetrics fm = g2d.getFontMetrics(font);
    int textWidth = fm.stringWidth(text);
    return textWidth;
}

public static Float pointToFit(double width, String text, Font font, Graphics2D g2d, float min, float max) {
    float fontSize = min + ((max - min) / 2f);
    font = font.deriveFont(fontSize);
    FontMetrics fm = g2d.getFontMetrics(font);
    int textWidth = fm.stringWidth(text);

    if (fontSize == min || fontSize == max) {
        return fontSize;
    }

    if (textWidth < width) {
        return pointToFit(width, text, font, g2d, fontSize, max);
    } else if (textWidth > width) {
        return pointToFit(width, text, font, g2d, min, fontSize);
    }
    return fontSize;
}
</code>```

Important to note, it's not perfect, but it betters a linear progression :P

With this in hand, we can start calculating the required properties we need...

```<code>String text = "Happy, Happy, Joy, Joy";
double width = cmToPixel(13.0, 72.0);

BufferedImage img = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = img.createGraphics();
float fontSize = pointToFit(width, text, font, g2d, 0, (float)width);

font = font.deriveFont(fontSize);
FontMetrics fm = g2d.getFontMetrics(font);
int height = fm.getHeight();
g2d.dispose();
</code>```

Okay, so this creates a small (1x1) temporary image.  We need Graphics context in order to calculate all the other properties.  It then calculates the font point size, from it can then calculate the text height

With all that information in hand, we can get around to actually rendering the text...

```<code>img = new BufferedImage((int) Math.round(width), height, BufferedImage.TYPE_INT_ARGB);
g2d = img.createGraphics();
g2d.setFont(font);
fm = g2d.getFontMetrics();
g2d.setColor(Color.BLACK);
g2d.drawString(text, 0, fm.getAscent());
g2d.dispose();
</code>```

Which will eventually output something like this...

I added the red border before I rendered the text so I could see how well it fitted.

Now, this is a really basic example, what this doesn't do is tell you when the text won't fit (ie, the point size is 1 or 0), you'll have to put traps in to catch that yourself

And, because I know you'll probably have lots of fun putting it together, my test code...

```<code>import java.awt.Color;
import java.awt.Font;
import java.awt.FontFormatException;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.GraphicsEnvironment;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.NumberFormat;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;

public class Test {

    public static void main(String[] args) {
        try {
            System.out.println(new File("Pacifico.ttf").exists());
            GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
            Font font = Font.createFont(Font.TRUETYPE_FONT, new File("Pacifico.ttf"));

            String text = "Happy, Happy, Joy, Joy";
            double width = cmToPixel(13.0, 72.0);
            BufferedImage img = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
            Graphics2D g2d = img.createGraphics();
            float fontSize = pointToFit(width, text, font, g2d, 0, (float) width);
            System.out.println(width);
            System.out.println(fontSize);
            font = font.deriveFont(fontSize);
            FontMetrics fm = g2d.getFontMetrics(font);
            int height = fm.getHeight();
            g2d.dispose();

            img = new BufferedImage((int) Math.round(width), height, BufferedImage.TYPE_INT_ARGB);
            g2d = img.createGraphics();
            g2d.setColor(Color.RED);
            g2d.drawRect(0, 0, img.getWidth() - 1, img.getHeight() - 1);
            g2d.setFont(font);
            fm = g2d.getFontMetrics();
            g2d.setColor(Color.BLACK);
            g2d.drawString(text, 0, fm.getAscent());
            g2d.dispose();

            JOptionPane.showConfirmDialog(null, new ImageIcon(img));
        } catch (IOException | FontFormatException e) {
            //Handle exception
        }
    }

    public static Float pointToFit(double width, String text, Font font, Graphics2D g2d) {
        return pointToFit(width, text, font, g2d, 0f, Float.MAX_VALUE);
    }

    protected static int widthOfText(String text, Font font, float fontSize, Graphics2D g2d) {
        font = font.deriveFont(fontSize);
        FontMetrics fm = g2d.getFontMetrics(font);
        int textWidth = fm.stringWidth(text);
        return textWidth;
    }

    public static Float pointToFit(double width, String text, Font font, Graphics2D g2d, float min, float max) {
        float fontSize = min + ((max - min) / 2f);
        NumberFormat nf = NumberFormat.getInstance();
        font = font.deriveFont(fontSize);
        FontMetrics fm = g2d.getFontMetrics(font);
        int textWidth = fm.stringWidth(text);

        if (fontSize == min || fontSize == max) {
            return fontSize;
        }

        if (textWidth < width) {
            return pointToFit(width, text, font, g2d, fontSize, max);
        } else if (textWidth > width) {
            return pointToFit(width, text, font, g2d, min, fontSize);
        }
        return fontSize;
    }

    public static double cmToPixel(double cm, double dpi) {
        return (dpi / 2.54) * cm;
    }

}
</code>```

Body:
I am inquiring about two things. First I am having an ttf file and it is located in my macair drive. I do not want to add that file into my project structure. How can i import the True_type font from it. I have tried various ways to import it my Java program. e.g. public class TextFixer {

    private static String[] names = { "iksswgrg.ttf" };  //this exists on my macair drive and i want to create font from it.

  private static Map<String, Font> cache = new ConcurrentHashMap<String, Font>(names.length);
  static {
    for (String name : names) {
      cache.put(name, getFont(name));
    }
  }
  public static Font getFont(String name) {
    Font font = null;
    if (cache != null) {
      if ((font = cache.get(name)) != null) {
        return font;
      }
    }
    String fName = "/fonts/" + name;
    try {
      InputStream is = TextFixer.class.getResourceAsStream(fName);
      font = new Font("ttf", 0, 16);
      //font = Font.createFont(Font.TRUETYPE_FONT, is);
    } catch (Exception ex) {
      ex.printStackTrace();
      System.err.println(fName + " not loaded.  Using serif font.");
      font = new Font("serif", Font.PLAIN, 24);
    }
    return font;
  }

2nd part is I want to create a String by using Graphics. First I need to have width that is of 130mm. The height of the displayed box will be the tallest character in the provided string. The font size is between 8 and 16. I have an enterprise project which take care of the height and size of the ttf. The problem i face is: I do not want to use swing/javafx libraries. I want to use Graphics library of Java, use Graphics2D to have a rectangle. How can i set its width to be precisely 130mm? Then I want to make that width flexible with according to the Font. I want to draw a string and the string should get adjusted/being flexible in the provided width. I am able to draw a string through g.drawString() but I am unable to see it on console. As I do not want to use Jframe or any Swing/javaFX libraries.
I know this seems a bit long but I hope I have explained it well enough. I desperately need help. Please let me know if you guys can help me out here.
Thanks in advance

Body:
First I am having an ttf file and it is located in my macair drive. I do not want to add that file into my project structure. How can i import the True_type font from it

This is more of a problem to do with "How do you reference a file on the file system" then "How do I load a font", because if you can solve the first, you can solve the second.

File fontFile = new File("some/relative/path/to/your/Font.tff");

or

File fontFile = new File("/some/absolute/path/to/your/Font.tff");

Personally, I like neither, as it it causes too much trouble (working directories, other systems, etc), I prefer to use embedded resources where possible or put the files in a common location.

For example {user.home}/AppData/Local/{application name} on Windows or on Mac you could use {user.home}/Library/Application Support/{application name}, then it doesn't matter where the program is executed from

Loading the font is relatively simple.  For my example, I placed the font file in the working directory of the program

System.out.println(new File("Pacifico.ttf").exists());
Font font = Font.createFont(Font.TRUETYPE_FONT, new File("Pacifico.ttf"));

2nd part is I want to create a String by using Graphics. First I need to have width that is of 130mm. The height of the displayed box will be the tallest character in the provided string

This is much more complicated, as images are measured in pixels.  In order to know how many pixels make up a given distance, we need to know the DPI of the image.

its 72DPI

Okay then, from that, we can calculate the number of pixels we need

public static double cmToPixel(double cm, double dpi) {
    return (dpi / 2.54) * cm;
}

130mm (13 cm) comes out to be 368.503937007874 @ 72dpi.

From this, we need to find the font point size for a given piece of text to fit within this range.

Now, there are a number of was you can do this, you could simply start at point 1 and perform a linear progression till you pass the range you're after.  It's not exactly fast and, as you increase the size, it can become a little error prone.

I've opted for more of a divide and conquer approach

protected static int widthOfText(String text, Font font, float fontSize, Graphics2D g2d) {
    font = font.deriveFont(fontSize);
    FontMetrics fm = g2d.getFontMetrics(font);
    int textWidth = fm.stringWidth(text);
    return textWidth;
}

public static Float pointToFit(double width, String text, Font font, Graphics2D g2d, float min, float max) {
    float fontSize = min + ((max - min) / 2f);
    font = font.deriveFont(fontSize);
    FontMetrics fm = g2d.getFontMetrics(font);
    int textWidth = fm.stringWidth(text);

    if (fontSize == min || fontSize == max) {
        return fontSize;
    }

    if (textWidth < width) {
        return pointToFit(width, text, font, g2d, fontSize, max);
    } else if (textWidth > width) {
        return pointToFit(width, text, font, g2d, min, fontSize);
    }
    return fontSize;
}

Important to note, it's not perfect, but it betters a linear progression :P

With this in hand, we can start calculating the required properties we need...

String text = "Happy, Happy, Joy, Joy";
double width = cmToPixel(13.0, 72.0);

BufferedImage img = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = img.createGraphics();
float fontSize = pointToFit(width, text, font, g2d, 0, (float)width);

font = font.deriveFont(fontSize);
FontMetrics fm = g2d.getFontMetrics(font);
int height = fm.getHeight();
g2d.dispose();

Okay, so this creates a small (1x1) temporary image.  We need Graphics context in order to calculate all the other properties.  It then calculates the font point size, from it can then calculate the text height

With all that information in hand, we can get around to actually rendering the text...

img = new BufferedImage((int) Math.round(width), height, BufferedImage.TYPE_INT_ARGB);
g2d = img.createGraphics();
g2d.setFont(font);
fm = g2d.getFontMetrics();
g2d.setColor(Color.BLACK);
g2d.drawString(text, 0, fm.getAscent());
g2d.dispose();

Which will eventually output something like this...

I added the red border before I rendered the text so I could see how well it fitted.

Now, this is a really basic example, what this doesn't do is tell you when the text won't fit (ie, the point size is 1 or 0), you'll have to put traps in to catch that yourself

And, because I know you'll probably have lots of fun putting it together, my test code...

import java.awt.Color;
import java.awt.Font;
import java.awt.FontFormatException;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.GraphicsEnvironment;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.NumberFormat;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;

public class Test {

    public static void main(String[] args) {
        try {
            System.out.println(new File("Pacifico.ttf").exists());
            GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
            Font font = Font.createFont(Font.TRUETYPE_FONT, new File("Pacifico.ttf"));

            String text = "Happy, Happy, Joy, Joy";
            double width = cmToPixel(13.0, 72.0);
            BufferedImage img = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
            Graphics2D g2d = img.createGraphics();
            float fontSize = pointToFit(width, text, font, g2d, 0, (float) width);
            System.out.println(width);
            System.out.println(fontSize);
            font = font.deriveFont(fontSize);
            FontMetrics fm = g2d.getFontMetrics(font);
            int height = fm.getHeight();
            g2d.dispose();

            img = new BufferedImage((int) Math.round(width), height, BufferedImage.TYPE_INT_ARGB);
            g2d = img.createGraphics();
            g2d.setColor(Color.RED);
            g2d.drawRect(0, 0, img.getWidth() - 1, img.getHeight() - 1);
            g2d.setFont(font);
            fm = g2d.getFontMetrics();
            g2d.setColor(Color.BLACK);
            g2d.drawString(text, 0, fm.getAscent());
            g2d.dispose();

            JOptionPane.showConfirmDialog(null, new ImageIcon(img));
        } catch (IOException | FontFormatException e) {
            //Handle exception
        }
    }

    public static Float pointToFit(double width, String text, Font font, Graphics2D g2d) {
        return pointToFit(width, text, font, g2d, 0f, Float.MAX_VALUE);
    }

    protected static int widthOfText(String text, Font font, float fontSize, Graphics2D g2d) {
        font = font.deriveFont(fontSize);
        FontMetrics fm = g2d.getFontMetrics(font);
        int textWidth = fm.stringWidth(text);
        return textWidth;
    }

    public static Float pointToFit(double width, String text, Font font, Graphics2D g2d, float min, float max) {
        float fontSize = min + ((max - min) / 2f);
        NumberFormat nf = NumberFormat.getInstance();
        font = font.deriveFont(fontSize);
        FontMetrics fm = g2d.getFontMetrics(font);
        int textWidth = fm.stringWidth(text);

        if (fontSize == min || fontSize == max) {
            return fontSize;
        }

        if (textWidth < width) {
            return pointToFit(width, text, font, g2d, fontSize, max);
        } else if (textWidth > width) {
            return pointToFit(width, text, font, g2d, min, fontSize);
        }
        return fontSize;
    }

    public static double cmToPixel(double cm, double dpi) {
        return (dpi / 2.54) * cm;
    }

}


来源: stackexchange

问:
react native fullwidth background image 'Android'
I used image as container to have a fullwidth background. It runs correctly in emulator, but when I open application on the device, background is white.
Thank you for attantion</p>

```<code><Container>
    <Content>
      <Image
        style={styles.bgImage}
        source={require('../../../images/login_bg.png')}>
        <View style={styles.wrapper}>
          <Image
            style={styles.logo}
            source={require('../../../images/logo.png')} />
          <Button
            style={styles.button}
            onPress={() => {this.logIn(username, password)}}>
            <Text style={styles.buttonText}>LOGIN</Text>
          </Button>
        </View>
        <View style={styles.footer}>
          <Text style={styles.version}>Version 4.0.0</Text>
          <Text style={styles.copyright}>© All rights reserved. Araqich is registered trademark of Araqich LLC.</Text>
        </View>
      </Image>
    </Content>
  </Container>
</code>```

答:
I think if you use alignSelf: 'stretch'
it will work

ContentLicense: CC BY-SA 3.0

Body:
I used image as container to have a fullwidth background. It runs correctly in emulator, but when I open application on the device, background is white.
Thank you for attantion

<Container>
    <Content>
      <Image
        style={styles.bgImage}
        source={require('../../../images/login_bg.png')}>
        <View style={styles.wrapper}>
          <Image
            style={styles.logo}
            source={require('../../../images/logo.png')} />
          <Button
            style={styles.button}
            onPress={() => {this.logIn(username, password)}}>
            <Text style={styles.buttonText}>LOGIN</Text>
          </Button>
        </View>
        <View style={styles.footer}>
          <Text style={styles.version}>Version 4.0.0</Text>
          <Text style={styles.copyright}>© All rights reserved. Araqich is registered trademark of Araqich LLC.</Text>
        </View>
      </Image>
    </Content>
  </Container>


问:
Better way to handle slow internet in retrofit
I am using Retrofit library for api's .I just want to know better way to handle slow internet.
Should i handle the timeout in error or should i download some file from the internet & calculate how long it took vs number of bytes in the file ?

Currently i am handling SocketTimeoutException and SocketException in onFailure.
Thanx in advance.

答:
Try this :     </p>

```<code>Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BuildConfig.SERVER_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .client(new OkHttpClient().newBuilder()
                        .connectTimeout(30, TimeUnit.SECONDS)
                        .readTimeout(30, TimeUnit.SECONDS)
                        .writeTimeout(30, TimeUnit.SECONDS)
                        .build())
                .build();
</code>```

Body:
Try this :

Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BuildConfig.SERVER_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .client(new OkHttpClient().newBuilder()
                        .connectTimeout(30, TimeUnit.SECONDS)
                        .readTimeout(30, TimeUnit.SECONDS)
                        .writeTimeout(30, TimeUnit.SECONDS)
                        .build())
                .build();


问:
Iterating object array within object - javascript?
I know iteration has been covered before - I'm usually pretty ok with it but struggling this time.

I have the following information I'm trying to loop through:

```<code>Object { leaving: object { all: array[10] } }
</code>```

I can quite easily return a single result by returning:

```<code> var html = '<p>' + news.leaving.all[0].departure_time + '</p>';
</code>```

But when I try to loop:

```<code>    var html = "";
    var i;
    for (i = 0; i < news.length; i++) {
        html +=
        '<p>' + news[i].leaving.all.departure_time '</p>';
     }
</code>```

I get nothing…

Any help with this will be great.

Thanks

答:
It looks like you need

```<code>'<p>' + news.leaving.all[i].departure_time '</p>';
</code>```

rather than

```<code> '<p>' + news[i].leaving.all.departure_time '</p>';
</code>```

and change also

```<code>for (i = 0; i < news.length; i++) {
</code>```

to

```<code>for (i = 0; i < news.leaving.all.length; i++) {
</code>```

Body:
I know iteration has been covered before - I'm usually pretty ok with it but struggling this time.

I have the following information I'm trying to loop through:

Object { leaving: object { all: array[10] } }

I can quite easily return a single result by returning:

 var html = '
' + news.leaving.all[0].departure_time + '
';

But when I try to loop:

    var html = "";
    var i;
    for (i = 0; i < news.length; i++) {
        html +=
        '
' + news[i].leaving.all.departure_time '
';
     }

I get nothing…

Any help with this will be great.

Thanks

Body:
It looks like you need

'<p>' + news.leaving.all[i].departure_time '</p>';

rather than

 '<p>' + news[i].leaving.all.departure_time '</p>';

and change also

for (i = 0; i < news.length; i++) {

to

for (i = 0; i < news.leaving.all.length; i++) {


问:
How to decrypt the encrypted string coming from python?
I get a encrypted base64 string from python. The format is AES 256 CBC. But when I try to decrypt using iOS Swift it return decrypted string as nil.

```<code># coding=utf-8
import base64
from random import choice
from string import letters

try:
    from Crypto import Random
    from Crypto.Cipher import AES
except ImportError:
    import crypto
    import sys

    sys.modules['Crypto'] = crypto
    from crypto.Cipher import AES
    from crypto import Random

class AESCipher(object):
    def __init__(self, key):
        self.bs = 32
        self.key = key

    def encrypt(self, raw):
        _raw = raw
        raw = self._pad(raw)

        print raw, ';'
        print _raw, ';'

        iv = "".join([choice(letters[:26]) for i in xrange(16)])
        print " iv :", iv
        cipher = AES.new(self.key, AES.MODE_CBC, iv)
        return base64.b64encode(iv + cipher.encrypt(raw))

    def decrypt(self, enc):
        enc = base64.b64decode(enc)
        iv = enc[:AES.block_size]
        cipher = AES.new(self.key, AES.MODE_CBC, iv)
        return self._unpad(cipher.decrypt(enc[AES.block_size:])).decode('utf-8')

    def _pad(self, s):
        a = (self.bs - len(s) % self.bs)
        b = chr(self.bs - len(s) % self.bs)
        return s + a * b

    @staticmethod
    def _unpad(s):
        return s[:-ord(s[len(s) - 1:])]
def encrypt(k, t):
    o = AESCipher(k)
    return o.encrypt(t)

def decrypt(k, t):
    o = AESCipher(k)
    return o.decrypt(t)

def main():
    k = "qwertyuiopasdfghjklzxcvbnmqwerty"
    s1 = "Hello World!"

    d2 = encrypt(k, s1)

    print " Password :", k
    print "Encrypted :", d2
    print "    Plain :", decrypt(k, d2)

if __name__ == '__main__':
    main()
</code>```

iOS

Here I use AES256CBC Lib https://github.com/SwiftyBeaver/AES256CBC

```<code>let decrypted = AES256CBC.decryptString("Ymdqc3ZqdmZ1cXdsZG1sZenhgr4Xt0+ceARYRh1n40QkNDV/dyKbQjYLcbiXBBeO", password: "qwertyuiopasdfghjklzxcvbnmqwerty")

        print("decrypted: \(String(describing: decrypted))") // here I get nil
</code>```

when python run I get this Logs

```<code>iv : bgjsvjvfuqwldmle
 Password : qwertyuiopasdfghjklzxcvbnmqwerty
Encrypted : Ymdqc3ZqdmZ1cXdsZG1sZenhgr4Xt0+ceARYRh1n40QkNDV/dyKbQjYLcbiXBBeO
    Plain : Hello World!
</code>```

I don't know why python and iOS not same in AES. Anyone solve this issue please put answer below. Thanks in advance.

答:
I think you need to decode your base64 string first.
Maybe this will work (just googled it, I'm not a iOS dev, so I'm sorry to eventual errors)

```<code>let decodedData = NSData("Ymdqc3ZqdmZ1cXdsZG1sZenhgr4Xt0+ceARYRh1n40QkNDV/dyKbQjYLcbiXBBeO": base64String, options:NSDataBase64DecodingOptions.fromRaw(0)!)
let decodedString = NSString(data: decodedData, encoding: NSUTF8StringEncoding)
let decrypted = AES256CBC.decryptString(decodedString, password: "qwertyuiopasdfghjklzxcvbnmqwerty")
        print("decrypted: \(String(describing: decrypted))")
</code>```

It's also stated in the documentation

Body:
I get a encrypted base64 string from python. The format is AES 256 CBC. But when I try to decrypt using iOS Swift it return decrypted string as nil.

# coding=utf-8
import base64
from random import choice
from string import letters

try:
    from Crypto import Random
    from Crypto.Cipher import AES
except ImportError:
    import crypto
    import sys

    sys.modules['Crypto'] = crypto
    from crypto.Cipher import AES
    from crypto import Random

class AESCipher(object):
    def __init__(self, key):
        self.bs = 32
        self.key = key

    def encrypt(self, raw):
        _raw = raw
        raw = self._pad(raw)

        print raw, ';'
        print _raw, ';'

        iv = "".join([choice(letters[:26]) for i in xrange(16)])
        print " iv :", iv
        cipher = AES.new(self.key, AES.MODE_CBC, iv)
        return base64.b64encode(iv + cipher.encrypt(raw))

    def decrypt(self, enc):
        enc = base64.b64decode(enc)
        iv = enc[:AES.block_size]
        cipher = AES.new(self.key, AES.MODE_CBC, iv)
        return self._unpad(cipher.decrypt(enc[AES.block_size:])).decode('utf-8')

    def _pad(self, s):
        a = (self.bs - len(s) % self.bs)
        b = chr(self.bs - len(s) % self.bs)
        return s + a * b

    @staticmethod
    def _unpad(s):
        return s[:-ord(s[len(s) - 1:])]
def encrypt(k, t):
    o = AESCipher(k)
    return o.encrypt(t)

def decrypt(k, t):
    o = AESCipher(k)
    return o.decrypt(t)

def main():
    k = "qwertyuiopasdfghjklzxcvbnmqwerty"
    s1 = "Hello World!"

    d2 = encrypt(k, s1)

    print " Password :", k
    print "Encrypted :", d2
    print "    Plain :", decrypt(k, d2)

if __name__ == '__main__':
    main()

iOS

Here I use AES256CBC Lib https://github.com/SwiftyBeaver/AES256CBC

let decrypted = AES256CBC.decryptString("Ymdqc3ZqdmZ1cXdsZG1sZenhgr4Xt0+ceARYRh1n40QkNDV/dyKbQjYLcbiXBBeO", password: "qwertyuiopasdfghjklzxcvbnmqwerty")

        print("decrypted: \(String(describing: decrypted))") // here I get nil

when python run I get this Logs

iv : bgjsvjvfuqwldmle
 Password : qwertyuiopasdfghjklzxcvbnmqwerty
Encrypted : Ymdqc3ZqdmZ1cXdsZG1sZenhgr4Xt0+ceARYRh1n40QkNDV/dyKbQjYLcbiXBBeO
    Plain : Hello World!

I don't know why python and iOS not same in AES. Anyone solve this issue please put answer below. Thanks in advance.

Body:
I think you need to decode your base64 string first.
Maybe this will work (just googled it, I'm not a iOS dev, so I'm sorry to eventual errors)

let decodedData = NSData("Ymdqc3ZqdmZ1cXdsZG1sZenhgr4Xt0+ceARYRh1n40QkNDV/dyKbQjYLcbiXBBeO": base64String, options:NSDataBase64DecodingOptions.fromRaw(0)!)
let decodedString = NSString(data: decodedData, encoding: NSUTF8StringEncoding)
let decrypted = AES256CBC.decryptString(decodedString, password: "qwertyuiopasdfghjklzxcvbnmqwerty")
        print("decrypted: \(String(describing: decrypted))")

It's also stated in the documentation


问:
passing functions as arguments in ruby
I'm trying to wrap my head around functional programming in ruby and there doesn't seem to be much good documentation out there.

Essentially, I'm trying to write a combine function that would have a Haskell type signature of:

```<code>[a] -> [a] -> (a -> a -> a) -> [a]
</code>```

So

```<code>combine([1,2,3], [2,3,4], plus_func) => [3,5,7]
combine([1,2,3], [2,3,4], multiply_func) => [2,6,12]
</code>```

etc.

I found some stuff about using zip and map but that feels really ugly to use.

What would be the most "ruby" way of implementing something like this?

答:
Well, you said you know about zip and map so this probably isn't helpful.
But I'll post just in case.

```<code>def combine a, b
    a.zip(b).map { |i| yield i[0], i[1] }
end

puts combine([1,2,3], [2,3,4]) { |i, j| i+j }
</code>```

No, I don't find it beautiful either.

edit - #ruby-lang @ irc.freenode.net suggests this:

```<code>def combine(a, b, &block)
    a.zip(b).map(&block)
end
</code>```

or this, if you want to forward args:

```<code>def combine(a, b, *args, &block)
    a.zip(b, *args).map(&block)
end
</code>```

OwnerDisplayName: Shalmanese

ContentLicense: CC BY-SA 2.5

Title: passing functions as arguments in ruby

Body:
I'm trying to wrap my head around functional programming in ruby and there doesn't seem to be much good documentation out there.

Essentially, I'm trying to write a combine function that would have a Haskell type signature of:

[a] -> [a] -> (a -> a -> a) -> [a]

So

combine([1,2,3], [2,3,4], plus_func) => [3,5,7]
combine([1,2,3], [2,3,4], multiply_func) => [2,6,12]

etc.

I found some stuff about using zip and map but that feels really ugly to use.

What would be the most "ruby" way of implementing something like this?

Body:
Well, you said you know about zip and map so this probably isn't helpful.
But I'll post just in case.

def combine a, b
    a.zip(b).map { |i| yield i[0], i[1] }
end

puts combine([1,2,3], [2,3,4]) { |i, j| i+j }

No, I don't find it beautiful either.

edit - #ruby-lang @ irc.freenode.net suggests this:

def combine(a, b, &block)
    a.zip(b).map(&block)
end

or this, if you want to forward args:

def combine(a, b, *args, &block)
    a.zip(b, *args).map(&block)
end

OwnerDisplayName: Iraimbilanja

LastEditorDisplayName: Iraimbilanja


问:
android app working on simulator but not on phone
i have this app that i developed and it works great on the simulator with no errors what so ever. but the moment i try to run the same on the phone for testing, the app crashes stating filenotfoundexception. it says the file /res/drawable/divider_horizontal.9.png is missing. but actually speaking, i have never referenced that file through my code.
i believe its a system/os file that is unavailable. i have a custom list view, i guess its the divider there...
could somebody please suggest what is wrong here. i believe this is a similar issue discussed here..but i am unable to make any sense out of it

http://code.google.com/p/transdroid/issues/detail?id=14

the listview.xml layout file

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="wrap_content" android:gravity="left|center"
    android:layout_width="wrap_content" android:paddingBottom="5px"
    android:paddingTop="5px" android:paddingLeft="5px" >
    <ImageView android:id="@+id/linkImage" android:layout_width="wrap_content"
        android:layout_height="fill_parent" android:layout_marginRight="6dip"
        android:src="@drawable/icon" />
    <LinearLayout android:orientation="vertical"
        android:layout_width="0dip" android:layout_weight="1"
        android:layout_height="fill_parent">
        <TextView android:id="@+id/firstLineView"
            android:layout_width="wrap_content" android:layout_height="wrap_content"
            android:gravity="center" android:textColor="#FFFF00" android:text="first line title"></TextView>

        <TextView android:id="@+id/secondLineView"
            android:layout_width="wrap_content" android:layout_height="wrap_content"
            android:text="second line title" android:layout_marginLeft="10px" android:gravity="center"
            android:textColor="#0099CC"></TextView>

    </LinearLayout>
</LinearLayout>
</code>```

the main xml file that calls the listview.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent" android:layout_height="fill_parent">

    <LinearLayout android:orientation="vertical"
        android:layout_width="fill_parent" android:layout_height="fill_parent">
        <LinearLayout android:orientation="horizontal"
            android:layout_width="fill_parent" android:layout_height="40px">
            <Button android:id="@+id/todayButton" android:layout_width="fill_parent"
                android:layout_height="fill_parent" android:text="Today"
                android:textSize="12sp" android:gravity="center"
                android:layout_weight="1" />
            <Button android:id="@+id/tomorrowButton" android:layout_width="fill_parent"
                android:layout_height="fill_parent" android:text="Tomorrow"
                android:textSize="12sp" android:layout_weight="1" />

            <Button android:id="@+id/WeekButton" android:layout_width="fill_parent"
                android:layout_height="fill_parent" android:text="Future"
                android:textSize="12sp" android:layout_weight="1" />

        </LinearLayout>
        <LinearLayout android:id="@+id/listLayout"
            android:orientation="vertical" android:layout_width="fill_parent"
            android:layout_height="fill_parent">
            <ListView android:id="@+id/ListView01" android:layout_width="fill_parent"
                android:layout_height="fill_parent" />
            <TextView android:id="@id/android:empty"
                android:layout_width="fill_parent" android:layout_height="fill_parent"
                android:text="No Results" />
        </LinearLayout>
    </LinearLayout>
</FrameLayout>
</code>```

and the code for the same is

```<code> private class EfficientAdapter extends BaseAdapter{
        private LayoutInflater mInflater;

        private String eventTitleArray[];

private String eventDateArray[];
    private String eventImageLinkArray[];

    public EfficientAdapter(Context context,String[] eventTitleArray,String[] eventDateArray, String[] eventImageLinkArray){
        mInflater = LayoutInflater.from(context);

        this.eventDateArray=eventDateArray;
        this.eventTitleArray=eventTitleArray;
        this.eventImageLinkArray =eventImageLinkArray;

    }
    public int getCount(){
        //return XmlParser.todayEvents.size()-1;
        return this.eventDateArray.length;
    }
    public Object getItem(int position){
        return position;
    }
    public long getItemId(int position){
        return position;
    }
    public View getView(int position, View convertView, ViewGroup parent){
        ViewHolder holder;
        if(convertView == null){
            convertView = mInflater.inflate(R.layout.listview,null);
        holder = new ViewHolder();
        holder.firstLine = (TextView) convertView.findViewById(R.id.firstLineView);
        holder.secondLine = (TextView) convertView.findViewById(R.id.secondLineView);
        holder.imageView = (ImageView) convertView.findViewById(R.id.linkImage);
        //holder.checkbox = (CheckBox) convertView.findViewById(R.id.star);
        holder.firstLine.setFocusable(false);
        holder.secondLine.setFocusable(false);
        holder.imageView.setFocusable(false);
        //holder.checkbox.setFocusable(false);
        convertView.setTag(holder);
    }else{
        holder = (ViewHolder) convertView.getTag();
    }
    Log.i(tag, "Creating the list");
    holder.firstLine.setText(this.eventTitleArray[position]);
    holder.secondLine.setText(this.eventDateArray[position]);

    Bitmap bitmap;
    try {
        bitmap = BitmapFactory.decodeStream((InputStream)new URL("http://edu/images/heinz7.jpg").getContent());
    } catch (MalformedURLException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (Exception e1) {
        // TODO Auto-generated catch block
        bitmap = BitmapFactory.decodeFile("assets/heinz7.jpg");//decodeFile(getResources().getAssets().open("icon.png"));
        e1.printStackTrace();
    }
    try {
        try{
            bitmap = BitmapFactory.decodeStream((InputStream)new URL(this.eventImageLinkArray[position]).getContent());}
        catch(Exception e){
            bitmap = BitmapFactory.decodeStream((InputStream)new URL("http://eventur.sis.pitt.edu/images/heinz7.jpg").getContent());
        }

        int width = 0;
        int height =0;
        int newWidth = 50;
        int newHeight = 40;

        try{
            width = bitmap.getWidth();
            height = bitmap.getHeight();
        }
        catch(Exception e){
            width = 50;
            height = 40;
        }
        float scaleWidth = ((float)newWidth)/width;
        float scaleHeight = ((float)newHeight)/height;
        Matrix mat = new Matrix();
        mat.postScale(scaleWidth, scaleHeight);

        try{
            Bitmap newBitmap = Bitmap.createBitmap(bitmap,0,0,width,height,mat,true);
            BitmapDrawable bmd = new BitmapDrawable(newBitmap);
            holder.imageView.setImageDrawable(bmd);
            holder.imageView.setScaleType(ScaleType.CENTER);
        }
        catch(Exception e){

        }

    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return convertView;
}
class ViewHolder{
    TextView firstLine;
    TextView secondLine;
    ImageView imageView;
    //CheckBox checkbox;

}
</code>```

The stack trace

```<code>12-12 22:55:25.022: ERROR/AndroidRuntime(11069): Uncaught handler: thread main exiting due to uncaught exception
12-12 22:55:25.212: ERROR/AndroidRuntime(11069): android.view.InflateException: Binary XML file line #6: Error inflating class java.lang.reflect.Constructor
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at android.view.LayoutInflater.createView(LayoutInflater.java:512)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:56)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:562)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at android.view.LayoutInflater.rInflate(LayoutInflater.java:617)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at android.view.LayoutInflater.inflate(LayoutInflater.java:407)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at android.view.LayoutInflater.inflate(LayoutInflater.java:320)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at android.view.LayoutInflater.inflate(LayoutInflater.java:276)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at com.eventur.MainActivity$EfficientAdapter.getView(MainActivity.java:566)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at android.widget.AbsListView.obtainView(AbsListView.java:1274)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at android.widget.ListView.makeAndAddView(ListView.java:1661)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at android.widget.ListView.fillDown(ListView.java:610)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at android.widget.ListView.fillFromTop(ListView.java:673)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at android.widget.ListView.layoutChildren(ListView.java:1519)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at android.widget.AbsListView.onLayout(AbsListView.java:1113)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at android.view.View.layout(View.java:6156)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1119)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at android.widget.LinearLayout.layoutVertical(LinearLayout.java:998)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at android.widget.LinearLayout.onLayout(LinearLayout.java:918)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at android.view.View.layout(View.java:6156)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1119)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at android.widget.LinearLayout.layoutVertical(LinearLayout.java:998)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at android.widget.LinearLayout.onLayout(LinearLayout.java:918)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at android.view.View.layout(View.java:6156)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at android.widget.FrameLayout.onLayout(FrameLayout.java:333)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at android.view.View.layout(View.java:6156)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at android.widget.FrameLayout.onLayout(FrameLayout.java:333)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at android.view.View.layout(View.java:6156)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1119)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at android.widget.LinearLayout.layoutVertical(LinearLayout.java:998)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at android.widget.LinearLayout.onLayout(LinearLayout.java:918)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at android.view.View.layout(View.java:6156)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at android.widget.FrameLayout.onLayout(FrameLayout.java:333)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at android.view.View.layout(View.java:6156)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at android.view.ViewRoot.performTraversals(ViewRoot.java:950)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at android.view.ViewRoot.handleMessage(ViewRoot.java:1529)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at android.os.Handler.dispatchMessage(Handler.java:99)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at android.os.Looper.loop(Looper.java:123)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at android.app.ActivityThread.main(ActivityThread.java:3977)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at java.lang.reflect.Method.invokeNative(Native Method)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at java.lang.reflect.Method.invoke(Method.java:521)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:782)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:540)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at dalvik.system.NativeStart.main(Native Method)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069): Caused by: java.lang.reflect.InvocationTargetException
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at android.widget.ImageView.<init>(ImageView.java:128)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at java.lang.reflect.Constructor.constructNative(Native Method)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at java.lang.reflect.Constructor.newInstance(Constructor.java:446)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at android.view.LayoutInflater.createView(LayoutInflater.java:499)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     ... 42 more
12-12 22:55:25.212: ERROR/AndroidRuntime(11069): Caused by: android.content.res.Resources$NotFoundException: File res/drawable/divider_horizontal_dark.9.png from drawable resource ID #0x7f020001
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at android.content.res.Resources.loadDrawable(Resources.java:1643)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at android.content.res.TypedArray.getDrawable(TypedArray.java:548)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at android.widget.ImageView.<init>(ImageView.java:138)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     ... 46 more
12-12 22:55:25.212: ERROR/AndroidRuntime(11069): Caused by: java.io.FileNotFoundException: res/drawable/divider_horizontal_dark.9.png
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at android.content.res.AssetManager.openNonAssetNative(Native Method)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at android.content.res.AssetManager.openNonAsset(AssetManager.java:417)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at android.content.res.Resources.loadDrawable(Resources.java:1636)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     ... 48 more
</code>```

答:
There's a problem occurring during inflation. Inflating doesn't have the best error reporting/recovery, so it throws weird cryptic messages like this up when it runs into problems. I'm confident the issue lies in listview.xml, and the problem is more than likely one of the xml attributes you've added to one of the elements. Line #6 is I think referring to either the first or second Button element. When it goes to compile, it seems to give each element just one line each. I would start by taking out all tags that aren't immediately necessary for the program to run, like gravity and layout_weight.

Sorry I can't provide a more specific answer; when you run into inflation errors like this, it's a matter of probing in the dark until you find what's wrong.

As to why this is happening on the phone and not the emulator, more than likely there's simply an operating system difference between the two (OS version, UI being used, other changes the manufacturer has made, etc). Testing on the emulator will give you a good idea of how the program is going to look and run on the phone, but offers no guarantee.

Kudos on providing so much information, it makes troubleshooting a lot easier ;-) Let me know if my advice works, or if you need more information.

Body:
i have this app that i developed and it works great on the simulator with no errors what so ever. but the moment i try to run the same on the phone for testing, the app crashes stating filenotfoundexception. it says the file /res/drawable/divider_horizontal.9.png is missing. but actually speaking, i have never referenced that file through my code.
i believe its a system/os file that is unavailable. i have a custom list view, i guess its the divider there...
could somebody please suggest what is wrong here. i believe this is a similar issue discussed here..but i am unable to make any sense out of it

http://code.google.com/p/transdroid/issues/detail?id=14

the listview.xml layout file

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="wrap_content" android:gravity="left|center"
    android:layout_width="wrap_content" android:paddingBottom="5px"
    android:paddingTop="5px" android:paddingLeft="5px" >
    <ImageView android:id="@+id/linkImage" android:layout_width="wrap_content"
        android:layout_height="fill_parent" android:layout_marginRight="6dip"
        android:src="@drawable/icon" />
    <LinearLayout android:orientation="vertical"
        android:layout_width="0dip" android:layout_weight="1"
        android:layout_height="fill_parent">
        <TextView android:id="@+id/firstLineView"
            android:layout_width="wrap_content" android:layout_height="wrap_content"
            android:gravity="center" android:textColor="#FFFF00" android:text="first line title"></TextView>

        <TextView android:id="@+id/secondLineView"
            android:layout_width="wrap_content" android:layout_height="wrap_content"
            android:text="second line title" android:layout_marginLeft="10px" android:gravity="center"
            android:textColor="#0099CC"></TextView>

    </LinearLayout>
</LinearLayout>

the main xml file that calls the listview.xml

<?xml version="1.0" encoding="UTF-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent" android:layout_height="fill_parent">

    <LinearLayout android:orientation="vertical"
        android:layout_width="fill_parent" android:layout_height="fill_parent">
        <LinearLayout android:orientation="horizontal"
            android:layout_width="fill_parent" android:layout_height="40px">
            <Button android:id="@+id/todayButton" android:layout_width="fill_parent"
                android:layout_height="fill_parent" android:text="Today"
                android:textSize="12sp" android:gravity="center"
                android:layout_weight="1" />
            <Button android:id="@+id/tomorrowButton" android:layout_width="fill_parent"
                android:layout_height="fill_parent" android:text="Tomorrow"
                android:textSize="12sp" android:layout_weight="1" />

            <Button android:id="@+id/WeekButton" android:layout_width="fill_parent"
                android:layout_height="fill_parent" android:text="Future"
                android:textSize="12sp" android:layout_weight="1" />

        </LinearLayout>
        <LinearLayout android:id="@+id/listLayout"
            android:orientation="vertical" android:layout_width="fill_parent"
            android:layout_height="fill_parent">
            <ListView android:id="@+id/ListView01" android:layout_width="fill_parent"
                android:layout_height="fill_parent" />
            <TextView android:id="@id/android:empty"
                android:layout_width="fill_parent" android:layout_height="fill_parent"
                android:text="No Results" />
        </LinearLayout>
    </LinearLayout>
</FrameLayout>

and the code for the same is

 private class EfficientAdapter extends BaseAdapter{
        private LayoutInflater mInflater;

        private String eventTitleArray[];

private String eventDateArray[];
    private String eventImageLinkArray[];

    public EfficientAdapter(Context context,String[] eventTitleArray,String[] eventDateArray, String[] eventImageLinkArray){
        mInflater = LayoutInflater.from(context);

        this.eventDateArray=eventDateArray;
        this.eventTitleArray=eventTitleArray;
        this.eventImageLinkArray =eventImageLinkArray;

    }
    public int getCount(){
        //return XmlParser.todayEvents.size()-1;
        return this.eventDateArray.length;
    }
    public Object getItem(int position){
        return position;
    }
    public long getItemId(int position){
        return position;
    }
    public View getView(int position, View convertView, ViewGroup parent){
        ViewHolder holder;
        if(convertView == null){
            convertView = mInflater.inflate(R.layout.listview,null);
        holder = new ViewHolder();
        holder.firstLine = (TextView) convertView.findViewById(R.id.firstLineView);
        holder.secondLine = (TextView) convertView.findViewById(R.id.secondLineView);
        holder.imageView = (ImageView) convertView.findViewById(R.id.linkImage);
        //holder.checkbox = (CheckBox) convertView.findViewById(R.id.star);
        holder.firstLine.setFocusable(false);
        holder.secondLine.setFocusable(false);
        holder.imageView.setFocusable(false);
        //holder.checkbox.setFocusable(false);
        convertView.setTag(holder);
    }else{
        holder = (ViewHolder) convertView.getTag();
    }
    Log.i(tag, "Creating the list");
    holder.firstLine.setText(this.eventTitleArray[position]);
    holder.secondLine.setText(this.eventDateArray[position]);

    Bitmap bitmap;
    try {
        bitmap = BitmapFactory.decodeStream((InputStream)new URL("http://edu/images/heinz7.jpg").getContent());
    } catch (MalformedURLException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (Exception e1) {
        // TODO Auto-generated catch block
        bitmap = BitmapFactory.decodeFile("assets/heinz7.jpg");//decodeFile(getResources().getAssets().open("icon.png"));
        e1.printStackTrace();
    }
    try {
        try{
            bitmap = BitmapFactory.decodeStream((InputStream)new URL(this.eventImageLinkArray[position]).getContent());}
        catch(Exception e){
            bitmap = BitmapFactory.decodeStream((InputStream)new URL("http://eventur.sis.pitt.edu/images/heinz7.jpg").getContent());
        }

        int width = 0;
        int height =0;
        int newWidth = 50;
        int newHeight = 40;

        try{
            width = bitmap.getWidth();
            height = bitmap.getHeight();
        }
        catch(Exception e){
            width = 50;
            height = 40;
        }
        float scaleWidth = ((float)newWidth)/width;
        float scaleHeight = ((float)newHeight)/height;
        Matrix mat = new Matrix();
        mat.postScale(scaleWidth, scaleHeight);

        try{
            Bitmap newBitmap = Bitmap.createBitmap(bitmap,0,0,width,height,mat,true);
            BitmapDrawable bmd = new BitmapDrawable(newBitmap);
            holder.imageView.setImageDrawable(bmd);
            holder.imageView.setScaleType(ScaleType.CENTER);
        }
        catch(Exception e){

        }

    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return convertView;
}
class ViewHolder{
    TextView firstLine;
    TextView secondLine;
    ImageView imageView;
    //CheckBox checkbox;

}

The stack trace

12-12 22:55:25.022: ERROR/AndroidRuntime(11069): Uncaught handler: thread main exiting due to uncaught exception
12-12 22:55:25.212: ERROR/AndroidRuntime(11069): android.view.InflateException: Binary XML file line #6: Error inflating class java.lang.reflect.Constructor
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at android.view.LayoutInflater.createView(LayoutInflater.java:512)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:56)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:562)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at android.view.LayoutInflater.rInflate(LayoutInflater.java:617)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at android.view.LayoutInflater.inflate(LayoutInflater.java:407)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at android.view.LayoutInflater.inflate(LayoutInflater.java:320)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at android.view.LayoutInflater.inflate(LayoutInflater.java:276)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at com.eventur.MainActivity$EfficientAdapter.getView(MainActivity.java:566)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at android.widget.AbsListView.obtainView(AbsListView.java:1274)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at android.widget.ListView.makeAndAddView(ListView.java:1661)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at android.widget.ListView.fillDown(ListView.java:610)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at android.widget.ListView.fillFromTop(ListView.java:673)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at android.widget.ListView.layoutChildren(ListView.java:1519)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at android.widget.AbsListView.onLayout(AbsListView.java:1113)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at android.view.View.layout(View.java:6156)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1119)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at android.widget.LinearLayout.layoutVertical(LinearLayout.java:998)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at android.widget.LinearLayout.onLayout(LinearLayout.java:918)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at android.view.View.layout(View.java:6156)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1119)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at android.widget.LinearLayout.layoutVertical(LinearLayout.java:998)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at android.widget.LinearLayout.onLayout(LinearLayout.java:918)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at android.view.View.layout(View.java:6156)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at android.widget.FrameLayout.onLayout(FrameLayout.java:333)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at android.view.View.layout(View.java:6156)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at android.widget.FrameLayout.onLayout(FrameLayout.java:333)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at android.view.View.layout(View.java:6156)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1119)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at android.widget.LinearLayout.layoutVertical(LinearLayout.java:998)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at android.widget.LinearLayout.onLayout(LinearLayout.java:918)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at android.view.View.layout(View.java:6156)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at android.widget.FrameLayout.onLayout(FrameLayout.java:333)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at android.view.View.layout(View.java:6156)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at android.view.ViewRoot.performTraversals(ViewRoot.java:950)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at android.view.ViewRoot.handleMessage(ViewRoot.java:1529)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at android.os.Handler.dispatchMessage(Handler.java:99)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at android.os.Looper.loop(Looper.java:123)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at android.app.ActivityThread.main(ActivityThread.java:3977)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at java.lang.reflect.Method.invokeNative(Native Method)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at java.lang.reflect.Method.invoke(Method.java:521)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:782)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:540)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at dalvik.system.NativeStart.main(Native Method)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069): Caused by: java.lang.reflect.InvocationTargetException
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at android.widget.ImageView.<init>(ImageView.java:128)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at java.lang.reflect.Constructor.constructNative(Native Method)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at java.lang.reflect.Constructor.newInstance(Constructor.java:446)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at android.view.LayoutInflater.createView(LayoutInflater.java:499)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     ... 42 more
12-12 22:55:25.212: ERROR/AndroidRuntime(11069): Caused by: android.content.res.Resources$NotFoundException: File res/drawable/divider_horizontal_dark.9.png from drawable resource ID #0x7f020001
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at android.content.res.Resources.loadDrawable(Resources.java:1643)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at android.content.res.TypedArray.getDrawable(TypedArray.java:548)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at android.widget.ImageView.<init>(ImageView.java:138)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     ... 46 more
12-12 22:55:25.212: ERROR/AndroidRuntime(11069): Caused by: java.io.FileNotFoundException: res/drawable/divider_horizontal_dark.9.png
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at android.content.res.AssetManager.openNonAssetNative(Native Method)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at android.content.res.AssetManager.openNonAsset(AssetManager.java:417)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     at android.content.res.Resources.loadDrawable(Resources.java:1636)
12-12 22:55:25.212: ERROR/AndroidRuntime(11069):     ... 48 more


问:
Is the APIClient created by ApacheAPIClientBuilder for Algolia Java threadsafe?
When using the APIClient created by ApacheAPIClientBuilder, is the APIClient thread-safe, or should a new one be created for each thread?</p>

答: The APIClient is not thread safe. It keeps an internal state that is not made to be thread safe.</p>


问:
Building Eigen3 with CXX_FLAGS
I'm trying to build Eigen3 using CMake as described in the installation menual:

```<code>root@60e449767588:/opt/tr/src/eigen/build_dir$ ../../cmake-3.8.1/bin/cmake  -DCMAKE_BUILD_TYPE=Release --build ..
</code>```

This is the output:

```<code>-- Standard libraries to link to explicitly: none
-- Found unsuitable Qt version "" from NOTFOUND
-- Could NOT find CHOLMOD (missing:  CHOLMOD_INCLUDES CHOLMOD_LIBRARIES)
-- Could NOT find UMFPACK (missing:  UMFPACK_INCLUDES UMFPACK_LIBRARIES)
-- Could NOT find SUPERLU (missing:  SUPERLU_INCLUDES SUPERLU_LIBRARIES SUPERLU_VERSION_OK)
-- Could NOT find PASTIX (missing:  PASTIX_INCLUDES PASTIX_LIBRARIES)
-- Could NOT find SCOTCH (missing:  SCOTCH_INCLUDES SCOTCH_LIBRARIES)
-- Could NOT find METIS (missing:  METIS_INCLUDES METIS_LIBRARIES)
-- Could NOT find SPQR (missing:  SPQR_INCLUDES SPQR_LIBRARIES)
-- Found unsuitable Qt version "" from NOTFOUND
-- Boost version: 1.64.0
-- Could NOT find GOOGLEHASH (missing:  GOOGLEHASH_INCLUDES GOOGLEHASH_COMPILE)
-- Could NOT find ADOLC (missing:  ADOLC_INCLUDES ADOLC_LIBRARIES)
-- Could NOT find MPFR (missing:  MPFR_INCLUDES MPFR_LIBRARIES MPFR_VERSION_OK) (Required is at least version "2.3.0")
-- Could NOT find GMP (missing:  GMP_INCLUDES GMP_LIBRARIES)
-- Could NOT find PkgConfig (missing:  PKG_CONFIG_EXECUTABLE)
-- Could NOT find FFTW (missing:  FFTW_INCLUDES FFTW_LIBRARIES)
-- Could NOT find OpenGL (missing:  OPENGL_gl_LIBRARY OPENGL_INCLUDE_DIR)
-- Could NOT find GLUT (missing:  GLUT_glut_LIBRARY GLUT_INCLUDE_DIR)
CUDA_TOOLKIT_ROOT_DIR not found or specified
-- Could NOT find CUDA (missing:  CUDA_TOOLKIT_ROOT_DIR CUDA_NVCC_EXECUTABLE CUDA_INCLUDE_DIRS CUDA_CUDART_LIBRARY) (Required is at least version "7.0")
-- Found unsuitable Qt version "" from NOTFOUND
-- Qt4 not found, so disabling the mandelbrot and opengl demos
-- Could NOT find CHOLMOD (missing:  CHOLMOD_INCLUDES CHOLMOD_LIBRARIES)
-- Could NOT find UMFPACK (missing:  UMFPACK_INCLUDES UMFPACK_LIBRARIES)
-- Could NOT find SUPERLU (missing:  SUPERLU_INCLUDES SUPERLU_LIBRARIES SUPERLU_VERSION_OK)
-- Could NOT find PASTIX (missing:  PASTIX_INCLUDES PASTIX_LIBRARIES)
-- Could NOT find SCOTCH (missing:  SCOTCH_INCLUDES SCOTCH_LIBRARIES)
-- Could NOT find METIS (missing:  METIS_INCLUDES METIS_LIBRARIES)
-- ************************************************************
-- ***    Eigen's unit tests configuration summary          ***
-- ************************************************************
--
-- Build type:        Release
-- Build site:        60e449767588
-- Build string:      linux-4.4.0-78-generic-_-4.9.2-sse2-64bit
-- Enabled backends:  Boost.Multiprecision,
-- Disabled backends: Cholmod,  UmfPack,  SuperLU,  PaStiX,  METIS,  SPQR,  Qt4 support,  GoogleHash,  Adolc,  MPFR C++,  fftw,  OpenGL,
-- Default order:     Column-major
-- Maximal matrix/vector size: 320
-- SSE2:              Using architecture defaults
-- SSE3:              Using architecture defaults
-- SSSE3:             Using architecture defaults
-- SSE4.1:            Using architecture defaults
-- SSE4.2:            Using architecture defaults
-- AVX:               Using architecture defaults
-- FMA:               Using architecture defaults
-- AVX512:            Using architecture defaults
-- Altivec:           Using architecture defaults
-- VSX:               Using architecture defaults
-- ARM NEON:          Using architecture defaults
-- ARMv8 NEON:        Using architecture defaults
-- S390X ZVECTOR:     Using architecture defaults
-- C++11:             OFF
-- SYCL:              OFF
-- CUDA:              OFF
--
CXX:               /usr/bin/c++
 CXX_VERSION:       c++ (Debian 4.9.2-10) 4.9.2
 CXX_FLAGS:         -O3 -DNDEBUG -fPIC -DEIGEN_USE_MKL_ALL -DMKL_ILP64 -fopenmp -m64 -v -pedantic -Wall -Wextra -Wundef -Wcast-align -Wchar-subscripts -Wnon-virtual-dtor -Wunused-local-typedefs -Wpointer-arith -Wwrite-strings -Wformat-security -Wlogical-op -Wdouble-promotion -Wno-psabi -Wno-variadic-macros -Wno-long-long -fno-check-new -fno-common -fstrict-aliasing -ansi
 Sparse lib flags:

-- ************************************************************
--
-- Configured Eigen 3.3.3
--
-- Some things you can do now:
-- --------------+--------------------------------------------------------------
-- Command       |   Description
-- --------------+--------------------------------------------------------------
-- make install  | Install Eigen. Headers will be installed to:
--               |     <CMAKE_INSTALL_PREFIX>/<INCLUDE_INSTALL_DIR>
--               |   Using the following values:
--               |     CMAKE_INSTALL_PREFIX: /usr/local
--               |     INCLUDE_INSTALL_DIR:  include/eigen3
--               |   Change the install location of Eigen headers using:
--               |     cmake . -DCMAKE_INSTALL_PREFIX=yourprefix
--               |   Or:
--               |     cmake . -DINCLUDE_INSTALL_DIR=yourdir
-- make doc      | Generate the API documentation, requires Doxygen & LaTeX
-- make check    | Build and run the unit-tests. Read this page:
--               |   http://eigen.tuxfamily.org/index.php?title=Tests
-- make blas     | Build BLAS library (not the same thing as Eigen)
-- make uninstall| Removes files installed by make install
-- --------------+--------------------------------------------------------------
--
-- Configuring done
-- Generating done
-- Build files have been written to: /opt/tr/src/eigen/build_dir
</code>```

My questions are:

How to remove the default value of CXX_FLAGS?

How to specify that I wish to work with C++11 or even 14?

How to specify that I wish to work with SYCL?

Thank you!

答:
As per the answer from @m7913d Eigen is a header only library so you can follow the standard instructions on how to include these.

For 3, there is a guide on how to integrate Eigen with your application, and how to build things
https://developer.codeplay.com/products/computecpp/ce/guides/eigen-guide/options-for-building-eigen

Title: Building Eigen3 with CXX_FLAGS

Body:
I'm trying to build Eigen3 using CMake as described in the installation menual:

root@60e449767588:/opt/tr/src/eigen/build_dir$ ../../cmake-3.8.1/bin/cmake  -DCMAKE_BUILD_TYPE=Release --build ..

This is the output:

-- Standard libraries to link to explicitly: none
-- Found unsuitable Qt version "" from NOTFOUND
-- Could NOT find CHOLMOD (missing:  CHOLMOD_INCLUDES CHOLMOD_LIBRARIES)
-- Could NOT find UMFPACK (missing:  UMFPACK_INCLUDES UMFPACK_LIBRARIES)
-- Could NOT find SUPERLU (missing:  SUPERLU_INCLUDES SUPERLU_LIBRARIES SUPERLU_VERSION_OK)
-- Could NOT find PASTIX (missing:  PASTIX_INCLUDES PASTIX_LIBRARIES)
-- Could NOT find SCOTCH (missing:  SCOTCH_INCLUDES SCOTCH_LIBRARIES)
-- Could NOT find METIS (missing:  METIS_INCLUDES METIS_LIBRARIES)
-- Could NOT find SPQR (missing:  SPQR_INCLUDES SPQR_LIBRARIES)
-- Found unsuitable Qt version "" from NOTFOUND
-- Boost version: 1.64.0
-- Could NOT find GOOGLEHASH (missing:  GOOGLEHASH_INCLUDES GOOGLEHASH_COMPILE)
-- Could NOT find ADOLC (missing:  ADOLC_INCLUDES ADOLC_LIBRARIES)
-- Could NOT find MPFR (missing:  MPFR_INCLUDES MPFR_LIBRARIES MPFR_VERSION_OK) (Required is at least version "2.3.0")
-- Could NOT find GMP (missing:  GMP_INCLUDES GMP_LIBRARIES)
-- Could NOT find PkgConfig (missing:  PKG_CONFIG_EXECUTABLE)
-- Could NOT find FFTW (missing:  FFTW_INCLUDES FFTW_LIBRARIES)
-- Could NOT find OpenGL (missing:  OPENGL_gl_LIBRARY OPENGL_INCLUDE_DIR)
-- Could NOT find GLUT (missing:  GLUT_glut_LIBRARY GLUT_INCLUDE_DIR)
CUDA_TOOLKIT_ROOT_DIR not found or specified
-- Could NOT find CUDA (missing:  CUDA_TOOLKIT_ROOT_DIR CUDA_NVCC_EXECUTABLE CUDA_INCLUDE_DIRS CUDA_CUDART_LIBRARY) (Required is at least version "7.0")
-- Found unsuitable Qt version "" from NOTFOUND
-- Qt4 not found, so disabling the mandelbrot and opengl demos
-- Could NOT find CHOLMOD (missing:  CHOLMOD_INCLUDES CHOLMOD_LIBRARIES)
-- Could NOT find UMFPACK (missing:  UMFPACK_INCLUDES UMFPACK_LIBRARIES)
-- Could NOT find SUPERLU (missing:  SUPERLU_INCLUDES SUPERLU_LIBRARIES SUPERLU_VERSION_OK)
-- Could NOT find PASTIX (missing:  PASTIX_INCLUDES PASTIX_LIBRARIES)
-- Could NOT find SCOTCH (missing:  SCOTCH_INCLUDES SCOTCH_LIBRARIES)
-- Could NOT find METIS (missing:  METIS_INCLUDES METIS_LIBRARIES)
-- ************************************************************
-- ***    Eigen's unit tests configuration summary          ***
-- ************************************************************
--
-- Build type:        Release
-- Build site:        60e449767588
-- Build string:      linux-4.4.0-78-generic-_-4.9.2-sse2-64bit
-- Enabled backends:  Boost.Multiprecision,
-- Disabled backends: Cholmod,  UmfPack,  SuperLU,  PaStiX,  METIS,  SPQR,  Qt4 support,  GoogleHash,  Adolc,  MPFR C++,  fftw,  OpenGL,
-- Default order:     Column-major
-- Maximal matrix/vector size: 320
-- SSE2:              Using architecture defaults
-- SSE3:              Using architecture defaults
-- SSSE3:             Using architecture defaults
-- SSE4.1:            Using architecture defaults
-- SSE4.2:            Using architecture defaults
-- AVX:               Using architecture defaults
-- FMA:               Using architecture defaults
-- AVX512:            Using architecture defaults
-- Altivec:           Using architecture defaults
-- VSX:               Using architecture defaults
-- ARM NEON:          Using architecture defaults
-- ARMv8 NEON:        Using architecture defaults
-- S390X ZVECTOR:     Using architecture defaults
-- C++11:             OFF
-- SYCL:              OFF
-- CUDA:              OFF
--
CXX:               /usr/bin/c++
 CXX_VERSION:       c++ (Debian 4.9.2-10) 4.9.2
 CXX_FLAGS:         -O3 -DNDEBUG -fPIC -DEIGEN_USE_MKL_ALL -DMKL_ILP64 -fopenmp -m64 -v -pedantic -Wall -Wextra -Wundef -Wcast-align -Wchar-subscripts -Wnon-virtual-dtor -Wunused-local-typedefs -Wpointer-arith -Wwrite-strings -Wformat-security -Wlogical-op -Wdouble-promotion -Wno-psabi -Wno-variadic-macros -Wno-long-long -fno-check-new -fno-common -fstrict-aliasing -ansi
 Sparse lib flags:

-- ************************************************************
--
-- Configured Eigen 3.3.3
--
-- Some things you can do now:
-- --------------+--------------------------------------------------------------
-- Command       |   Description
-- --------------+--------------------------------------------------------------
-- make install  | Install Eigen. Headers will be installed to:
--               |     <CMAKE_INSTALL_PREFIX>/<INCLUDE_INSTALL_DIR>
--               |   Using the following values:
--               |     CMAKE_INSTALL_PREFIX: /usr/local
--               |     INCLUDE_INSTALL_DIR:  include/eigen3
--               |   Change the install location of Eigen headers using:
--               |     cmake . -DCMAKE_INSTALL_PREFIX=yourprefix
--               |   Or:
--               |     cmake . -DINCLUDE_INSTALL_DIR=yourdir
-- make doc      | Generate the API documentation, requires Doxygen & LaTeX
-- make check    | Build and run the unit-tests. Read this page:
--               |   http://eigen.tuxfamily.org/index.php?title=Tests
-- make blas     | Build BLAS library (not the same thing as Eigen)
-- make uninstall| Removes files installed by make install
-- --------------+--------------------------------------------------------------
--
-- Configuring done
-- Generating done
-- Build files have been written to: /opt/tr/src/eigen/build_dir

My questions are:

How to remove the default value of CXX_FLAGS?

How to specify that I wish to work with C++11 or even 14?

How to specify that I wish to work with SYCL?

Thank you!

ContentLicense: CC BY-SA 4.0


问:
Uncaught TypeError: like is not a function at HTMLSpanElement.onclick. when i click on like its throughting error
when i click on like its throughting error

getting error:Uncaught TypeError: like is not a function at HTMLSpanElement.onclick

```<code>//In Controller
    myApp.controller('AppCtrl', ['$scope', '$http', 'chatBotService', function($scope, $http, chatBotService) {

        (function () {
            $scope.like = function (lll) {
                alert("like");
                //lll.previousSibling.style.color = 'gray';
                //lll.style.color = 'green';
            }
        });
           (function () {
            $scope.dislike = function (ddd) {
                alert("dislike");
                //ddd.style.color = 'red';
                //ddd.nextSibling.style.color = 'gray';
            }
           });

    function send_message(message) {
          $("#container").append("<div class='row msg_container base_receive'>" +
           "<div class='avatar'>" + "<img src='bot.png' alt='Chat' style='width:15px;margin-right: 10px;'/>" + "<br/>" +"</div>" + "<div class='col-md-10 col-xs-10'>" +"<div class='messages msg_receive'>" + message + "</div>" +"<small>" + DisplayCurrentTime() + "<small/>" + "<span id='dislike'
    class='glyphicon glyphicon-thumbs-down gly-flip-horizontal dislike' onclick='dislike(this)' aria-hidden='true'></span>" + "<span id='like' onclick='like(this)' class='glyphicon glyphicon-thumbs-up like' aria-hidden='true'></span>" +  "</div>" + "</div>");
            }

    }]);
</code>```

答:
document.getElementById("dislike").addEventListener("click", dislike);
        document.getElementById("like").addEventListener("click", like);</p>

```<code>    function dislike() {
        this.style.color = 'red';
        this.nextSibling.style.color = 'gray';
    }

    function like() {
        this.previousSibling.style.color = 'gray';
        this.style.color = 'green';
    }
</code>```

Body:
when i click on like its throughting error

getting error:Uncaught TypeError: like is not a function at HTMLSpanElement.onclick

//In Controller
    myApp.controller('AppCtrl', ['$scope', '$http', 'chatBotService', function($scope, $http, chatBotService) {

        (function () {
            $scope.like = function (lll) {
                alert("like");
                //lll.previousSibling.style.color = 'gray';
                //lll.style.color = 'green';
            }
        });
           (function () {
            $scope.dislike = function (ddd) {
                alert("dislike");
                //ddd.style.color = 'red';
                //ddd.nextSibling.style.color = 'gray';
            }
           });

    function send_message(message) {
          $("#container").append("
" +
           "
" + "" + "
" +"
" + "
" +"
" + message + "
" +"" + DisplayCurrentTime() + "" + "" + "" +  "
" + "
");
            }

    }]);

Body:
document.getElementById("dislike").addEventListener("click", dislike);
        document.getElementById("like").addEventListener("click", like);

    function dislike() {
        this.style.color = 'red';
        this.nextSibling.style.color = 'gray';
    }

    function like() {
        this.previousSibling.style.color = 'gray';
        this.style.color = 'green';
    }


问:
How can I run Linux commands on an Android device?
On some Android devices, in the ADB shell, I can only run echo, cd, ls. When I run:

```<code>tar -cvf //mnt/sdcard/BackUp1669/apk/test.tar /mnt/sdcard/test.apk
</code>```

Or the command cp, it returns:

```<code>sh: tar: not found
</code>```

Why can I not run these commands? Some devices support these commands. My end goal is to copy a file from the /data/data folder to SD card. I got su and I got the following code:

```<code>int timeout = 1000;
String command = "tar -cvf /" + Environment.getExternalStorageDirectory() + "/cp/"
        + packageName + ".tar" + " " + path;
DataOutputStream os = new DataOutputStream(process.getOutputStream());
BufferedReader is = new BufferedReader(new InputStreamReader(new DataInputStream(
        process.getInputStream())), 64);

String inLine;
try {
    StringBuilder sbCommand = new StringBuilder();
    sbCommand.append(command).append(" ");
    sbCommand.append("\n");
    os.writeBytes(command.toString());
    if (is != null) {
        for (int i = 0; i < timeout; i++) {
            if (is.ready())
                break;
            try {
                Thread.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        if (is.ready()) {
            inLine = is.readLine();
        } else {
        }
    }

} catch (IOException e) {
    e.printStackTrace();
}
</code>```

It always stops in is.ready(), and when I changed it to process.waitfor() it also stopped. Why?

答:
Install busybox, then type the command in the following format:

busybox [linux command]

You cannot use all the linux commands without busybox, because Android doesn't have all the binaries that are available in a standard linux operating system.

FYI, a binary is just a file that contains compiled code. A lot of the default binaries are stored in /system/bin/sh directory. All these commands like 'cp' 'ls' 'get' etc, are actually binaries. You can view them through:

ls -a /system/bin/sh

Hope this helps.

Body:
On some Android devices, in the ADB shell, I can only run echo, cd, ls. When I run:

tar -cvf //mnt/sdcard/BackUp1669/apk/test.tar /mnt/sdcard/test.apk

Or the command cp, it returns:

sh: tar: not found

Why can I not run these commands? Some devices support these commands. My end goal is to copy a file from the /data/data folder to SD card. I got su and I got the following code:

int timeout = 1000;
String command = "tar -cvf /" + Environment.getExternalStorageDirectory() + "/cp/"
        + packageName + ".tar" + " " + path;
DataOutputStream os = new DataOutputStream(process.getOutputStream());
BufferedReader is = new BufferedReader(new InputStreamReader(new DataInputStream(
        process.getInputStream())), 64);

String inLine;
try {
    StringBuilder sbCommand = new StringBuilder();
    sbCommand.append(command).append(" ");
    sbCommand.append("\n");
    os.writeBytes(command.toString());
    if (is != null) {
        for (int i = 0; i < timeout; i++) {
            if (is.ready())
                break;
            try {
                Thread.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        if (is.ready()) {
            inLine = is.readLine();
        } else {
        }
    }

} catch (IOException e) {
    e.printStackTrace();
}

It always stops in is.ready(), and when I changed it to process.waitfor() it also stopped. Why?


问:
Iterate through Json data
So I have this array of JSON objects:

```<code>[
  {
    "columns": [
      {
        "fields": [
          {
            "valueFields": [
              {
                "type": 1,
                "fieldName": "prj_Name",
                "value": "1A BNL FB e-Powedr basic Balci Reizen",
                "valueId": "",
                "defaultValue": false,
                "baseValue": false,
                "mandatoryField": true,
                "hasError": false,
                "errorMessage": "",
                "disabled": false,
                "visible": true
              }
            ]
          }
        ]
      }
    ]
  }
]
</code>```

and I would like to Iterate through the Data to do some stuff with it later.

I already tried this :

```<code>for (var key in currentObject) {
    if (currentObject.hasOwnProperty(key)) {
        console.log(key + ': ' + currentObject[key]);
    }
}
</code>```

But it prints every letter separatly in the console, so I guess it isn't right.
Do you have any Ideas of what I am doing wrong ?

[EDIT]

I tried to add var currentObject = JSON.parse(Json); before the for loop.

I now get this printed 0: [object Object]

How to iterate through the object then ?

答:
Your JsonObject is a JsonArray in a JsonArray in a JsonArray in a JsonArray...

Try the following code online, it works for your case

```<code>var x  = '[{"columns":[{"fields":[{"valueFields":[{"type":1,"fieldName":"prj_Name","value":"1A BNL FB e-Powedr basic BalciReizen","valueId":"","defaultValue":false,"baseValue":false,"mandatoryField":true,"hasError":false,"errorMessage":"","disabled":false,"visible":true}]}]}]}]';
var parsedJson = JSON.parse(x);
var valueFields = parsedJson[0].columns[0].fields[0].valueFields[0];

for (var key in valueFields) {
    if (valueFields.hasOwnProperty(key)) {
        console.log(key + ': ' + valueFields[key]);
    }
}
</code>```

I would suggest to change the output if it's only one result to make it easier to parse. If you have access to modify the server code ofcourse.

Title: Iterate through Json data

Body:
So I have this array of JSON objects:

[
  {
    "columns": [
      {
        "fields": [
          {
            "valueFields": [
              {
                "type": 1,
                "fieldName": "prj_Name",
                "value": "1A BNL FB e-Powedr basic Balci Reizen",
                "valueId": "",
                "defaultValue": false,
                "baseValue": false,
                "mandatoryField": true,
                "hasError": false,
                "errorMessage": "",
                "disabled": false,
                "visible": true
              }
            ]
          }
        ]
      }
    ]
  }
]

and I would like to Iterate through the Data to do some stuff with it later.

I already tried this :

for (var key in currentObject) {
    if (currentObject.hasOwnProperty(key)) {
        console.log(key + ': ' + currentObject[key]);
    }
}

But it prints every letter separatly in the console, so I guess it isn't right.
Do you have any Ideas of what I am doing wrong ?

[EDIT]

I tried to add var currentObject = JSON.parse(Json); before the for loop.

I now get this printed 0: [object Object]

How to iterate through the object then ?

Body:
Your JsonObject is a JsonArray in a JsonArray in a JsonArray in a JsonArray...

Try the following code online, it works for your case

var x  = '[{"columns":[{"fields":[{"valueFields":[{"type":1,"fieldName":"prj_Name","value":"1A BNL FB e-Powedr basic BalciReizen","valueId":"","defaultValue":false,"baseValue":false,"mandatoryField":true,"hasError":false,"errorMessage":"","disabled":false,"visible":true}]}]}]}]';
var parsedJson = JSON.parse(x);
var valueFields = parsedJson[0].columns[0].fields[0].valueFields[0];

for (var key in valueFields) {
    if (valueFields.hasOwnProperty(key)) {
        console.log(key + ': ' + valueFields[key]);
    }
}

I would suggest to change the output if it's only one result to make it easier to parse. If you have access to modify the server code ofcourse.


答:
You also have to iterate over the "all" member:</p>

```<code>var html = "";
for (var i = 0; i < news.leaving.all.length; j++) {
   html +=
   '<p>' + news.leaving.all[i].departure_time '</p>';
}
</code>```

Title: Iterating object array within object - javascript?

Body:
You also have to iterate over the "all" member:

var html = "";
for (var i = 0; i < news.leaving.all.length; j++) {
   html +=
   '<p>' + news.leaving.all[i].departure_time '</p>';
}


问:
Telerik RadGridView selected item binding not working when clicking on button in datagrid properly
Hi I have a telerik RadGridView bound up to an observable collection via MVVM and the SelectedItem property of the grid is also bound to a property from within the model as well. There is then a button column that is bound to open the selected item to see more details of the selected item. The code for this is below.

```<code>           <telerik:RadGridView Name="RadGridView"
                         Height="900"
                         AutoGenerateColumns="False"
                         CanUserSortColumns="True"
                         IsReadOnly="True"
                         ItemsSource="{Binding Model.Items}"
                         SelectedItem="{Binding Model.SelectedItem,Mode=TwoWay}"
                         Width="990">
            <telerik:RadGridView.Columns>

                <telerik:GridViewColumn Header="Open Item" >
                    <telerik:GridViewColumn.CellTemplate>
                        <DataTemplate>
                            <Button Content="Open"
                                Command="{Binding Path=DataContext.OpenItemBySelectedItemCommand,
                                RelativeSource= {RelativeSource FindAncestor,
                                AncestorType={x:Type telerik:RadGridView}}}">
                            </Button>
                        </DataTemplate>
                    </telerik:GridViewColumn.CellTemplate>
                </telerik:GridViewColumn>

                <telerik:GridViewDataColumn DataMemberBinding="{Binding DateScanned}" Header="Date Scanned"  />
                <telerik:GridViewDataColumn DataMemberBinding="{Binding Amount}" Header="Amount"  />
                <telerik:GridViewDataColumn DataMemberBinding="{Binding Description}" Header="Description"  />
                <telerik:GridViewDataColumn DataMemberBinding="{Binding IsRefund}" Header="Is Refund"  />

            </telerik:RadGridView.Columns>
        </telerik:RadGridView>
</code>```

Now this code works fine whenever I click into the row then click the button, however if I just click the button of the row without clicking into the row first the SelectedItem property is not set and so the command does not function as expected.

I thought when clicking the button of a row it would auto select that row but apparently not. Does anyone know how I can get it to set the SelectedItem property whenever I only click on the button within a specific row without having to click on the row before clicking the button?

答:
You could pass a reference to the underlying data object as a command parameter to the command:

```<code><Button Content="Open"
        Command="{Binding Path=DataContext.OpenItemBySelectedItemCommand, RelativeSource= {RelativeSource FindAncestor, AncestorType={x:Type telerik:RadGridView}}}"
        CommandParameter="{Binding}">
</Button>
</code>```

For the row to actually become selected when you click on the Button, you will have to write some code that actually selects it. You could do this by handling the Button's Click event like this:

```<code>private void Button_Click_1(object sender, RoutedEventArgs e)
{
    Button button = sender as Button;
    RadGridView.SelectedItem = button.DataContext;
}
</code>```

```<code><Button Content="Open"
        Click="Button_Click_1"
        Command="{Binding Path=DataContext.OpenItemBySelectedItemCommand,
        RelativeSource= {RelativeSource FindAncestor,
        AncestorType={x:Type telerik:RadGridView}}}">
</Button>
</code>```

This does not break the MVVM pattern since selecting a row in the view is pure view functionality.

Body:
Hi I have a telerik RadGridView bound up to an observable collection via MVVM and the SelectedItem property of the grid is also bound to a property from within the model as well. There is then a button column that is bound to open the selected item to see more details of the selected item. The code for this is below.

           <telerik:RadGridView Name="RadGridView"
                         Height="900"
                         AutoGenerateColumns="False"
                         CanUserSortColumns="True"
                         IsReadOnly="True"
                         ItemsSource="{Binding Model.Items}"
                         SelectedItem="{Binding Model.SelectedItem,Mode=TwoWay}"
                         Width="990">
            <telerik:RadGridView.Columns>

                <telerik:GridViewColumn Header="Open Item" >
                    <telerik:GridViewColumn.CellTemplate>
                        <DataTemplate>
                            <Button Content="Open"
                                Command="{Binding Path=DataContext.OpenItemBySelectedItemCommand,
                                RelativeSource= {RelativeSource FindAncestor,
                                AncestorType={x:Type telerik:RadGridView}}}">
                            </Button>
                        </DataTemplate>
                    </telerik:GridViewColumn.CellTemplate>
                </telerik:GridViewColumn>

                <telerik:GridViewDataColumn DataMemberBinding="{Binding DateScanned}" Header="Date Scanned"  />
                <telerik:GridViewDataColumn DataMemberBinding="{Binding Amount}" Header="Amount"  />
                <telerik:GridViewDataColumn DataMemberBinding="{Binding Description}" Header="Description"  />
                <telerik:GridViewDataColumn DataMemberBinding="{Binding IsRefund}" Header="Is Refund"  />

            </telerik:RadGridView.Columns>
        </telerik:RadGridView>

Now this code works fine whenever I click into the row then click the button, however if I just click the button of the row without clicking into the row first the SelectedItem property is not set and so the command does not function as expected.

I thought when clicking the button of a row it would auto select that row but apparently not. Does anyone know how I can get it to set the SelectedItem property whenever I only click on the button within a specific row without having to click on the row before clicking the button?

Body:
You could pass a reference to the underlying data object as a command parameter to the command:

<Button Content="Open"
        Command="{Binding Path=DataContext.OpenItemBySelectedItemCommand, RelativeSource= {RelativeSource FindAncestor, AncestorType={x:Type telerik:RadGridView}}}"
        CommandParameter="{Binding}">
</Button>

For the row to actually become selected when you click on the Button, you will have to write some code that actually selects it. You could do this by handling the Button's Click event like this:

private void Button_Click_1(object sender, RoutedEventArgs e)
{
    Button button = sender as Button;
    RadGridView.SelectedItem = button.DataContext;
}

<Button Content="Open"
        Click="Button_Click_1"
        Command="{Binding Path=DataContext.OpenItemBySelectedItemCommand,
        RelativeSource= {RelativeSource FindAncestor,
        AncestorType={x:Type telerik:RadGridView}}}">
</Button>

This does not break the MVVM pattern since selecting a row in the view is pure view functionality.


问:
Long-held, incorrect programming assumptions
I am doing some research into common errors and poor assumptions made by junior (and perhaps senior) software engineers.

What was your longest-held assumption that was eventually corrected?

For example, I misunderstood that the size of an integer is not a standard and instead depends on the language and target.  A bit embarrassing to state, but there it is.

Be frank; what firm belief did you have, and roughly how long did you maintain the assumption?  It can be about an algorithm, a language, a programming concept, testing, or anything else about programming, programming languages, or computer science.

答:
that:

```<code>for (int i = 0; i < myObj.variable; i = i + 1)
</code>```

gets optimized to:

```<code>int j = myObj.variable;
for (int i = 0; i < j; i = i + 1)
</code>```

wow, i stopped putting in function calls in the place of j when I realized that they were being run EVERY time!

Reason:

```<code>for (int i = 0; i < myObj.variable; i = i + 1){
    if (function_argument == NULL){
        myObj.variable++;
    } else {
        printf("%d", myObj.variable);
    }
}
</code>```

is not the same as:

```<code>int j = myObj.variable;
for (int i = 0; i < j; i = i + 1){
    if (function_argument == NULL){
        myObj.variable++;
    } else {
        printf("%d", myObj.variable);
    }
}
</code>```

arbitrary example, but you can see how the optimization would change execution.

LastEditorDisplayName: Roger Pate

Body:
that:

for (int i = 0; i < myObj.variable; i = i + 1)

gets optimized to:

int j = myObj.variable;
for (int i = 0; i < j; i = i + 1)

wow, i stopped putting in function calls in the place of j when I realized that they were being run EVERY time!

Reason:

for (int i = 0; i < myObj.variable; i = i + 1){
    if (function_argument == NULL){
        myObj.variable++;
    } else {
        printf("%d", myObj.variable);
    }
}

is not the same as:

int j = myObj.variable;
for (int i = 0; i < j; i = i + 1){
    if (function_argument == NULL){
        myObj.variable++;
    } else {
        printf("%d", myObj.variable);
    }
}

arbitrary example, but you can see how the optimization would change execution.


问:
php ctype_digit not telling whether the string is numeric
I have a script that i want to use to process user input from the clients. I have several checks but the very first one requires the submitted string to be numeric.

This is the code

```<code><?php
$num = '09201x11222';

//Check whether the string is numeric
function test($str){
  return ctype_digit($str);
}

echo test($num);

echo '<br/><br/><br/>';

//Check if the length is exactly 10 characters
$len = strlen($num);
if($len < 10 || $len > 10){
  echo 'that number is wrong';
}
elseif($len == 10){
  echo 'that number is of required length';
}
echo '<br/><br/><br/>';
//Trim Leading Zero
$afterTrim = substr($num,1);

echo $afterTrim;

//Append countrycode 380
echo '<br/><br/><br/>';

$countryCode = '380';
$afterAppend = $countryCode.$afterTrim;

echo $afterAppend;

?>
</code>```

When the $num is correct, i get 1 on the screen but when its wrong i get nothing at all. Why is that?

答:
Echoing false will result in a "void" print.  This because a echo needs to cast a boolean to a string representation.

As you can see from method signature

```<code>bool ctype_digit ( string $text )
</code>```

this returns a boolean value that is converted by echo: if true, it will print 1, otherwise it will print nothing.

From manual

A boolean TRUE value is converted to the string "1". Boolean FALSE is converted to "" (the empty string). This allows conversion back and forth between boolean and string values.

Body:
I have a script that i want to use to process user input from the clients. I have several checks but the very first one requires the submitted string to be numeric.

This is the code

<?php
$num = '09201x11222';

//Check whether the string is numeric
function test($str){
  return ctype_digit($str);
}

echo test($num);

echo '

';

//Check if the length is exactly 10 characters
$len = strlen($num);
if($len < 10 || $len > 10){
  echo 'that number is wrong';
}
elseif($len == 10){
  echo 'that number is of required length';
}
echo '

';
//Trim Leading Zero
$afterTrim = substr($num,1);

echo $afterTrim;

//Append countrycode 380
echo '

';

$countryCode = '380';
$afterAppend = $countryCode.$afterTrim;

echo $afterAppend;

?>

When the $num is correct, i get 1 on the screen but when its wrong i get nothing at all. Why is that?

Body:
Echoing false will result in a "void" print.  This because a echo needs to cast a boolean to a string representation.

As you can see from method signature

bool ctype_digit ( string $text )

this returns a boolean value that is converted by echo: if true, it will print 1, otherwise it will print nothing.

From manual

A boolean TRUE value is converted to the string "1". Boolean FALSE is converted to "" (the empty string). This allows conversion back and forth between boolean and string values.