问:
Receive and send data from arduino to c# and vice versa
first of all I started using c# yesterday morning so I apologize for potential numb questions.

So far I wrote the following code. I'm able to send data from c# to arduino which seems to be working fine. Now i would like to receive data from arduino, through serial.print, at the same time and display it in a box (ListBox?). How could add this to the code?

I would be thankful for any input, tips and ideas.

```<code>namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {

        public Form1()
        {
            InitializeComponent();
            stop.Enabled = false;
            left.Enabled = false;
            right.Enabled = false;
            up.Enabled = false;
            down.Enabled = false;
            string[] ports = SerialPort.GetPortNames();
            comboBox1.Items.AddRange(ports);

        }
        private void Form1_Load(object sender, EventArgs e)
        {

        }
        private void start_Click(object sender, EventArgs e)
        {

            if (comboBox1.SelectedIndex > -1)
            {
                string port = (string)comboBox1.SelectedItem;
                serialPort2.PortName = port; // "port";
                serialPort2.BaudRate = 9600;
                serialPort2.Open();
                if (serialPort2.IsOpen)
                {
                    start.Enabled = false;
                    stop.Enabled = true;
                    left.Enabled = true;
                    right.Enabled = true;
                    up.Enabled = true;
                    down.Enabled = true;
                }
            }
                else
                {
                    MessageBox.Show("Please connect the Arduino and select a Port");
                }

        }
        private void stop_Click(object sender, EventArgs e)
        {
            if (serialPort2.IsOpen)
            {
                serialPort2.Close();
                start.Enabled = true;
                stop.Enabled = false;
                left.Enabled = false;
                right.Enabled = false;
                up.Enabled = false;
                down.Enabled = false;
            }
        }
        private void up_Click(object sender, EventArgs e)
        {

            if (serialPort2.IsOpen)
            {
                serialPort2.WriteLine("1");
            }

        }

        private void left_Click(object sender, EventArgs e)
        {

            if (serialPort2.IsOpen)
            {
                serialPort2.WriteLine("4");
            }

        }

        private void right_Click(object sender, EventArgs e)
        {
            if (serialPort2.IsOpen)
            {
                serialPort2.WriteLine("2");
            }
        }

        private void down_Click(object sender, EventArgs e)
        {
            if (serialPort2.IsOpen)
            {
                serialPort2.WriteLine("3");
            }
        }
</code>```

答:
I did the same like you, but I have used a Potentiometer.

The Pot analogic output is sent to C# over Serial; and C# application reads it.

The only difference is that I have used the protocols to read from Arduino.

Your Arduino Sketch Code depends on what you are trying to send and/or receive.
I'm providing my example. I hope this helps.

C# Code

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;
using System.Threading;
using System.Data;

namespace ArduinoValor
{
   internal class Class1
   {
    public string port = "";

    static SerialPort currentPort;

    public Boolean connect(int baud, string recognizeText, byte paramone, byte paramtwo, byte paramthree)
    {
        try
        {
            byte[] buffer = new byte[3];
            buffer[0] = Convert.ToByte(paramone);
            buffer[1] = Convert.ToByte(paramtwo); // For Details
            buffer[2] = Convert.ToByte(paramthree);

            int intReturnASCII = 0;
            char charReturnValue = (Char)intReturnASCII;
            string[] ports = SerialPort.GetPortNames();

            foreach (string newport in ports)
            {
                currentPort = new SerialPort(newport, baud);
                currentPort.Open(); // Open Serial Port (Use the Port)
                currentPort.Write(buffer, 0,3);
                Thread.Sleep(1000);
                int count = currentPort.BytesToRead; //Read bytes
                string returnMessage = "";

                while (count > 0)
                {
                    intReturnASCII = currentPort.ReadByte();
                    returnMessage = returnMessage + Convert.ToChar(intReturnASCII);
                    count--;
                }

                currentPort.Close();
                port = newport;

                if (returnMessage.Contains(recognizeText))
                {
                    return true;
                }
            }
            return false;
        }

        catch (Exception e) { return false; }
    }

    public string message(byte paramone, byte paramtwo, byte paramthree)
    {
        try
        {
            byte[] buffer = new byte[3];
            buffer[0] = Convert.ToByte(paramone);
            buffer[1] = Convert.ToByte(paramtwo);
            buffer[2] = Convert.ToByte(paramthree);

            currentPort.Open();
            currentPort.Write(buffer, 0, 3);

            int intReturnASCII = 0;
            char charReturnValue = (char)intReturnASCII;

            Thread.Sleep(1000);

            int count = currentPort.BytesToRead;
            string returnMessage = "";

            while (count > 0)
            {
                intReturnASCII = currentPort.ReadByte();
                returnMessage = returnMessage + Convert.ToChar(intReturnASCII);
                count--;
            }

            currentPort.Close();
            return returnMessage;
        }

        catch (Exception e) { return "Error"; }
    }
}
</code>```

}

Body:
first of all I started using c# yesterday morning so I apologize for potential numb questions.

So far I wrote the following code. I'm able to send data from c# to arduino which seems to be working fine. Now i would like to receive data from arduino, through serial.print, at the same time and display it in a box (ListBox?). How could add this to the code?

I would be thankful for any input, tips and ideas.

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {

        public Form1()
        {
            InitializeComponent();
            stop.Enabled = false;
            left.Enabled = false;
            right.Enabled = false;
            up.Enabled = false;
            down.Enabled = false;
            string[] ports = SerialPort.GetPortNames();
            comboBox1.Items.AddRange(ports);

        }
        private void Form1_Load(object sender, EventArgs e)
        {

        }
        private void start_Click(object sender, EventArgs e)
        {

            if (comboBox1.SelectedIndex > -1)
            {
                string port = (string)comboBox1.SelectedItem;
                serialPort2.PortName = port; // "port";
                serialPort2.BaudRate = 9600;
                serialPort2.Open();
                if (serialPort2.IsOpen)
                {
                    start.Enabled = false;
                    stop.Enabled = true;
                    left.Enabled = true;
                    right.Enabled = true;
                    up.Enabled = true;
                    down.Enabled = true;
                }
            }
                else
                {
                    MessageBox.Show("Please connect the Arduino and select a Port");
                }

        }
        private void stop_Click(object sender, EventArgs e)
        {
            if (serialPort2.IsOpen)
            {
                serialPort2.Close();
                start.Enabled = true;
                stop.Enabled = false;
                left.Enabled = false;
                right.Enabled = false;
                up.Enabled = false;
                down.Enabled = false;
            }
        }
        private void up_Click(object sender, EventArgs e)
        {

            if (serialPort2.IsOpen)
            {
                serialPort2.WriteLine("1");
            }

        }

        private void left_Click(object sender, EventArgs e)
        {

            if (serialPort2.IsOpen)
            {
                serialPort2.WriteLine("4");
            }

        }

        private void right_Click(object sender, EventArgs e)
        {
            if (serialPort2.IsOpen)
            {
                serialPort2.WriteLine("2");
            }
        }

        private void down_Click(object sender, EventArgs e)
        {
            if (serialPort2.IsOpen)
            {
                serialPort2.WriteLine("3");
            }
        }

Body:
I did the same like you, but I have used a Potentiometer.

The Pot analogic output is sent to C# over Serial; and C# application reads it.

The only difference is that I have used the protocols to read from Arduino.

Your Arduino Sketch Code depends on what you are trying to send and/or receive.
I'm providing my example. I hope this helps.

C# Code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;
using System.Threading;
using System.Data;

namespace ArduinoValor
{
   internal class Class1
   {
    public string port = "";

    static SerialPort currentPort;

    public Boolean connect(int baud, string recognizeText, byte paramone, byte paramtwo, byte paramthree)
    {
        try
        {
            byte[] buffer = new byte[3];
            buffer[0] = Convert.ToByte(paramone);
            buffer[1] = Convert.ToByte(paramtwo); // For Details
            buffer[2] = Convert.ToByte(paramthree);

            int intReturnASCII = 0;
            char charReturnValue = (Char)intReturnASCII;
            string[] ports = SerialPort.GetPortNames();

            foreach (string newport in ports)
            {
                currentPort = new SerialPort(newport, baud);
                currentPort.Open(); // Open Serial Port (Use the Port)
                currentPort.Write(buffer, 0,3);
                Thread.Sleep(1000);
                int count = currentPort.BytesToRead; //Read bytes
                string returnMessage = "";

                while (count > 0)
                {
                    intReturnASCII = currentPort.ReadByte();
                    returnMessage = returnMessage + Convert.ToChar(intReturnASCII);
                    count--;
                }

                currentPort.Close();
                port = newport;

                if (returnMessage.Contains(recognizeText))
                {
                    return true;
                }
            }
            return false;
        }

        catch (Exception e) { return false; }
    }

    public string message(byte paramone, byte paramtwo, byte paramthree)
    {
        try
        {
            byte[] buffer = new byte[3];
            buffer[0] = Convert.ToByte(paramone);
            buffer[1] = Convert.ToByte(paramtwo);
            buffer[2] = Convert.ToByte(paramthree);

            currentPort.Open();
            currentPort.Write(buffer, 0, 3);

            int intReturnASCII = 0;
            char charReturnValue = (char)intReturnASCII;

            Thread.Sleep(1000);

            int count = currentPort.BytesToRead;
            string returnMessage = "";

            while (count > 0)
            {
                intReturnASCII = currentPort.ReadByte();
                returnMessage = returnMessage + Convert.ToChar(intReturnASCII);
                count--;
            }

            currentPort.Close();
            return returnMessage;
        }

        catch (Exception e) { return "Error"; }
    }
}

}


来源: stackexchange

问:
Match sequence at the very beginning of a string along with other sequences in the middle
I'm trying to find a way to match 2 patterns in the same regular expression, but I can't seem to be able to combine both. These are a few strings I'm trying to match against:

```<code>0 800-204-4000
0800-204 4000
0 800 -204 - 4000
800 204 4000
</code>```

What I'm trying to do is find a regular expression that matches a zero at the beginning of a string if it exists and all subsequent white spaces and dashes. So I was able to match the first zero if it exists using /^0?/ and match all empty spaces and dashes using /[\s-]*/g but how exactly can I combine both into the same expression?

Edit:

So I want to match the first 0 IF it exists and all following spaces and dashes. So in the examples above, what should be matched is in brackets:

```<code>[0 ]800[-]204[-]4000
[0]800[-]204[ ]4000
[0 ]800[ -]204[ - ]4000
800[ ]204[ ]4000
</code>```

The regex provided in the answers do not work. Check it out: https://regex101.com/r/dMN6xR/1

答: Drawing on the others' answers, you can use /^0[-\s]*|[-\s]+/g.  I've used [- ] in the demo because I don't like how difficult it is to read when newlines are removed.

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to find a way to match 2 patterns in the same regular expression, but I can't seem to be able to combine both. These are a few strings I'm trying to match against:

0 800-204-4000
0800-204 4000
0 800 -204 - 4000
800 204 4000

What I'm trying to do is find a regular expression that matches a zero at the beginning of a string if it exists and all subsequent white spaces and dashes. So I was able to match the first zero if it exists using /^0?/ and match all empty spaces and dashes using /[\s-]*/g but how exactly can I combine both into the same expression?

Edit:

So I want to match the first 0 IF it exists and all following spaces and dashes. So in the examples above, what should be matched is in brackets:

[0 ]800[-]204[-]4000
[0]800[-]204[ ]4000
[0 ]800[ -]204[ - ]4000
800[ ]204[ ]4000

The regex provided in the answers do not work. Check it out: https://regex101.com/r/dMN6xR/1


问:
Tmeout in Linux in order to run a command for a certain time
I am trying to run this command for 1 second:

```<code>#!/bin/bash
# rsync using variables
epoch=$(date +%s)
u_id=100
id=1
timeout 5 echo $id",Danny_"$id","$id","$epoch","$u_id >> lfs.csv
</code>```

It doesn't seem to run 5 seconds, so I tried to run it before execution of my script:
timeout 5 lfs_to.sh. Which did not do the trick as well.

答:
timeout command is limiting the command that you are running for the specific amount of time that you set.
in your case the command is finishing way before 5 seconds that you set.

```<code>[aa@vm007 ~]$ timeout 5 find / 1>/dev/null 2>/dev/null <-- finished after 5 seconds
[aa@vm007 ~]$ time timeout 5 find / 1>/dev/null 2>/dev/null <-- actual time that it takes to run with timeout command
</code>```

and the output:

```<code>real    0m5.016s
user    0m0.008s
sys     0m0.037s
</code>```

Body:
I am trying to run this command for 1 second:

#!/bin/bash
# rsync using variables
epoch=$(date +%s)
u_id=100
id=1
timeout 5 echo $id",Danny_"$id","$id","$epoch","$u_id >> lfs.csv

It doesn't seem to run 5 seconds, so I tried to run it before execution of my script:
timeout 5 lfs_to.sh. Which did not do the trick as well.

Body:
timeout command is limiting the command that you are running for the specific amount of time that you set.
in your case the command is finishing way before 5 seconds that you set.

[aa@vm007 ~]$ timeout 5 find / 1>/dev/null 2>/dev/null <-- finished after 5 seconds
[aa@vm007 ~]$ time timeout 5 find / 1>/dev/null 2>/dev/null <-- actual time that it takes to run with timeout command

and the output:

real    0m5.016s
user    0m0.008s
sys     0m0.037s


问:
How to release Outlook objects correctly?
I just can't release my Outlook MailItems. After opening 200 Mails the Exchange Sever  returns the maximum open Emails is reached.

I'm remove my UserProperty from all selected Mail.

My Code:

```<code>
foreach (var selection in Globals.ThisAddIn.Application.ActiveExplorer().Selection)
{
 if (selection is MailItem)
 {
  MailItem mi = (MailItem)selection;
  UserProperty up = mi.UserProperties.Find("MyProp");
  if (up != null)
  {
   up.Delete();
   //##################################
   // I also tried :
   //----------------------------------
   //    Marshal.ReleaseComObject(up);
   //    up = null;
   //----------------------------------
  }

  mi.Save();

  //##################################
  // I also tried :
  //----------------------------------
  //     mi.Close(OlInspectorClose.olDiscard);
  //----------------------------------

  // I don't know if this loop is necessary, but I have found it somewhere on the web
  while (Marshal.ReleaseComObject(mi) > 0);
  mi = null;

  //##################################
  // I also tried :
  //----------------------------------
  //    GC.Collect();
  //    GC.WaitForPendingFinalizers();
  //----------------------------------
 }
}</code>```

Any idea what's wrong?

答:
I believe its any kind of bug like Bolu said.
Again much thanks for your help Bolu.

I'm now using following workaround:

```<code>List entryids = new List();

foreach (var selection in Globals.ThisAddIn.Application.ActiveExplorer().Selection)
{
    MailItem mi = selection as MailItem;
    if (mi != null)
    {
        // For any reason it's not possible to change the mail here

        entryids.Add(mi.EntryID);

        Marshal.ReleaseComObject(mi);
        mi = null;

    }
}

foreach (string id in entryids)
{
    MailItem mi = Globals.ThisAddIn.Application.ActiveExplorer().Session.GetItemFromID(id);

    // My changes on the mail

    mi.Save();
    Marshal.ReleaseComObject(mi);
    mi = null;
}</code>```

ContentLicense: CC BY-SA 4.0

Body:
I just can't release my Outlook MailItems. After opening 200 Mails the Exchange Sever  returns the maximum open Emails is reached.

I'm remove my UserProperty from all selected Mail.

My Code:

foreach (var selection in Globals.ThisAddIn.Application.ActiveExplorer().Selection)
{
 if (selection is MailItem)
 {
  MailItem mi = (MailItem)selection;
  UserProperty up = mi.UserProperties.Find("MyProp");
  if (up != null)
  {
   up.Delete();
   //##################################
   // I also tried :
   //----------------------------------
   //    Marshal.ReleaseComObject(up);
   //    up = null;
   //----------------------------------
  }

  mi.Save();

  //##################################
  // I also tried :
  //----------------------------------
  //     mi.Close(OlInspectorClose.olDiscard);
  //----------------------------------

  // I don't know if this loop is necessary, but I have found it somewhere on the web
  while (Marshal.ReleaseComObject(mi) > 0);
  mi = null;

  //##################################
  // I also tried :
  //----------------------------------
  //    GC.Collect();
  //    GC.WaitForPendingFinalizers();
  //----------------------------------
 }
}

Any idea what's wrong?

Body:
I believe its any kind of bug like Bolu said.
Again much thanks for your help Bolu.

I'm now using following workaround:

List entryids = new List();

foreach (var selection in Globals.ThisAddIn.Application.ActiveExplorer().Selection)
{
    MailItem mi = selection as MailItem;
    if (mi != null)
    {
        // For any reason it's not possible to change the mail here

        entryids.Add(mi.EntryID);

        Marshal.ReleaseComObject(mi);
        mi = null;

    }
}

foreach (string id in entryids)
{
    MailItem mi = Globals.ThisAddIn.Application.ActiveExplorer().Session.GetItemFromID(id);

    // My changes on the mail

    mi.Save();
    Marshal.ReleaseComObject(mi);
    mi = null;
}

ContentLicense: CC BY-SA 2.5


问:
Calculator doesn't execute the operations
I am trying to build a calculator in abap. The requirements are:

Reads

two numbers (ex. 56.3 and 78.2)

a character from the following list: q, w, e, r, t

Displays the result of the operation specified by the character

Addition for character q

Subtraction for character w

Multiplication for character e

Division for character r

Exponent for character t

I have created a table with the operations that I am using in the calculator.
The problem is when I execute the program it only prints my last option (else) "the operation is not possible".

Here's the code I wrote:

```<code>REPORT Z_CALCULATOR_V2.

TABLES: ZOPERATII.
DATA result type p decimals 2.
DATA Q type c.
DATA W like Q.
DATA E like Q.
DATA R like Q.
DATA T like Q.

PARAMETERS Nr_1 type p decimals 2 OBLIGATORY.
PARAMETERS Nr_2 like Nr_1 OBLIGATORY.
PARAMETERS Operatie LIKE zoperatii-operatie OBLIGATORY.

if Operatie = Q.
  result = Nr_1 + Nr_2.

elseif Operatie = W.
    result = Nr_1 - Nr_2.

elseif Operatie = E.

elseif Operatie = R.
        result = Nr_1 / Nr_2.

elseif Operatie = T.
       result = Nr_1 ** Nr_2.

else.
  WRITE 'The operation is not possible'.
  endif.
  write result.
</code>```

答:
if you change the data declarations to:

```<code>DATA Q type c value 'Q'.
DATA W type c value 'W'.
DATA E type c value 'E'.
DATA R type c value 'R'.
DATA T type c value 'T'.
</code>```

the code should run as you expect.  That said, you should read up on the documentation as suggested in the comments.

Body:
I am trying to build a calculator in abap. The requirements are:

Reads

two numbers (ex. 56.3 and 78.2)

a character from the following list: q, w, e, r, t

Displays the result of the operation specified by the character

Addition for character q

Subtraction for character w

Multiplication for character e

Division for character r

Exponent for character t

I have created a table with the operations that I am using in the calculator.
The problem is when I execute the program it only prints my last option (else) "the operation is not possible".

Here's the code I wrote:

REPORT Z_CALCULATOR_V2.

TABLES: ZOPERATII.
DATA result type p decimals 2.
DATA Q type c.
DATA W like Q.
DATA E like Q.
DATA R like Q.
DATA T like Q.

PARAMETERS Nr_1 type p decimals 2 OBLIGATORY.
PARAMETERS Nr_2 like Nr_1 OBLIGATORY.
PARAMETERS Operatie LIKE zoperatii-operatie OBLIGATORY.

if Operatie = Q.
  result = Nr_1 + Nr_2.

elseif Operatie = W.
    result = Nr_1 - Nr_2.

elseif Operatie = E.

elseif Operatie = R.
        result = Nr_1 / Nr_2.

elseif Operatie = T.
       result = Nr_1 ** Nr_2.

else.
  WRITE 'The operation is not possible'.
  endif.
  write result.

Body:
if you change the data declarations to:

DATA Q type c value 'Q'.
DATA W type c value 'W'.
DATA E type c value 'E'.
DATA R type c value 'R'.
DATA T type c value 'T'.

the code should run as you expect.  That said, you should read up on the documentation as suggested in the comments.


问:
Saving Bitmap Image without shrinking width and height
What im trying to do is to save an edited bitmap that is composed by 2 bitmaps overlayed. My application allows the user to draw on top of a picture and save it.

My problem is: when i save the result image, it gets smaller, even setting the quality to 100. So, if the user saves and edit the image multiple times, the image will get smaller and smaller.

I save the bitmap with this:

```<code>result.compress(Bitmap.CompressFormat.JPEG, 100, fos);
</code>```

I debugged the code, and at this point the width and height are fine, but after saving, the image shrinks.

I've researched for questions about this, but the ones i've found had no answers that could help me.

What i need is a way to save a bitmap without shrinking it, but i need it to be in image format, like JPG, PNG, etc.

Thanks in advance.

答: I guess is not at the time when you are saving the image, the issue is when you are editing the image (creating layers). Check that mechanism, maybe you are setting the image size there.</p>

Body:
What im trying to do is to save an edited bitmap that is composed by 2 bitmaps overlayed. My application allows the user to draw on top of a picture and save it.

My problem is: when i save the result image, it gets smaller, even setting the quality to 100. So, if the user saves and edit the image multiple times, the image will get smaller and smaller.

I save the bitmap with this:

result.compress(Bitmap.CompressFormat.JPEG, 100, fos);

I debugged the code, and at this point the width and height are fine, but after saving, the image shrinks.

I've researched for questions about this, but the ones i've found had no answers that could help me.

What i need is a way to save a bitmap without shrinking it, but i need it to be in image format, like JPG, PNG, etc.

Thanks in advance.


问:
Haskell pre-monadic I/O
I wonder how I/O were done in Haskell in the days when IO monad was still not invented. Anyone knows an example.

Edit: Can I/O be done without the IO Monad in modern Haskell? I'd prefer an example that works with modern GHC.

答:
@sepp2k already clarified how this works, but i wanted to add a few words

I'm really sorry for this. I don't think it is possible to write this function without unsafePerformIO

Of course you can, you should almost never use unsafePerformIO
http://chrisdone.com/posts/haskellers

I'm using slightly different Request type constructor, so that it does not take channel version (stdin / stdout like in @sepp2k's code). Here is my solution for this:

(Note: getFirstReq doesn't work on empty list, you would have to add a case for that, bu it should be trivial)

data Request = Readline
             | PutStrLn String

data Response = Success
              | Str String

type Dialog = [Response] -> [Request]

execRequest :: Request -> IO Response
execRequest Readline = getLine >>= \s -> return (Str s)
execRequest (PutStrLn s) = putStrLn s >> return Success

dialogToIOMonad :: Dialog -> IO ()
dialogToIOMonad dialog =
    let getFirstReq :: Dialog -> Request
        getFirstReq dialog = let (req:_) = dialog [] in req

        getTailReqs :: Dialog -> Response -> Dialog
        getTailReqs dialog resp =
            \resps -> let (_:reqs) = dialog (resp:resps) in reqs
    in do
        let req = getFirstReq dialog
        resp <- execRequest req
        dialogToIOMonad (getTailReqs dialog resp)
```

Title: Haskell pre-monadic I/O


问:
Why is kivy read_pixel not returning expected color?
I am trying to create markers on an image that would allow a user to select colors, mark features etc. Ultimately I would like to have the corresponding image pixel for further use via opencv.

I'm having a lot of trouble getting the expected color under the touch and it sometimes returns colors like magenta which are not even in the example image.

I am pretty sure the problem is with how I am converting the touch position to the values I am handing to the read_pixel function.

I have tried many different solutions without success so I think there is something I am missing here.

main.py

```<code>from kivy.app import App
from kivy.properties import ListProperty, ObjectProperty
from kivy.uix.image import AsyncImage
from kivy.uix.relativelayout import RelativeLayout
from kivy.uix.widget import Widget
from kivy.uix.screenmanager import ScreenManager, Screen

class Marker(Widget):
    selected_color = ListProperty([0,1,0])

    def __init__(self, **kwargs):
        super(Marker, self).__init__(**kwargs)
        self.selected_pos = None

    def on_touch_down(self, touch):
        if self.collide_point(*touch.pos):
            print("Touched at Marker: {0}".format(touch.spos))

    def on_touch_move(self, touch):
        self.set_position_from_touch(touch.spos)

    def set_position_from_touch(self, spos):
        # print("touch: {0}".format(touch))
        self.image = self.parent.parent.image
        x = spos[0] * self.image.width
        y = spos[1] * self.image.height

        # setting position of the widget relative to touch
        self.pos = (x-self.width/2, y-self.height*(2/3))
        # self.pos = (x, y)

        print("widget position : {0}".format(self.pos))
        # converting widget position to pixel(row, column of
        selected_pixel = self.image.to_row_col(self.pos)
        print("selected Pixel: {0}".format(selected_pixel))

        try:
            self.selected_color = self.image._coreimage.read_pixel(
                selected_pixel[0],
                selected_pixel[1])
                # this skips conversion and just uses pos
                # self.pos[0],
                # self.pos[1])
        except IndexError:
            print("position out of range")

class MarkerManager(RelativeLayout):
    def __init__(self, **kwargs):
        super(MarkerManager, self).__init__(**kwargs)
        self.marker_mode = None
        self.features = []

    def on_touch_down(self, touch):
        if self.collide_point(*touch.pos):
            child_touched = False
            print("Touched: {0}".format(touch))
            if self.children:
                for child in self.children[:]:
                    if child.collide_point(touch.pos[0], touch.pos[1]):
                        child_touched = True
                        child.dispatch('on_touch_down', touch)
            if not child_touched:
                print("Touched only Image at: {0}".format(touch.spos))
                marker = Marker()
                self.features.append(marker)
                self.add_widget(marker)
                marker.set_position_from_touch(touch.spos)

class SelectedImage(AsyncImage):
    def __init__(self, **kwargs):
        super(SelectedImage, self).__init__(**kwargs)
        self.allow_stretch=True
        self.keep_ratio=False

    def to_row_col(self, pos):
        pixels_x = self._coreimage.width
        pixels_y = self._coreimage.height
        pixel_x = (pos[0] / self.width) * pixels_x
        # pixel_y = (pos[1] / self.height) * self.pixels_y
        pixel_y = (1 - (pos[1] / self.height)) * pixels_y
        # should correspond to row column of image
        return [int(pixel_x), int(pixel_y)]

class ImageScreen(Screen):
    image = ObjectProperty()
    manager = ObjectProperty()
    def __init__(self, **kwargs):
        super(ImageScreen, self).__init__(**kwargs)

class PointsSelectorApp(App):
    def build(self):
        return ImageScreen()

if __name__ == "__main__":
    PointsSelectorApp().run()
</code>```

pointsselector.kv

```<code><ImageScreen>:
    image: image_id
    manager: manager_id

    SelectedImage:
        id: image_id
        source: "rainbow_checkerboard.jpg"
        keep_data: True

    MarkerManager:
        id: manager_id

<Marker>:
    size_hint: None, None
    size: "40dp", "40dp"
    canvas:
        Color:
            rgb: self.selected_color
        Ellipse:
            pos: self.pos[0]+self.width/4, self.pos[1]+self.height/3
#            pos: self.pos[0], self.pos[1]
            size: self.width*.6, self.height*.6
</code>```

here is my image i have been using to test with "rainbow_checkerboard.jpg"

答:
I believe this is a bug in the Kivy itself. Particularly I think that line 901 at the kivy/core/image/__init__.py

    index = y * data.width * size + x * size
    raw = bytearray(data.data[index:index + size])
    color = [c / 255.0 for c in raw]
```

<p>is wrong. It should be</p>

<pre class="lang-python prettyprint-override"><code>    index = y * data.rowlength + x * size
</code>```

instead.

Important thing here is that for performance reasons bitmap images in memory are alligned at 4 bytes addresses. Thus there is an explicit data.rowlength field. Usually that line works fine because images are typically well alligned so that data.rowlength = data.width * size. But your particular image is different: it uses 3-bytes RGB format (no alpha) and its width is odd 561 i.e. data.width * size =  1683 and so data.rowlength should be rounded up to 1684, which it actually is but that code doesn't take it into account. It means that often you read colors from two consecutive pixels and with RGB components randomly rotated.

Additionally since you use JPEG format for your image, borders between "cells" are not really strict. If you zoom in really hard, you can see some compression artifacts such as these from around bottom-left corner.

Those artifacts mutliplied by the aforementioned random color components rotation bug give you very strange (seemingly non-existent) colors.

Possible workarounds

Change your image so that it is pre-aligned in the memory and the bug doesn't affect you (for example use mutliple of 4 as width)

Submit a bug or even a pull request to the Kivy and wait for it to be fixed

Patch kivy/core/image/__init__.py file locally (I tried it and it seems to work fine).

Body:
I am trying to create markers on an image that would allow a user to select colors, mark features etc. Ultimately I would like to have the corresponding image pixel for further use via opencv.

I'm having a lot of trouble getting the expected color under the touch and it sometimes returns colors like magenta which are not even in the example image.

I am pretty sure the problem is with how I am converting the touch position to the values I am handing to the read_pixel function.

I have tried many different solutions without success so I think there is something I am missing here.

main.py

from kivy.app import App
from kivy.properties import ListProperty, ObjectProperty
from kivy.uix.image import AsyncImage
from kivy.uix.relativelayout import RelativeLayout
from kivy.uix.widget import Widget
from kivy.uix.screenmanager import ScreenManager, Screen

class Marker(Widget):
    selected_color = ListProperty([0,1,0])

    def __init__(self, **kwargs):
        super(Marker, self).__init__(**kwargs)
        self.selected_pos = None

    def on_touch_down(self, touch):
        if self.collide_point(*touch.pos):
            print("Touched at Marker: {0}".format(touch.spos))

    def on_touch_move(self, touch):
        self.set_position_from_touch(touch.spos)

    def set_position_from_touch(self, spos):
        # print("touch: {0}".format(touch))
        self.image = self.parent.parent.image
        x = spos[0] * self.image.width
        y = spos[1] * self.image.height

        # setting position of the widget relative to touch
        self.pos = (x-self.width/2, y-self.height*(2/3))
        # self.pos = (x, y)

        print("widget position : {0}".format(self.pos))
        # converting widget position to pixel(row, column of
        selected_pixel = self.image.to_row_col(self.pos)
        print("selected Pixel: {0}".format(selected_pixel))

        try:
            self.selected_color = self.image._coreimage.read_pixel(
                selected_pixel[0],
                selected_pixel[1])
                # this skips conversion and just uses pos
                # self.pos[0],
                # self.pos[1])
        except IndexError:
            print("position out of range")

class MarkerManager(RelativeLayout):
    def __init__(self, **kwargs):
        super(MarkerManager, self).__init__(**kwargs)
        self.marker_mode = None
        self.features = []

    def on_touch_down(self, touch):
        if self.collide_point(*touch.pos):
            child_touched = False
            print("Touched: {0}".format(touch))
            if self.children:
                for child in self.children[:]:
                    if child.collide_point(touch.pos[0], touch.pos[1]):
                        child_touched = True
                        child.dispatch('on_touch_down', touch)
            if not child_touched:
                print("Touched only Image at: {0}".format(touch.spos))
                marker = Marker()
                self.features.append(marker)
                self.add_widget(marker)
                marker.set_position_from_touch(touch.spos)

class SelectedImage(AsyncImage):
    def __init__(self, **kwargs):
        super(SelectedImage, self).__init__(**kwargs)
        self.allow_stretch=True
        self.keep_ratio=False

    def to_row_col(self, pos):
        pixels_x = self._coreimage.width
        pixels_y = self._coreimage.height
        pixel_x = (pos[0] / self.width) * pixels_x
        # pixel_y = (pos[1] / self.height) * self.pixels_y
        pixel_y = (1 - (pos[1] / self.height)) * pixels_y
        # should correspond to row column of image
        return [int(pixel_x), int(pixel_y)]

class ImageScreen(Screen):
    image = ObjectProperty()
    manager = ObjectProperty()
    def __init__(self, **kwargs):
        super(ImageScreen, self).__init__(**kwargs)

class PointsSelectorApp(App):
    def build(self):
        return ImageScreen()

if __name__ == "__main__":
    PointsSelectorApp().run()

pointsselector.kv

<ImageScreen>:
    image: image_id
    manager: manager_id

    SelectedImage:
        id: image_id
        source: "rainbow_checkerboard.jpg"
        keep_data: True

    MarkerManager:
        id: manager_id

<Marker>:
    size_hint: None, None
    size: "40dp", "40dp"
    canvas:
        Color:
            rgb: self.selected_color
        Ellipse:
            pos: self.pos[0]+self.width/4, self.pos[1]+self.height/3
#            pos: self.pos[0], self.pos[1]
            size: self.width*.6, self.height*.6

here is my image i have been using to test with "rainbow_checkerboard.jpg"

Body:
I believe this is a bug in the Kivy itself. Particularly I think that line 901 at the kivy/core/image/__init__.py

    index = y * data.width * size + x * size
    raw = bytearray(data.data[index:index + size])
    color = [c / 255.0 for c in raw]

is wrong. It should be

    index = y * data.rowlength + x * size

instead.

Important thing here is that for performance reasons bitmap images in memory are alligned at 4 bytes addresses. Thus there is an explicit data.rowlength field. Usually that line works fine because images are typically well alligned so that data.rowlength = data.width * size. But your particular image is different: it uses 3-bytes RGB format (no alpha) and its width is odd 561 i.e. data.width * size =  1683 and so data.rowlength should be rounded up to 1684, which it actually is but that code doesn't take it into account. It means that often you read colors from two consecutive pixels and with RGB components randomly rotated.

Additionally since you use JPEG format for your image, borders between "cells" are not really strict. If you zoom in really hard, you can see some compression artifacts such as these from around bottom-left corner.

Those artifacts mutliplied by the aforementioned random color components rotation bug give you very strange (seemingly non-existent) colors.

Possible workarounds

Change your image so that it is pre-aligned in the memory and the bug doesn't affect you (for example use mutliple of 4 as width)

Submit a bug or even a pull request to the Kivy and wait for it to be fixed

Patch kivy/core/image/__init__.py file locally (I tried it and it seems to work fine).


问:
Sending Buttons to the back of Layout
I am trying to add List Session header and add hidden buttons at the back.

Kindly help me to send Del Button and Edit Button to back of session header. It will be viewed after a swipe.

I also tried bringToFront and sendToBack on buttons which dint work.

To Set Z Order, I need to set Project min SDK to 21 which I dont want to do. SO I cant use Z order also.

```<code> RelativeLayout SupRelLyoVar = new RelativeLayout(KxtVar);
 RelativeLayout.LayoutParams NamLysHtrRloRulVaj = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, LyHtrHytVal);
 SupRelLyoVar.setLayoutParams(NamLysHtrRloRulVaj);

 Button DelBtnVav = new Button(KxtVar);
 DelBtnVav.setId(View.generateViewId());
 RelativeLayout.LayoutParams DelBtnRulVaj = new RelativeLayout.LayoutParams(LyHtrHytVal, LyHtrHytVal);
 DelBtnRulVaj.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
 DelBtnVav.setLayoutParams(DelBtnRulVaj);
 SupRelLyoVar.addView(DelBtnVav);

 Button EdtBtnVav = new Button(KxtVar);
 RelativeLayout.LayoutParams EdtBtnRulVaj = new RelativeLayout.LayoutParams(LyHtrHytVal, LyHtrHytVal);
 EdtBtnRulVaj.addRule(RelativeLayout.LEFT_OF, DelBtnVav.getId());
 EdtBtnVav.setLayoutParams(EdtBtnRulVaj);
 SupRelLyoVar.addView(EdtBtnVav);

 LinearLayout LnrLyoVar = new LinearLayout(KxtVar);
 LnrLyoVar.setBackgroundColor(SsnHtrBgdClr);
 RelativeLayout.LayoutParams LnrLyoRulVaj = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, LyHtrHytVal);
 LnrLyoRulVaj.addRule(RelativeLayout.CENTER_IN_PARENT);

 TextView TxtVyuVav = new TextView(KxtVar);
 LinearLayout.LayoutParams LysHtrTxtVyuRulVaj = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
 TxtVyuVav.setLayoutParams(LysHtrTxtVyuRulVaj);
 LnrLyoVar.addView(TxtVyuVav);

 SupRelLyoVar.addView(LnrLyoVar, LnrLyoRulVaj);
</code>```

答:
I got solution and like to post

This is for all whom I wish not to struggle like me.

|*| Set OnTouchListener :

```<code>LnrLyoVar.setOnTouchListener(WkaMovLitRitVyuKlkVaf);
</code>```

|*| Use below outside function :

```<code>View.OnTouchListener WkaMovLitRitVyuKlkVaf = new View.OnTouchListener()
{
    float WkaStrVyuXcoVar, WkaStrTchXcoVar, WkaStpTchXcoVar;
    final int MovDstVar = LloHytVal * 2;
    RelativeLayout.LayoutParams EdtBtnRulVaj, DelBtnRulVaj;

    @Override
    public boolean onTouch(View VyuPsgVar, MotionEvent MsnEvtPsgVar)
    {
        switch (MsnEvtPsgVar.getActionMasked())
        {
            case MotionEvent.ACTION_DOWN:
                WkaStrTchXcoVar = MsnEvtPsgVar.getRawX();
                WkaStrVyuXcoVar = (int) VyuPsgVar.getX();
                break;

            case MotionEvent.ACTION_MOVE:
                WkaStpTchXcoVar = MsnEvtPsgVar.getRawX();
                float XcoDstVar = Math.abs(WkaStpTchXcoVar - WkaStrTchXcoVar);

                if (XcoDstVar < MovDstVar)
                {
                    EdtBtnRulVaj = (RelativeLayout.LayoutParams) NamEdtBtnVav.getLayoutParams();
                    DelBtnRulVaj = (RelativeLayout.LayoutParams) NamDelBtnVav.getLayoutParams();
                    int SetBtnWytVar;
                    if (WkaStrVyuXcoVar == 0)
                    {
                        VyuPsgVar.animate()
                                .translationX(-XcoDstVar)
                                .setDuration(0)
                                .start();
                        SetBtnWytVar = (int) XcoDstVar / 2;
                    }
                    else
                    {
                        VyuPsgVar.animate()
                                .x(-MovDstVar + XcoDstVar)
                                .setDuration(0)
                                .start();
                        SetBtnWytVar = (int) (LloHytVal - XcoDstVar / 2);
                    }
                    DelBtnRulVaj.width = SetBtnWytVar;
                    EdtBtnRulVaj.width = SetBtnWytVar;
                    NamEdtBtnVav.setLayoutParams(EdtBtnRulVaj);
                    NamDelBtnVav.setLayoutParams(DelBtnRulVaj);
                }
                break;

            case MotionEvent.ACTION_UP :
            case MotionEvent.ACTION_CANCEL:
                EdtBtnRulVaj = (RelativeLayout.LayoutParams) NamEdtBtnVav.getLayoutParams();
                DelBtnRulVaj = (RelativeLayout.LayoutParams) NamDelBtnVav.getLayoutParams();
                int SetBtnWytVar = 0;
                if (WkaStrVyuXcoVar == 0 && WkaStpTchXcoVar < WkaStrTchXcoVar)
                {
                    VyuPsgVar.animate()
                            .x(-MovDstVar);
                    SetBtnWytVar = LloHytVal;
                }
                else if (WkaStrVyuXcoVar == -MovDstVar)
                {
                    VyuPsgVar.animate()
                            .x(0);
                    SetBtnWytVar = 0;
                }
                DelBtnRulVaj.width = SetBtnWytVar;
                EdtBtnRulVaj.width = SetBtnWytVar;
                NamEdtBtnVav.setLayoutParams(EdtBtnRulVaj);
                NamDelBtnVav.setLayoutParams(DelBtnRulVaj);
                break;
        }
        return true;
    }
};
</code>```

Title: Sending Buttons to the back of Layout

Body:
I am trying to add List Session header and add hidden buttons at the back.

Kindly help me to send Del Button and Edit Button to back of session header. It will be viewed after a swipe.

I also tried bringToFront and sendToBack on buttons which dint work.

To Set Z Order, I need to set Project min SDK to 21 which I dont want to do. SO I cant use Z order also.

 RelativeLayout SupRelLyoVar = new RelativeLayout(KxtVar);
 RelativeLayout.LayoutParams NamLysHtrRloRulVaj = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, LyHtrHytVal);
 SupRelLyoVar.setLayoutParams(NamLysHtrRloRulVaj);

 Button DelBtnVav = new Button(KxtVar);
 DelBtnVav.setId(View.generateViewId());
 RelativeLayout.LayoutParams DelBtnRulVaj = new RelativeLayout.LayoutParams(LyHtrHytVal, LyHtrHytVal);
 DelBtnRulVaj.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
 DelBtnVav.setLayoutParams(DelBtnRulVaj);
 SupRelLyoVar.addView(DelBtnVav);

 Button EdtBtnVav = new Button(KxtVar);
 RelativeLayout.LayoutParams EdtBtnRulVaj = new RelativeLayout.LayoutParams(LyHtrHytVal, LyHtrHytVal);
 EdtBtnRulVaj.addRule(RelativeLayout.LEFT_OF, DelBtnVav.getId());
 EdtBtnVav.setLayoutParams(EdtBtnRulVaj);
 SupRelLyoVar.addView(EdtBtnVav);

 LinearLayout LnrLyoVar = new LinearLayout(KxtVar);
 LnrLyoVar.setBackgroundColor(SsnHtrBgdClr);
 RelativeLayout.LayoutParams LnrLyoRulVaj = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, LyHtrHytVal);
 LnrLyoRulVaj.addRule(RelativeLayout.CENTER_IN_PARENT);

 TextView TxtVyuVav = new TextView(KxtVar);
 LinearLayout.LayoutParams LysHtrTxtVyuRulVaj = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
 TxtVyuVav.setLayoutParams(LysHtrTxtVyuRulVaj);
 LnrLyoVar.addView(TxtVyuVav);

 SupRelLyoVar.addView(LnrLyoVar, LnrLyoRulVaj);

Body:
I got solution and like to post

This is for all whom I wish not to struggle like me.

|*| Set OnTouchListener :

LnrLyoVar.setOnTouchListener(WkaMovLitRitVyuKlkVaf);

|*| Use below outside function :

View.OnTouchListener WkaMovLitRitVyuKlkVaf = new View.OnTouchListener()
{
    float WkaStrVyuXcoVar, WkaStrTchXcoVar, WkaStpTchXcoVar;
    final int MovDstVar = LloHytVal * 2;
    RelativeLayout.LayoutParams EdtBtnRulVaj, DelBtnRulVaj;

    @Override
    public boolean onTouch(View VyuPsgVar, MotionEvent MsnEvtPsgVar)
    {
        switch (MsnEvtPsgVar.getActionMasked())
        {
            case MotionEvent.ACTION_DOWN:
                WkaStrTchXcoVar = MsnEvtPsgVar.getRawX();
                WkaStrVyuXcoVar = (int) VyuPsgVar.getX();
                break;

            case MotionEvent.ACTION_MOVE:
                WkaStpTchXcoVar = MsnEvtPsgVar.getRawX();
                float XcoDstVar = Math.abs(WkaStpTchXcoVar - WkaStrTchXcoVar);

                if (XcoDstVar < MovDstVar)
                {
                    EdtBtnRulVaj = (RelativeLayout.LayoutParams) NamEdtBtnVav.getLayoutParams();
                    DelBtnRulVaj = (RelativeLayout.LayoutParams) NamDelBtnVav.getLayoutParams();
                    int SetBtnWytVar;
                    if (WkaStrVyuXcoVar == 0)
                    {
                        VyuPsgVar.animate()
                                .translationX(-XcoDstVar)
                                .setDuration(0)
                                .start();
                        SetBtnWytVar = (int) XcoDstVar / 2;
                    }
                    else
                    {
                        VyuPsgVar.animate()
                                .x(-MovDstVar + XcoDstVar)
                                .setDuration(0)
                                .start();
                        SetBtnWytVar = (int) (LloHytVal - XcoDstVar / 2);
                    }
                    DelBtnRulVaj.width = SetBtnWytVar;
                    EdtBtnRulVaj.width = SetBtnWytVar;
                    NamEdtBtnVav.setLayoutParams(EdtBtnRulVaj);
                    NamDelBtnVav.setLayoutParams(DelBtnRulVaj);
                }
                break;

            case MotionEvent.ACTION_UP :
            case MotionEvent.ACTION_CANCEL:
                EdtBtnRulVaj = (RelativeLayout.LayoutParams) NamEdtBtnVav.getLayoutParams();
                DelBtnRulVaj = (RelativeLayout.LayoutParams) NamDelBtnVav.getLayoutParams();
                int SetBtnWytVar = 0;
                if (WkaStrVyuXcoVar == 0 && WkaStpTchXcoVar < WkaStrTchXcoVar)
                {
                    VyuPsgVar.animate()
                            .x(-MovDstVar);
                    SetBtnWytVar = LloHytVal;
                }
                else if (WkaStrVyuXcoVar == -MovDstVar)
                {
                    VyuPsgVar.animate()
                            .x(0);
                    SetBtnWytVar = 0;
                }
                DelBtnRulVaj.width = SetBtnWytVar;
                EdtBtnRulVaj.width = SetBtnWytVar;
                NamEdtBtnVav.setLayoutParams(EdtBtnRulVaj);
                NamDelBtnVav.setLayoutParams(DelBtnRulVaj);
                break;
        }
        return true;
    }
};


问:
Android intent to check/view emails
I am looking for a way to fire the email-app on device from my app to check emails. Note: I do not want to 'send' any email, just want to 'check' emails. The following code crashes for the gmail app -

```<code>          Intent intent = new Intent(Intent.ACTION_VIEW);
          intent.setType("message/rfc822");
          startActivity(intent);
</code>```

The stack-trace being -

```<code>06-06 23:26:20.313 27703-27731/? E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
                                                   Process: com.google.android.gm, PID: 27703
                                                   java.lang.RuntimeException: An error occurred while executing doInBackground()
                                                       at android.os.AsyncTask$3.done(AsyncTask.java:309)
                                                       at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
                                                       at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
                                                       at java.util.concurrent.FutureTask.run(FutureTask.java:242)
                                                       at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
                                                       at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
                                                       at java.lang.Thread.run(Thread.java:818)
                                                    Caused by: java.lang.NullPointerException: uri
                                                       at com.android.internal.util.Preconditions.checkNotNull(Preconditions.java:60)
                                                       at android.content.ContentResolver.openInputStream(ContentResolver.java:645)
                                                       at clk.a(SourceFile:8)
                                                       at clk.loadInBackground(SourceFile:74)
                                                       at android.content.AsyncTaskLoader.onLoadInBackground(AsyncTaskLoader.java:312)
                                                       at android.content.AsyncTaskLoader$LoadTask.doInBackground(AsyncTaskLoader.java:69)
                                                       at android.content.AsyncTaskLoader$LoadTask.doInBackground(AsyncTaskLoader.java:66)
                                                       at android.os.AsyncTask$2.call(AsyncTask.java:295)
                                                       at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                                                       at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
                                                       at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
                                                       at java.lang.Thread.run(Thread.java:818)
</code>```

Is there no way to fire email app just to check emails?

答:
As Commonsware referenced</p>

```<code>Intent intent= Intent.makeMainSelectorActivity(Intent.ACTION_MAIN, Intent.CATEGORY_APP_EMAIL);
startActivity(intent);
</code>```

Title: Android intent to check/view emails

Body:
I am looking for a way to fire the email-app on device from my app to check emails. Note: I do not want to 'send' any email, just want to 'check' emails. The following code crashes for the gmail app -

          Intent intent = new Intent(Intent.ACTION_VIEW);
          intent.setType("message/rfc822");
          startActivity(intent);

The stack-trace being -

06-06 23:26:20.313 27703-27731/? E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
                                                   Process: com.google.android.gm, PID: 27703
                                                   java.lang.RuntimeException: An error occurred while executing doInBackground()
                                                       at android.os.AsyncTask$3.done(AsyncTask.java:309)
                                                       at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
                                                       at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
                                                       at java.util.concurrent.FutureTask.run(FutureTask.java:242)
                                                       at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
                                                       at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
                                                       at java.lang.Thread.run(Thread.java:818)
                                                    Caused by: java.lang.NullPointerException: uri
                                                       at com.android.internal.util.Preconditions.checkNotNull(Preconditions.java:60)
                                                       at android.content.ContentResolver.openInputStream(ContentResolver.java:645)
                                                       at clk.a(SourceFile:8)
                                                       at clk.loadInBackground(SourceFile:74)
                                                       at android.content.AsyncTaskLoader.onLoadInBackground(AsyncTaskLoader.java:312)
                                                       at android.content.AsyncTaskLoader$LoadTask.doInBackground(AsyncTaskLoader.java:69)
                                                       at android.content.AsyncTaskLoader$LoadTask.doInBackground(AsyncTaskLoader.java:66)
                                                       at android.os.AsyncTask$2.call(AsyncTask.java:295)
                                                       at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                                                       at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
                                                       at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
                                                       at java.lang.Thread.run(Thread.java:818)

Is there no way to fire email app just to check emails?

Body:
As Commonsware referenced

Intent intent= Intent.makeMainSelectorActivity(Intent.ACTION_MAIN, Intent.CATEGORY_APP_EMAIL);
startActivity(intent);


问:
Conda: Downloading a package and updating it
Using Python 2.7, I am trying to download a package from Anaconda.org, increase its version number by 0.1 (i.e ver 0.0 to ver 0.1), and then re-upload it to the same Anaconda channel. My code is saved in a .py file that is used in Window's cmd or iPython

So far in my .py file I have:

```<code>import sys, subprocess, conda

# Search for the package
search = subprocess.check_output(['conda', 'search', 'gladio'])

# Take version number from package
v = [int(s) for s in search.split() if s.isdigit()]

# Update with new version number
v = v[0] + 1
print 'New version number is 0.%s' % v

# Set new commands as strings
pack = '''!conda package -p C:\Users\Ian\Anaconda\gladio --pkg-name gladio -
       -pkg-ver 0.%s''' % v
load = '!anaconda upload gladio0.%s-0.tar.bz2' % v

# Execute strings
exec pack
exec load
</code>```

However I get this as a response in the terminal:

```<code>New version number is 0.1
  File "<string>", line 1
    !conda package -p C:\Users\Ian\Anaconda\gladio --pkg-name gladi...
    ^
SyntaxError: invalid syntax
</code>```

However if I copy and paste as raw text into iPython it works.

When deleting the exclamation mark I get:

```<code>conda package -p C:\Users\Ian\Anaconda\gladio --pkg-name gladi...
            ^
SyntaxError: invalid syntax
</code>```

I have also tried changing to

```<code>eval pack
eval load
</code>```

or

```<code>eval $pack
eval $load
</code>```

with no luck. I also tried defining a 'pack' and a 'load' but I get the same syntax error. I know I'm supposed to avoid the exec and eval functions but I'm not sure what to do here. I have the exact same issue when using Window's cmd, Spyder, or iPython.

答: This is because the exclamation ! code here syntax is valid in IPython (and Jupyter Notebooks) as a means to run shell commands. However, it is not valid syntax for the general (regular) Python interpreter that runs when you type python script_name.py in the CMD. Although not well documented, there is a conda.cli.python_api and conda.exports. You can find the code for the former here: https://github.com/conda/conda/blob/master/conda/cli/python_api.py

Body:
Using Python 2.7, I am trying to download a package from Anaconda.org, increase its version number by 0.1 (i.e ver 0.0 to ver 0.1), and then re-upload it to the same Anaconda channel. My code is saved in a .py file that is used in Window's cmd or iPython

So far in my .py file I have:

import sys, subprocess, conda

# Search for the package
search = subprocess.check_output(['conda', 'search', 'gladio'])

# Take version number from package
v = [int(s) for s in search.split() if s.isdigit()]

# Update with new version number
v = v[0] + 1
print 'New version number is 0.%s' % v

# Set new commands as strings
pack = '''!conda package -p C:\Users\Ian\Anaconda\gladio --pkg-name gladio -
       -pkg-ver 0.%s''' % v
load = '!anaconda upload gladio0.%s-0.tar.bz2' % v

# Execute strings
exec pack
exec load

However I get this as a response in the terminal:

New version number is 0.1
  File "<string>", line 1
    !conda package -p C:\Users\Ian\Anaconda\gladio --pkg-name gladi...
    ^
SyntaxError: invalid syntax

However if I copy and paste as raw text into iPython it works.

When deleting the exclamation mark I get:

conda package -p C:\Users\Ian\Anaconda\gladio --pkg-name gladi...
            ^
SyntaxError: invalid syntax

I have also tried changing to

eval pack
eval load

or

eval $pack
eval $load

with no luck. I also tried defining a 'pack' and a 'load' but I get the same syntax error. I know I'm supposed to avoid the exec and eval functions but I'm not sure what to do here. I have the exact same issue when using Window's cmd, Spyder, or iPython.


问:
Difference between {$_GET['id']} and '".$_GET['id']."'?
Is the any difference between writing

```
{$_GET['id']}
```

and

'".$_GET['id']."'

in a sql statement? both works the same

答:
Its always a bad idea to put data from a get request directly into SQL, and there are many easy ways to prevent SQL injection.

For the simple case where you know you want a numeric ID, then you can simply force the value to be numeric and then there is no chance of SQL injection. One way might be okoman's usage of sprintf(), maybe something like this:

```<code>$sql = "INSERT INTO table VALUES(".sprintf("%d",$_GET['id']) .")";
</code>```

though I think its ugly and bad form. Something like this is nicer:

```<code>$sql = "INSERT INTO table VALUES(".(int)$_GET['id']) .")";
</code>```

Which simply casts the value to an int - if its not a number that can be cast to int - you'll get a "0" which may or may not be what you want.

Other alternatives (and for when your data is not supposed to be a number) include using escaping functions such as add_slashes() or the above mentioned mysql_real_escape_string().

IMHO, the best way to use database access from within PHP and very easily protect from SQL injection is to use the new PHP PDO library ( http://php.net/PDO ). This allows you to write SQL strings that contain no data whatsoever, and have the data added later inside the database server itself. In this form there is absolutely no way to do SQL injection.

Here is some example code:

```<code>$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
$stmt = $dbh->prepare("INSERT INTO table VALUES (?)");
$stmt->bindParam(1, $_GET['id']);
$stml->execute();
</code>```

As you can see, the data is not added to the SQL query itself and so no need for escaping.

OwnerDisplayName: Bartek

LastEditorDisplayName: Ross

Body:
Is the any difference between writing

{$_GET['id']}

and

'".$_GET['id']."'

in a sql statement? both works the same

Body:
Its always a bad idea to put data from a get request directly into SQL, and there are many easy ways to prevent SQL injection.

For the simple case where you know you want a numeric ID, then you can simply force the value to be numeric and then there is no chance of SQL injection. One way might be okoman's usage of sprintf(), maybe something like this:

$sql = "INSERT INTO table VALUES(".sprintf("%d",$_GET['id']) .")";

though I think its ugly and bad form. Something like this is nicer:

$sql = "INSERT INTO table VALUES(".(int)$_GET['id']) .")";

Which simply casts the value to an int - if its not a number that can be cast to int - you'll get a "0" which may or may not be what you want.

Other alternatives (and for when your data is not supposed to be a number) include using escaping functions such as add_slashes() or the above mentioned mysql_real_escape_string().

IMHO, the best way to use database access from within PHP and very easily protect from SQL injection is to use the new PHP PDO library ( http://php.net/PDO ). This allows you to write SQL strings that contain no data whatsoever, and have the data added later inside the database server itself. In this form there is absolutely no way to do SQL injection.

Here is some example code:

$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
$stmt = $dbh->prepare("INSERT INTO table VALUES (?)");
$stmt->bindParam(1, $_GET['id']);
$stml->execute();

As you can see, the data is not added to the SQL query itself and so no need for escaping.

OwnerDisplayName: Guss


问:
deleting datas in the table in GUI
I have question that how can I delete all datas from my jTable in GUI when a user entered a key?
thanks</p>

答:
You need to understand that a JTable is a view of the data, while the actual data resides in the TableModel.  If you need to clear out the table, then you need to clear out the TableModel.

If your TableModel is an AbstractTableModel, you must provide implementations of 3 methods:

```<code>public int getRowCount();
public int getColumnCount();
public Object getValueAt(int row, int column);
</code>```

Frequently the actual data objects are stored in an additional data structure (e.g. a list), and then the AbstractTableModel queries that list.

```<code>List<DomainObject> objects = new ArrayList<DomainObject>();

public int getRowCount() { return objects.size(); }
// How many columns you make depends on what features of the objects you're exposing.
public int getColumnCount() { return NUMBER_OF_COLUMNS; }
public Object getValueAt(int row, int column) {
     DomainObject object = objects.get(row);
     ... // pull out the property based on the column they pass in
}

// By exposing this method, you can allow your Controller code to reach into this model
// and delete all the rows.
public void clear() {
    objects.clear()
}
</code>```

What HH is suggesting you do is change the model of your JTable to reference an empty model, which will in effect clear out the table.  However, the columns etc. will not be persisted correctly (the new DefaultTableModel has no idea what those column names would be).

After you've researched how the view and model fit together more, take a look at GlazedLists.  It allows a very powerful way to create TableModels which provide dynamic views of your data, e.g. by filtering out rows that do not match certain criteria.

To sum up - you're not going to find a method on the JTable to clear out its contents, because that's the job of the TableModel.  You need some way of ensuring that the TableModel's backing data structures are cleared out.

Title: deleting datas in the table in GUI

Body:
You need to understand that a JTable is a view of the data, while the actual data resides in the TableModel.  If you need to clear out the table, then you need to clear out the TableModel.

If your TableModel is an AbstractTableModel, you must provide implementations of 3 methods:

public int getRowCount();
public int getColumnCount();
public Object getValueAt(int row, int column);

Frequently the actual data objects are stored in an additional data structure (e.g. a list), and then the AbstractTableModel queries that list.

List<DomainObject> objects = new ArrayList<DomainObject>();

public int getRowCount() { return objects.size(); }
// How many columns you make depends on what features of the objects you're exposing.
public int getColumnCount() { return NUMBER_OF_COLUMNS; }
public Object getValueAt(int row, int column) {
     DomainObject object = objects.get(row);
     ... // pull out the property based on the column they pass in
}

// By exposing this method, you can allow your Controller code to reach into this model
// and delete all the rows.
public void clear() {
    objects.clear()
}

What HH is suggesting you do is change the model of your JTable to reference an empty model, which will in effect clear out the table.  However, the columns etc. will not be persisted correctly (the new DefaultTableModel has no idea what those column names would be).

After you've researched how the view and model fit together more, take a look at GlazedLists.  It allows a very powerful way to create TableModels which provide dynamic views of your data, e.g. by filtering out rows that do not match certain criteria.

To sum up - you're not going to find a method on the JTable to clear out its contents, because that's the job of the TableModel.  You need some way of ensuring that the TableModel's backing data structures are cleared out.


问:
Windows Service Template for Visual Studio 2017
The Windows Service Template no longer displays by-default for new projects in Visual Studio 2017....and the installer has no 'search' capability.

All this AZURE stuff is great, but I still gotta do normal 'on-prem' work too...and I hate maintaining 2 versions of Visual Studio.

Any thoughts here?

答: VS2017 --> New project --> Visual Basic or Visual C# --> Windows Classic Desktop --> Windows Service


问:
Angular2 avoid adding duplicate JSON objects to array
I'm trying to avoid adding duplicate objects to an Angular2 array. For example let's say we have an array "Cars" and we put in a JSON object in that array that might be something like:

```<code>{
 "brand": "Acura"
 "engine": "2.4L"
 + others details
}
</code>```

We can keep adding cars with to the array. My issue is now how to avoid adding the same car into the array again. If I were to add the same JSON as described above, it shouldn't be added. Would I have to iterate through all the existing objects in the array and compare each field of the JSON? This sounds like an expensive operation to me, or is there some more elegant/faster method?

Thanks!

答:
You need to find or create a unique property on the items in the list, then you could use something like lodash to query the array by a property to see if that item already exists in the list before you add it.

Example from Lodash site

```<code>var users = [
  { 'user': 'barney',  'active': false },
  { 'user': 'fred',    'active': false },
  { 'user': 'pebbles', 'active': true }
];

// The `_.matches` iteratee shorthand.
_.findIndex(users, { 'user': 'fred', 'active': false });
</code>```

Body:
I'm trying to avoid adding duplicate objects to an Angular2 array. For example let's say we have an array "Cars" and we put in a JSON object in that array that might be something like:

{
 "brand": "Acura"
 "engine": "2.4L"
 + others details
}

We can keep adding cars with to the array. My issue is now how to avoid adding the same car into the array again. If I were to add the same JSON as described above, it shouldn't be added. Would I have to iterate through all the existing objects in the array and compare each field of the JSON? This sounds like an expensive operation to me, or is there some more elegant/faster method?

Thanks!

Body:
You need to find or create a unique property on the items in the list, then you could use something like lodash to query the array by a property to see if that item already exists in the list before you add it.

Example from Lodash site

var users = [
  { 'user': 'barney',  'active': false },
  { 'user': 'fred',    'active': false },
  { 'user': 'pebbles', 'active': true }
];

// The `_.matches` iteratee shorthand.
_.findIndex(users, { 'user': 'fred', 'active': false });


问:
Removing padding on columns makes horizontal scrollbar
I wanted to remove the padding from the bootstrap grid column classes.

So I did

```<code>.col-x {
    padding: 0;
}
</code>```

But this is kind of breaking the whole layout because a horizontal scrollbar appears.

I've created a pen for this so you can see it.

What is causing the horizontal scrollbar and how to fix it?

答:
The .row has minus margins on them. Also the .content-fluid has padding applied to them. So you just need to add this to your CSS:

```<code>.row {
  margin:0;
}
.container-fluid {
  padding:0;
}
</code>```

Body:
I wanted to remove the padding from the bootstrap grid column classes.

So I did

.col-x {
    padding: 0;
}

But this is kind of breaking the whole layout because a horizontal scrollbar appears.

I've created a pen for this so you can see it.

What is causing the horizontal scrollbar and how to fix it?

Body:
The .row has minus margins on them. Also the .content-fluid has padding applied to them. So you just need to add this to your CSS:

.row {
  margin:0;
}
.container-fluid {
  padding:0;
}


问:
Neo4j duplicate input id exception
I am new to neo4j and I am trying to construct bitcoin transaction graph using it. I am following this link behas/bitcoingraph to do so, I came across the neo4j import command to create a database

```<code>$NEO4J_HOME/bin/neo4j-import --into $NEO4J_HOME/data/graph.db \
  --nodes:Block blocks_header.csv,blocks.csv \
  --nodes:Transaction transactions_header.csv,transactions.csv \
  --nodes:Output outputs_header.csv,outputs.csv \  .......
</code>```

After executing the above command I encountered an error

```<code>Exception in thread "Thread-1" org.neo4j.unsafe.impl.batchimport.cache.idmapping.string.DuplicateInputIdException: Id '00000000f079868ed92cd4e7b7f50a5f8a2bb459ab957dd5402af7be7bd8ea6b' is defined more than once in Block, at least at /home/nikhil/Desktop/Thesis/bitcoingraph/blocks_0_1000/blocks.csv:409 and /home/nikhil/Desktop/Thesis/bitcoingraph/blocks_0_1000/blocks.csv:1410
</code>```

Here is the block_header. csv

```<code>hash:ID(Block),height:int,timestamp:int
</code>```

Does anyone know how to fix it? I read there is a solution available in id-spaces but I am not quiet sure how to use it. Thanks in advance for any help

答:
The --skip-duplicate-nodes flag will skip import of nodes with the same ID instead of aborting the import.

For example:

```<code>$NEO4J_HOME/bin/neo4j-import --into $NEO4J_HOME/data/graph.db \
  --nodes:Block blocks_header.csv,blocks.csv --skip-duplicate-nodes \
  --nodes:Transaction transactions_header.csv,transactions.csv \
  --nodes:Output outputs_header.csv,outputs.csv \  .......
</code>```

Title: Neo4j duplicate input id exception

Body:
I am new to neo4j and I am trying to construct bitcoin transaction graph using it. I am following this link behas/bitcoingraph to do so, I came across the neo4j import command to create a database

$NEO4J_HOME/bin/neo4j-import --into $NEO4J_HOME/data/graph.db \
  --nodes:Block blocks_header.csv,blocks.csv \
  --nodes:Transaction transactions_header.csv,transactions.csv \
  --nodes:Output outputs_header.csv,outputs.csv \  .......

After executing the above command I encountered an error

Exception in thread "Thread-1" org.neo4j.unsafe.impl.batchimport.cache.idmapping.string.DuplicateInputIdException: Id '00000000f079868ed92cd4e7b7f50a5f8a2bb459ab957dd5402af7be7bd8ea6b' is defined more than once in Block, at least at /home/nikhil/Desktop/Thesis/bitcoingraph/blocks_0_1000/blocks.csv:409 and /home/nikhil/Desktop/Thesis/bitcoingraph/blocks_0_1000/blocks.csv:1410

Here is the block_header. csv

hash:ID(Block),height:int,timestamp:int

Does anyone know how to fix it? I read there is a solution available in id-spaces but I am not quiet sure how to use it. Thanks in advance for any help

Body:
The --skip-duplicate-nodes flag will skip import of nodes with the same ID instead of aborting the import.

For example:

$NEO4J_HOME/bin/neo4j-import --into $NEO4J_HOME/data/graph.db \
  --nodes:Block blocks_header.csv,blocks.csv --skip-duplicate-nodes \
  --nodes:Transaction transactions_header.csv,transactions.csv \
  --nodes:Output outputs_header.csv,outputs.csv \  .......


问:
centering an SVG inside a div
I want to display an SVG image inside a position:fixed div. I have

```<code><div class="main">
  <svg class="svg" viewBox="0 0 180 100">
    <rect height="100%" width="100%" fill="#003300"></rect>
  </svg>
</div>
</code>```

and style

```<code>.main {
  position:fixed;
  left: 100px;
  height: 100%;
  width:100%;
  background: #33AAAA;
}

.svg {
  display: block;
  height: 100%;
  width: 100%;
  position:static;
}
</code>```

I want to center the SVG horizontally and vertically. I get a strange behavior. Changing the size of the browser window, shows that when the svg is smaller than available width, it is weirdly placed. For example:  there is more space on the left than on the right.

Codepen (including CSS reset): Codepen

答:
You are setting the width to 100%, then shifting it over by 100px. The width is still calculated as whatever the 100% width is. To center it the way you want, you will need to subtract 100px from the width or nest things differently.</p>

```<code>.main {
  position:fixed;
  left:100px;
  height: 100%;
  width:calc(100% - 100px);
  background: #33AAAA;
}
</code>```

Title: centering an SVG inside a div

Body:
I want to display an SVG image inside a position:fixed div. I have

  <svg class="svg" viewBox="0 0 180 100">
    <rect height="100%" width="100%" fill="#003300"></rect>
  </svg>

and style

.main {
  position:fixed;
  left: 100px;
  height: 100%;
  width:100%;
  background: #33AAAA;
}

.svg {
  display: block;
  height: 100%;
  width: 100%;
  position:static;
}

I want to center the SVG horizontally and vertically. I get a strange behavior. Changing the size of the browser window, shows that when the svg is smaller than available width, it is weirdly placed. For example:  there is more space on the left than on the right.

Codepen (including CSS reset): Codepen

Body:
You are setting the width to 100%, then shifting it over by 100px. The width is still calculated as whatever the 100% width is. To center it the way you want, you will need to subtract 100px from the width or nest things differently.

.main {
  position:fixed;
  left:100px;
  height: 100%;
  width:calc(100% - 100px);
  background: #33AAAA;
}


问:
FileNotFoundException while trying to import URI that contains emoji
I wrote some code in my android app to import files.

It is working well when i import a file like foo.bar but it's not when i try to import a file that contains an emoji like foo.bar

Each time I get a FileNotFoundException when i try to use openFileDescriptor method from contentResolver...

```<code>ParcelFileDescriptor pfd = mActivity.getContentResolver().openFileDescriptor(mImportUri, "r");
</code>```

Here is the value for mImportUri:

```<code>content://com.android.externalstorage.documents/document/primary%3ADownload%2Ffoo%20%F0%9F%98%AD.bar
</code>```

I assume openFileDescriptor does not support %20%F0%9F%98%AD in the URI but i don't know how to fix it ??

edit:

a simple use case. Only 1 button and one TextView to get the result.
When i try to get foo.bar it si working -> result = OK but when i select foo.bar result is KO -> so i got an exception.

MainActivity.java

```<code>public final static int IMPORT_NEBO_REQUEST = 0;
public TextView resText;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    resText = (TextView) findViewById(R.id.result_text);
    findViewById(R.id.import_button).setOnClickListener(this);
}

@Override
public void onClick(View view) {
    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.addCategory(Intent.CATEGORY_OPENABLE);
    intent.setType("*/*");

    //This will start the appropriate app able to pick a file
    startActivityForResult(intent, IMPORT_NEBO_REQUEST);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == IMPORT_NEBO_REQUEST && resultCode == RESULT_OK) {
        Uri uri = data.getData();
        try {
            ParcelFileDescriptor pfd = getContentResolver().openFileDescriptor(uri, "r");
            resText.setText("OK");
        } catch (Exception e) {
            e.printStackTrace();
            resText.setText("KO");
        }

    }
}
</code>```

Not working on Samsung GTab 12pce -> Android 5.0.2

Working on Samsung GTab 3 -> Android 7

Not working on Huawei M2 -> Android 5.1.1

Not working on Nvidia sheld -> Android 6

Working on OnePlus 3 -> Android 7.1.1

Is someone could help me?

François

答:
There's no guarantee ContentResolver.openFileDescriptor() works for arbitrary content: URIs. The documentation contains the following warning:

Open a raw file descriptor to access data under a URI. This is like openAssetFileDescriptor(Uri, String), but uses the underlying openFile(Uri, String) method, so will not work with providers that return sub-sections of files. If at all possible, you should use openAssetFileDescriptor(Uri, String). You will receive a FileNotFoundException exception if the provider returns a sub-section of a file.

For most use cases ContentResolver.openInputStream() is the preferable option.

Body:
I wrote some code in my android app to import files.

It is working well when i import a file like foo.bar but it's not when i try to import a file that contains an emoji like foo.bar

Each time I get a FileNotFoundException when i try to use openFileDescriptor method from contentResolver...

ParcelFileDescriptor pfd = mActivity.getContentResolver().openFileDescriptor(mImportUri, "r");

Here is the value for mImportUri:

content://com.android.externalstorage.documents/document/primary%3ADownload%2Ffoo%20%F0%9F%98%AD.bar

I assume openFileDescriptor does not support %20%F0%9F%98%AD in the URI but i don't know how to fix it ??

edit:

a simple use case. Only 1 button and one TextView to get the result.
When i try to get foo.bar it si working -> result = OK but when i select foo.bar result is KO -> so i got an exception.

MainActivity.java

public final static int IMPORT_NEBO_REQUEST = 0;
public TextView resText;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    resText = (TextView) findViewById(R.id.result_text);
    findViewById(R.id.import_button).setOnClickListener(this);
}

@Override
public void onClick(View view) {
    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.addCategory(Intent.CATEGORY_OPENABLE);
    intent.setType("*/*");

    //This will start the appropriate app able to pick a file
    startActivityForResult(intent, IMPORT_NEBO_REQUEST);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == IMPORT_NEBO_REQUEST && resultCode == RESULT_OK) {
        Uri uri = data.getData();
        try {
            ParcelFileDescriptor pfd = getContentResolver().openFileDescriptor(uri, "r");
            resText.setText("OK");
        } catch (Exception e) {
            e.printStackTrace();
            resText.setText("KO");
        }

    }
}

Not working on Samsung GTab 12pce -> Android 5.0.2

Working on Samsung GTab 3 -> Android 7

Not working on Huawei M2 -> Android 5.1.1

Not working on Nvidia sheld -> Android 6

Working on OnePlus 3 -> Android 7.1.1

Is someone could help me?

François


问:
Pause HTML Video on exiting a tab
I have a section with tabs. Two tabs have a video.

Only problem is, which I can't figure out, when I click to play video it plays (that is good) but when I go to the next tab the initial video will still be playing - what I want is the video to pause when I exit each tab.

I've tried playing about with functions but just can't get it working.

Thanks!

$('ul.tabs li').click(function() {
    var tab_id = $(this).data('tab');

    $('ul.tabs li').removeClass('current');
    $('.tab-content').removeClass('current');

    $(this).addClass('current');
    $(this).parent().parent().parent().children("#"+tab_id).addClass('current');
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>section {
 background: #fff;
}

ul.tabs {
 margin: 0;
 padding: 0;
 list-style: none;
  background: #ccc;
}

.tab-link {
 background: none;
 color: #fff;
 display: inline-block;
 padding: 10px;
 cursor: pointer;
 font-size: 16px;
}

.tabs .tab-link.current {
 background: #ccc;
}

.tab-content {
 display: none;
 background: #ccc;
}

.tab-content.current {
 display: block;
}

video {
 width: 100%;
 height: 400px;
}</code>```

        One

        Two

    <video controls>
      <source type="video/mp4"
      src="http://techslides.com/demos/sample-videos/small.mp4">
    </video>

    <video controls>
      <source type="video/mp4"
      src="http://techslides.com/demos/sample-videos/small.mp4">
    </video>

```

答:
In order to stop the video you can use native stop method, and if there are only two videos, you can stop the hidden one like this:

```<code>$("video").not(":visible").get(0).stop();
</code>```

You can tweak this response if you need multiple videos by using id, detecting the tab you are opening and stopping the video in the other tabs.

EDIT: you also can stop all videos using this code after tab change:

```<code>$("video").each(function(i,video){video.stop()});
</code>```

Title: Pause HTML Video on exiting a tab

Body:
I have a section with tabs. Two tabs have a video.

Only problem is, which I can't figure out, when I click to play video it plays (that is good) but when I go to the next tab the initial video will still be playing - what I want is the video to pause when I exit each tab.

I've tried playing about with functions but just can't get it working.

Thanks!

$('ul.tabs li').click(function() {
    var tab_id = $(this).data('tab');

    $('ul.tabs li').removeClass('current');
    $('.tab-content').removeClass('current');

    $(this).addClass('current');
    $(this).parent().parent().parent().children("#"+tab_id).addClass('current');
});

section {
 background: #fff;
}

ul.tabs {
 margin: 0;
 padding: 0;
 list-style: none;
  background: #ccc;
}

.tab-link {
 background: none;
 color: #fff;
 display: inline-block;
 padding: 10px;
 cursor: pointer;
 font-size: 16px;
}

.tabs .tab-link.current {
 background: #ccc;
}

.tab-content {
 display: none;
 background: #ccc;
}

.tab-content.current {
 display: block;
}

video {
 width: 100%;
 height: 400px;
}

        One

        Two

    <video controls>
      <source type="video/mp4"
      src="http://techslides.com/demos/sample-videos/small.mp4">
    </video>

    <video controls>
      <source type="video/mp4"
      src="http://techslides.com/demos/sample-videos/small.mp4">
    </video>

Body:
In order to stop the video you can use native stop method, and if there are only two videos, you can stop the hidden one like this:

$("video").not(":visible").get(0).stop();

You can tweak this response if you need multiple videos by using id, detecting the tab you are opening and stopping the video in the other tabs.

EDIT: you also can stop all videos using this code after tab change:

$("video").each(function(i,video){video.stop()});


问:
in VC++ VS6 a simple printf gives fatal error C1001: INTERNAL COMPILER ERROR
I am using visual studio 6 , vc++ on windows 7 and written a simple helloworld program which is by default created by VS6.
but due to printf it is giving following error:

```<code>    // testapp.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

int main(int argc, char* argv[])
{
    printf("Hello World!\n");
    return 0;
}
</code>```

Error :

```<code>--------------------Configuration: testapp - Win32 Debug--------------------
Compiling...
StdAfx.cpp
Compiling...
testapp.cpp
D:\PROJECTS\FATT\testapp\testapp.cpp(8) : fatal error C1001: INTERNAL COMPILER ERROR
  (compiler file 'E:\8783\vc98\p2\src\P2\main.c', line 494)
    Please choose the Technical Support command on the Visual C++
    Help menu, or open the Technical Support help file for more information
Error executing cl.exe.

testapp.exe - 1 error(s), 0 warning(s)
</code>```

why printf and sprintf not working?

答:
My first thought was that VS6 SP6 might be required. (Previous answer).
Large projects will fail (with lots of files) there is a CL.exe crash that is also fixed in SP3.
You need to not install all of the VS6 in the install for Win7 and newer. There is a package that needs to be skipped, ADO/RDS and OLE Providers.
If you attempt to install these components the VS6.0 install will hang out of the box, and later the VS6 SP6 will not install properly.

I did a lot of work in the Amazon Cloud in 2015 to see if VS6.0 will install in Win2012, and it does.  I assume Win7/8/10 will be similar.

There is also a /GF (String Pooling) bug we found last year (2016) in VS6.0 which can really mess things up if you have runtime searches of strings.  Two different string names can be pooled into a single string so searching through a list of strings will never find one of the two at runtime.  /GF is implied by /ZI (IIRC) so change to /Zi. (I may have that switched).
Recommendation is to move from VS6.0 -> ON ASAP.  I know that might not be possible :(.

Body:
I am using visual studio 6 , vc++ on windows 7 and written a simple helloworld program which is by default created by VS6.
but due to printf it is giving following error:

    // testapp.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

int main(int argc, char* argv[])
{
    printf("Hello World!\n");
    return 0;
}

Error :

--------------------Configuration: testapp - Win32 Debug--------------------
Compiling...
StdAfx.cpp
Compiling...
testapp.cpp
D:\PROJECTS\FATT\testapp\testapp.cpp(8) : fatal error C1001: INTERNAL COMPILER ERROR
  (compiler file 'E:\8783\vc98\p2\src\P2\main.c', line 494)
    Please choose the Technical Support command on the Visual C++
    Help menu, or open the Technical Support help file for more information
Error executing cl.exe.

testapp.exe - 1 error(s), 0 warning(s)

why printf and sprintf not working?


问:
Setting up multiple dependent elements (JavaScript)
I have a form with dependent dropdowns (cat) which depend on the value selected from an independent dropdown (item). I want to avoid copy paste code so I am looking to have a function that can handle multiple dropdowns based on their independent partner. I dont want to explicitly call the dependent element or I will have to result in copy paste ugly code.

So is there away to bind to elements together, or tie to elements together?

Example:

item1 --> cat1

item2 --> cat2

item3 --> cat3

```<code>    var roleByCategory = {
        A: ["Soup", "Juice", "Tea", "Others"],
        B: ["Soup", "Juice", "Water", "Others"],
        C: ["Soup", "Juice", "Coffee", "Tea", "Others"]
    }

    $("form").on("change", ".indi_ele", changeCat);
    $(".indi_ele select").change();

    function changeCat(event) { //should handle everything
        var indie = $(event.target);
        var depends = indie.closest('select').find('.gfield_select'); //dependent dropdown
        var type = indie.val(); // this equals A, B, or C

        var catOptions = "";
        for (categoryId = 0; categoryId < roleByCategory[type].length; categoryId++) {
            catOptions += "<option>" + roleByCategory[type][categoryId] + "</option>";
        }
            depends.html(catOptions);
    }
</code>```

答: Give certain value to the elements of first dropdown and Populate the elements of second dropdown beforehand as well (you may hide it from the user if you want). On change of first dropdown filter the second dropdown using the filter() method.

Body:
I have a form with dependent dropdowns (cat) which depend on the value selected from an independent dropdown (item). I want to avoid copy paste code so I am looking to have a function that can handle multiple dropdowns based on their independent partner. I dont want to explicitly call the dependent element or I will have to result in copy paste ugly code.

So is there away to bind to elements together, or tie to elements together?

Example:

item1 --> cat1

item2 --> cat2

item3 --> cat3

    var roleByCategory = {
        A: ["Soup", "Juice", "Tea", "Others"],
        B: ["Soup", "Juice", "Water", "Others"],
        C: ["Soup", "Juice", "Coffee", "Tea", "Others"]
    }

    $("form").on("change", ".indi_ele", changeCat);
    $(".indi_ele select").change();

    function changeCat(event) { //should handle everything
        var indie = $(event.target);
        var depends = indie.closest('select').find('.gfield_select'); //dependent dropdown
        var type = indie.val(); // this equals A, B, or C

        var catOptions = "";
        for (categoryId = 0; categoryId < roleByCategory[type].length; categoryId++) {
            catOptions += "<option>" + roleByCategory[type][categoryId] + "</option>";
        }
            depends.html(catOptions);
    }


问:
Combining two tables into one in Google BigQuery
In bigQuery, I have two tables - one with 30K records, and another with 20M records.

I need an efficient way to search them with a join, so I was thinking of creating a combined table with this SQL:

```<code>SELECT
s.site site,
s.rank rank,
s.visitors visitors,
s.store_id store_id,
s.currency currency,
p.title title,
p.product_type product_type,
p.handle handle,
p.price price,
p.created_at created_at,
p.image_url image_url,
p.description description
FROM eComData.stores s INNER JOIN eComData.products p ON s.store_id = p.store_id
WHERE
s.active = 1
</code>```

However, running this bq command:

```<code>bq query --destination_table=eComData.stores_n_products --allow_large_results "SELECT s.site site,s.rank rank,s.visitors visitors,s.store_id store_id,s.currency currency,p.title title,p.product_type product_type,p.handle handle,p.price price,p.created_at created_at,p.image_url image_url,p.description description FROM eComData.stores s INNER JOIN eComData.products p ON s.store_id = p.store_id WHERE s.active = 1"
</code>```

is taking forever - 5,000 seconds plug so far. Is there an efficient way to create a combined table for easier searching?

答:
Try below

SELECT
  s.site site,
  s.rank rank,
  s.visitors visitors,
  s.store_id store_id,
  s.currency currency,
  p.title title,
  p.product_type product_type,
  p.handle handle,
  p.price price,
  p.created_at created_at,
  p.image_url image_url,
  p.description description
FROM (
  SELECT
    site,
    rank,
    visitors,
    store_id,
    currency
  FROM eComData.stores
  WHERE active = 1
) s
INNER JOIN eComData.products p
ON s.store_id = p.store_id
```

Body:
In bigQuery, I have two tables - one with 30K records, and another with 20M records.

I need an efficient way to search them with a join, so I was thinking of creating a combined table with this SQL:

SELECT
s.site site,
s.rank rank,
s.visitors visitors,
s.store_id store_id,
s.currency currency,
p.title title,
p.product_type product_type,
p.handle handle,
p.price price,
p.created_at created_at,
p.image_url image_url,
p.description description
FROM eComData.stores s INNER JOIN eComData.products p ON s.store_id = p.store_id
WHERE
s.active = 1

However, running this bq command:

bq query --destination_table=eComData.stores_n_products --allow_large_results "SELECT s.site site,s.rank rank,s.visitors visitors,s.store_id store_id,s.currency currency,p.title title,p.product_type product_type,p.handle handle,p.price price,p.created_at created_at,p.image_url image_url,p.description description FROM eComData.stores s INNER JOIN eComData.products p ON s.store_id = p.store_id WHERE s.active = 1"

is taking forever - 5,000 seconds plug so far. Is there an efficient way to create a combined table for easier searching?


问:
Task Scheduler 2.0 populating current scheduled tasks to WPF GridView
I need to populate the currently scheduled tasks in task scheduler 2.0 to a GridView in WPF. My application currently adds and deletes tasks scheduled by the user but I need a way for them to view the current scheduled tasks without having to go to the task scheduler.

UPDATE

Thanks pax I ended up using this method and tying the column info using the .xaml

```<code>    private void PopulateGridView()
    {
        //initialize task scheduler 2.0
        var scheduler = new TaskScheduler.TaskScheduler();
        //connect using server, username, password, and domain
        scheduler.Connect(null, null, null, null);

        //set folder to register tasks; "\\" = local directory
        ITaskFolder rootGet = scheduler.GetFolder("\\");

        //for each task in the folder delete the task
        foreach (IRegisteredTask irTasks in rootGet.GetTasks(0))
        {
            dgInstanceView.ItemsSource = rootGet.GetTasks(0);
        }
     }
</code>```

答: I'd suggest using the GetTasks method of the ITaskFolder interface.</p>

Body:
I need to populate the currently scheduled tasks in task scheduler 2.0 to a GridView in WPF. My application currently adds and deletes tasks scheduled by the user but I need a way for them to view the current scheduled tasks without having to go to the task scheduler.

UPDATE

Thanks pax I ended up using this method and tying the column info using the .xaml

    private void PopulateGridView()
    {
        //initialize task scheduler 2.0
        var scheduler = new TaskScheduler.TaskScheduler();
        //connect using server, username, password, and domain
        scheduler.Connect(null, null, null, null);

        //set folder to register tasks; "\\" = local directory
        ITaskFolder rootGet = scheduler.GetFolder("\\");

        //for each task in the folder delete the task
        foreach (IRegisteredTask irTasks in rootGet.GetTasks(0))
        {
            dgInstanceView.ItemsSource = rootGet.GetTasks(0);
        }
     }