问:
Kafka consumer exception and offset commits
I've been trying to do some POC work for Spring Kafka. Specifically, I wanted to experiment with what are the best practices in terms of dealing with errors while consuming messages within Kafka.

I am wondering if anyone is able to help with:

Sharing best practices surrounding what Kafka consumers should do
when there is a failure

Help me understand how AckMode Record works, and how to prevent commits to the Kafka offset queue when an exception is thrown in the listener method.

The code example for 2 is given below:

Given that AckMode is set to RECORD, which according to the documentation:

commit the offset when the listener returns after processing the
  record.

I would have thought the the offset would not be incremented if the listener method threw an exception. However, this was not the case when I tested it using the code/config/command combination below. The offset still gets updated, and the next message continues to be processed.

My config:

```<code>    private Map<String, Object> producerConfigs() {
    Map<String, Object> props = new HashMap<>();
    props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "192.168.0.1:9092");
    props.put(ProducerConfig.RETRIES_CONFIG, 0);
    props.put(ProducerConfig.BATCH_SIZE_CONFIG, 16384);
    props.put(ProducerConfig.LINGER_MS_CONFIG, 1);
    props.put(ProducerConfig.BUFFER_MEMORY_CONFIG, 33554432);
    props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, IntegerSerializer.class);
    props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
    return props;
}

   @Bean
ConcurrentKafkaListenerContainerFactory<Integer, String> kafkaListenerContainerFactory() {
    ConcurrentKafkaListenerContainerFactory<Integer, String> factory =
            new ConcurrentKafkaListenerContainerFactory<>();
    factory.setConsumerFactory(new DefaultKafkaConsumerFactory<>(consumerConfigs()));
    factory.getContainerProperties().setAckMode(AbstractMessageListenerContainer.AckMode.RECORD);
    return factory;
}
</code>```

My code:

```<code>@Component
public class KafkaMessageListener{
    @KafkaListener(topicPartitions = {@TopicPartition( topic = "my-replicated-topic", partitionOffsets = @PartitionOffset(partition = "0", initialOffset = "0", relativeToCurrent = "true"))})
    public void onReplicatedTopicMessage(ConsumerRecord<Integer, String> data) throws InterruptedException {
            throw new RuntimeException("Oops!");
    }
</code>```

Command to verify offset:

```<code>bin/kafka-consumer-groups.sh --bootstrap-server localhost:9092 --describe --group test-group
</code>```

I'm using kafka_2.12-0.10.2.0 and org.springframework.kafka:spring-kafka:1.1.3.RELEASE

答:
The container (via ContainerProperties) has a property, ackOnError which is true by default...

```<code>/**
 * Set whether or not the container should commit offsets (ack messages) where the
 * listener throws exceptions. This works in conjunction with {@link #ackMode} and is
 * effective only when the kafka property {@code enable.auto.commit} is {@code false};
 * it is not applicable to manual ack modes. When this property is set to {@code true}
 * (the default), all messages handled will have their offset committed. When set to
 * {@code false}, offsets will be committed only for successfully handled messages.
 * Manual acks will be always be applied. Bear in mind that, if the next message is
 * successfully handled, its offset will be committed, effectively committing the
 * offset of the failed message anyway, so this option has limited applicability.
 * Perhaps useful for a component that starts throwing exceptions consistently;
 * allowing it to resume when restarted from the last successfully processed message.
 * @param ackOnError whether the container should acknowledge messages that throw
 * exceptions.
 */
public void setAckOnError(boolean ackOnError) {
    this.ackOnError = ackOnError;
}
</code>```

Bear in mind, though, that if the next message is successful, its offset will be committed anyway, which effectively commits the failed offset too.

EDIT

Starting with version 2.3, ackOnError is now false by default.

Body:
I've been trying to do some POC work for Spring Kafka. Specifically, I wanted to experiment with what are the best practices in terms of dealing with errors while consuming messages within Kafka.

I am wondering if anyone is able to help with:

Sharing best practices surrounding what Kafka consumers should do
when there is a failure

Help me understand how AckMode Record works, and how to prevent commits to the Kafka offset queue when an exception is thrown in the listener method.

The code example for 2 is given below:

Given that AckMode is set to RECORD, which according to the documentation:

commit the offset when the listener returns after processing the
  record.

I would have thought the the offset would not be incremented if the listener method threw an exception. However, this was not the case when I tested it using the code/config/command combination below. The offset still gets updated, and the next message continues to be processed.

My config:

    private Map<String, Object> producerConfigs() {
    Map<String, Object> props = new HashMap<>();
    props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "192.168.0.1:9092");
    props.put(ProducerConfig.RETRIES_CONFIG, 0);
    props.put(ProducerConfig.BATCH_SIZE_CONFIG, 16384);
    props.put(ProducerConfig.LINGER_MS_CONFIG, 1);
    props.put(ProducerConfig.BUFFER_MEMORY_CONFIG, 33554432);
    props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, IntegerSerializer.class);
    props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
    return props;
}

   @Bean
ConcurrentKafkaListenerContainerFactory<Integer, String> kafkaListenerContainerFactory() {
    ConcurrentKafkaListenerContainerFactory<Integer, String> factory =
            new ConcurrentKafkaListenerContainerFactory<>();
    factory.setConsumerFactory(new DefaultKafkaConsumerFactory<>(consumerConfigs()));
    factory.getContainerProperties().setAckMode(AbstractMessageListenerContainer.AckMode.RECORD);
    return factory;
}

My code:

@Component
public class KafkaMessageListener{
    @KafkaListener(topicPartitions = {@TopicPartition( topic = "my-replicated-topic", partitionOffsets = @PartitionOffset(partition = "0", initialOffset = "0", relativeToCurrent = "true"))})
    public void onReplicatedTopicMessage(ConsumerRecord<Integer, String> data) throws InterruptedException {
            throw new RuntimeException("Oops!");
    }

Command to verify offset:

bin/kafka-consumer-groups.sh --bootstrap-server localhost:9092 --describe --group test-group

I'm using kafka_2.12-0.10.2.0 and org.springframework.kafka:spring-kafka:1.1.3.RELEASE

Body:
The container (via ContainerProperties) has a property, ackOnError which is true by default...

/**
 * Set whether or not the container should commit offsets (ack messages) where the
 * listener throws exceptions. This works in conjunction with {@link #ackMode} and is
 * effective only when the kafka property {@code enable.auto.commit} is {@code false};
 * it is not applicable to manual ack modes. When this property is set to {@code true}
 * (the default), all messages handled will have their offset committed. When set to
 * {@code false}, offsets will be committed only for successfully handled messages.
 * Manual acks will be always be applied. Bear in mind that, if the next message is
 * successfully handled, its offset will be committed, effectively committing the
 * offset of the failed message anyway, so this option has limited applicability.
 * Perhaps useful for a component that starts throwing exceptions consistently;
 * allowing it to resume when restarted from the last successfully processed message.
 * @param ackOnError whether the container should acknowledge messages that throw
 * exceptions.
 */
public void setAckOnError(boolean ackOnError) {
    this.ackOnError = ackOnError;
}

Bear in mind, though, that if the next message is successful, its offset will be committed anyway, which effectively commits the failed offset too.

EDIT

Starting with version 2.3, ackOnError is now false by default.


来源: stackexchange

问:
How to ensure a string length in Ruby
What is the proper way to ensure a string length in Ruby? The string is multi-byte (UTF8). The strings inputted can be either too short, exactly right, or too long. It would need respectively padding, nothing and slicing.

I can get there in two steps:

```<code>def ensure_length(str, length)
  str.ljust(length).slice(0, length)
end
</code>```

Is there a single method for this? And if it needs in two steps, what order is best: ljust then slice or vice versa, and why?

答:
```<code> p "%-10.10s" % "abcdabcdabcd"
</code>```

In which the first -10 pads the string to 10 like ljust and the second 10 is the max number of characters. Documented under sprintf.

ContentLicense: CC BY-SA 3.0

Title: How to ensure a string length in Ruby

Body:
What is the proper way to ensure a string length in Ruby? The string is multi-byte (UTF8). The strings inputted can be either too short, exactly right, or too long. It would need respectively padding, nothing and slicing.

I can get there in two steps:

def ensure_length(str, length)
  str.ljust(length).slice(0, length)
end

Is there a single method for this? And if it needs in two steps, what order is best: ljust then slice or vice versa, and why?

Body:
 p "%-10.10s" % "abcdabcdabcd"

In which the first -10 pads the string to 10 like ljust and the second 10 is the max number of characters. Documented under sprintf.


问:
Output of Compute Shader with error (inconsistent value)
I have a issue in unity3D with ComputeShader.

My objective : find all normals facing the camera (dot of two vector > 0)

As my camera and my model are fixed, I expect to get always the same amount of normal in output of my compute shader.

But, each time I use the compute shader, the count increase, leading me to a number of normals facing the camera superior to the number in the mesh and it quickly reach a point where I have 10e9 normals. And sometime this value is negative.

I use a append buffer for this purpose, and my hlsh only test the dot , and append the value to the buffer.

My question is : Where is the problem ?

I suspect a problem with the GPU memory, but I can't find why (first time hlsl/unity3)

C# :
Note : Key is for another test

```<code>public static Vector3[] KeyCam(Vector3 key, Vector3 cam, Vector3[] normal) {
ComputeShader shader = (ComputeShader) Resources.Load("ComputeShader/Normal");
int _kernel = shader.FindKernel("KeyCam");

#region init Buffer
ComputeBuffer inputBuffer = new ComputeBuffer(normal.Length, sizeof(float) * 3);
inputBuffer.SetData(normal);
ComputeBuffer outputBuffer = new ComputeBuffer(normal.Length, sizeof(float) * 3, ComputeBufferType.Append);
#endregion

#region set
shader.SetBuffer(_kernel, "input", inputBuffer);
shader.SetBuffer(_kernel, "output", outputBuffer);
shader.SetVector("key", key);
shader.SetVector("cam", cam);
#endregion

shader.Dispatch(_kernel, 1, 1, 1);

#region get count
//https://sites.google.com/site/aliadevlog/counting-buffers-in-directcompute
ComputeBuffer countBuffer = new ComputeBuffer(1, sizeof(int), ComputeBufferType.IndirectArguments);
ComputeBuffer.CopyCount(outputBuffer, countBuffer, 0);

//Debug.Log("Copy buffer : " + countBuffer.count);
int[] counter = new int[1] { 0 };
countBuffer.GetData(counter);
countBuffer.Release();
int c = counter[0];
#endregion

//int c = GetAppendCount(outputBuffer);
Debug.Log("Normals : " + c +"/"+normal.Length);
if(c <= 0)
    return null;

Vector3[] output = new Vector3[c];
outputBuffer.GetData(output);

inputBuffer.Release();
outputBuffer.Release();

return output;
    }
</code>```

HLSL :

```<code>    #pragma kernel KeyCam
StructuredBuffer<float3> input;
float3 key;
float3 cam;
AppendStructuredBuffer<float3> output;

[numthreads(64,1,1)]
void KeyCam(uint3 id : SV_DispatchThreadID) {

    if (dot(input[id.x], cam) >= 0.05)
        output.Append(input[id.x]);
}
</code>```

答:
Sorry I forgot to answer

I found the answer after

The problem was indeed the counter but also the method of recovery of the value.

```<code>outputBuffer.SetCounterValue(0);
</code>```

and for the value

```<code>        ComputeBuffer counter = new ComputeBuffer(4, sizeof(int), ComputeBufferType.IndirectArguments);
        int[] Counts = new int[] { 0, 1, 0, 0 };
        counter.SetData(Counts);

        counter.SetData(Counts);
        ComputeBuffer.CopyCount(outputBuffer, counter, 0);
        counter.GetData(Counts);
        counter.Release();
        return Counts[0];
</code>```

Body:
I have a issue in unity3D with ComputeShader.

My objective : find all normals facing the camera (dot of two vector > 0)

As my camera and my model are fixed, I expect to get always the same amount of normal in output of my compute shader.

But, each time I use the compute shader, the count increase, leading me to a number of normals facing the camera superior to the number in the mesh and it quickly reach a point where I have 10e9 normals. And sometime this value is negative.

I use a append buffer for this purpose, and my hlsh only test the dot , and append the value to the buffer.

My question is : Where is the problem ?

I suspect a problem with the GPU memory, but I can't find why (first time hlsl/unity3)

C# :
Note : Key is for another test

public static Vector3[] KeyCam(Vector3 key, Vector3 cam, Vector3[] normal) {
ComputeShader shader = (ComputeShader) Resources.Load("ComputeShader/Normal");
int _kernel = shader.FindKernel("KeyCam");

#region init Buffer
ComputeBuffer inputBuffer = new ComputeBuffer(normal.Length, sizeof(float) * 3);
inputBuffer.SetData(normal);
ComputeBuffer outputBuffer = new ComputeBuffer(normal.Length, sizeof(float) * 3, ComputeBufferType.Append);
#endregion

#region set
shader.SetBuffer(_kernel, "input", inputBuffer);
shader.SetBuffer(_kernel, "output", outputBuffer);
shader.SetVector("key", key);
shader.SetVector("cam", cam);
#endregion

shader.Dispatch(_kernel, 1, 1, 1);

#region get count
//https://sites.google.com/site/aliadevlog/counting-buffers-in-directcompute
ComputeBuffer countBuffer = new ComputeBuffer(1, sizeof(int), ComputeBufferType.IndirectArguments);
ComputeBuffer.CopyCount(outputBuffer, countBuffer, 0);

//Debug.Log("Copy buffer : " + countBuffer.count);
int[] counter = new int[1] { 0 };
countBuffer.GetData(counter);
countBuffer.Release();
int c = counter[0];
#endregion

//int c = GetAppendCount(outputBuffer);
Debug.Log("Normals : " + c +"/"+normal.Length);
if(c <= 0)
    return null;

Vector3[] output = new Vector3[c];
outputBuffer.GetData(output);

inputBuffer.Release();
outputBuffer.Release();

return output;
    }

HLSL :

    #pragma kernel KeyCam
StructuredBuffer<float3> input;
float3 key;
float3 cam;
AppendStructuredBuffer<float3> output;

[numthreads(64,1,1)]
void KeyCam(uint3 id : SV_DispatchThreadID) {

    if (dot(input[id.x], cam) >= 0.05)
        output.Append(input[id.x]);
}

Body:
Sorry I forgot to answer

I found the answer after

The problem was indeed the counter but also the method of recovery of the value.

outputBuffer.SetCounterValue(0);

and for the value

        ComputeBuffer counter = new ComputeBuffer(4, sizeof(int), ComputeBufferType.IndirectArguments);
        int[] Counts = new int[] { 0, 1, 0, 0 };
        counter.SetData(Counts);

        counter.SetData(Counts);
        ComputeBuffer.CopyCount(outputBuffer, counter, 0);
        counter.GetData(Counts);
        counter.Release();
        return Counts[0];


问:
problem with scons in windows
I tried to build an executable for a python script using scons, which is failing with the following trace:

```<code>C:\WORKAREA\study>C:\Python26\Scripts\scons
scons: Reading SConscript files ...

scons: warning: No installed VCs
File "C:\WORKAREA\study\SConstruct", line 1, in <module>

scons: warning: No version of Visual Studio compiler found - C/C++ compilers most likely not set correctly
File "C:\WORKAREA\study\SConstruct", line 1, in <module>
scons: done reading SConscript files.
scons: Building targets ...
link /nologo /OUT:fibo.exe fibo.py
'link' is not recognized as an internal or external command,
operable program or batch file.
scons: *** [fibo.exe] Error 1
scons: building terminated because of errors.
</code>```

It seems that link /nologo /OUT is the point where everything breaks down. Can anyone help me with this?

答:
You're trying to build a .exe file from a .py file right? In that case, you don't need the VC++ compiler, you will need a tool like py2exe. And if you want to use SCons as a build system, you will need to create a SCons builder for py2exe.exe. Something along the lines as:

```<code>env = Environment()

def py2exe_action(target, source, env):
  # execute py2exe <source> <output> here
  return 0

env['BUILDERS']['Py2Exe'] = env.Builder(action = py2exe_action)
env.Default(env.Py2Exe(target = 'out_exe_file.exe', source = 'in_python_file.py'))
</code>```

http://www.py2exe.org/

ContentLicense: CC BY-SA 2.5

Title: problem with scons in windows

Body:
I tried to build an executable for a python script using scons, which is failing with the following trace:

C:\WORKAREA\study>C:\Python26\Scripts\scons
scons: Reading SConscript files ...

scons: warning: No installed VCs
File "C:\WORKAREA\study\SConstruct", line 1, in <module>

scons: warning: No version of Visual Studio compiler found - C/C++ compilers most likely not set correctly
File "C:\WORKAREA\study\SConstruct", line 1, in <module>
scons: done reading SConscript files.
scons: Building targets ...
link /nologo /OUT:fibo.exe fibo.py
'link' is not recognized as an internal or external command,
operable program or batch file.
scons: *** [fibo.exe] Error 1
scons: building terminated because of errors.

It seems that link /nologo /OUT is the point where everything breaks down. Can anyone help me with this?

Body:
You're trying to build a .exe file from a .py file right? In that case, you don't need the VC++ compiler, you will need a tool like py2exe. And if you want to use SCons as a build system, you will need to create a SCons builder for py2exe.exe. Something along the lines as:

env = Environment()

def py2exe_action(target, source, env):
  # execute py2exe <source> <output> here
  return 0

env['BUILDERS']['Py2Exe'] = env.Builder(action = py2exe_action)
env.Default(env.Py2Exe(target = 'out_exe_file.exe', source = 'in_python_file.py'))

http://www.py2exe.org/


问:
Android - Real-Time get image data from camera?
I want to do some image processing jobs and I want to get real-time image data from my camera(during preview state) instead of after taking pictures.

I looked on this post but don't know how to use this.

After setting this,

```<code>SurfaceHolder.Callback surfaceCallback=new SurfaceHolder.Callback()
{
    public void surfaceCreated(SurfaceHolder holder) {
       camera.setPreviewCallback(previewCallback);
    }
}
</code>```

and this

```<code>private Camera.PreviewCallback  previewCallback= new Camera.PreviewCallback()
{
    @Override
    public void onPreviewFrame(byte[] data,Camera cam)
    {
            Camera.Size previewSize = cam.getParameters().getPreviewSize();
            YuvImage yuvImage = new YuvImage(data, ImageFormat.NV21,previewSize.width,previewSize.height, null);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            yuvImage.compressToJpeg(new Rect(0,0,previewSize.width,previewSize.height),80,baos);
            byte[] jdata = baos.toByteArray();
            Bitmap bitmap = BitmapFactory.decodeByteArray(jdata,0,jdata.length);
    }
};
</code>```

How can I real-time get my image data? Could anyone please kindly give me an short example code?

Thanks

答:
For doing image processing based operations you can use with OpenCV Library.
Here i given sample code to process the frames directly from camera using OpenCV

```<code>import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;

import org.opencv.android.BaseLoaderCallback;
import org.opencv.android.CameraBridgeViewBase;
import org.opencv.android.JavaCameraView;
import org.opencv.android.LoaderCallbackInterface;
import org.opencv.android.OpenCVLoader;
import org.opencv.core.Mat;

import static org.opencv.core.CvType.CV_8UC1;

public class MainActivity extends AppCompatActivity implements CameraBridgeViewBase.CvCameraViewListener2 {

    private static final String TAG = "MainActivity";
    JavaCameraView javaCameraView;
    Mat frame;
    public static final int CAMERA_PERMISSION_REQUEST_CODE = 3;

    static {
        System.loadLibrary("MyOpenCVLibs");
    }

    private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {
        @Override
        public void onManagerConnected(int status) {
            switch(status){
                case LoaderCallbackInterface.SUCCESS:
                {
                    javaCameraView.enableView();
                } break;
                default:
                {
                    super.onManagerConnected(status);
                } break;
            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (ContextCompat.checkSelfPermission(this,Manifest.permission.CAMERA)!= PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.CAMERA},CAMERA_PERMISSION_REQUEST_CODE);
        }

        javaCameraView = (JavaCameraView) findViewById(R.id.java_camera_view);
        javaCameraView.setVisibility(View.VISIBLE);
        javaCameraView.setCvCameraViewListener(this);
    }

    @Override
    protected void onPause(){
        super.onPause();
        if(javaCameraView!=null)
            javaCameraView.disableView();
    }

    @Override
    protected void onDestroy(){
        super.onDestroy();
        if(javaCameraView!=null)
            javaCameraView.disableView();
    }

    @Override
    protected void  onResume(){

        super.onResume();
        if (OpenCVLoader.initDebug()) {
            Log.i(TAG, "OpenCV loaded successfully.");
            mLoaderCallback.onManagerConnected(LoaderCallbackInterface.SUCCESS);
        } else {
            Log.i(TAG, "OpenCV not loaded.");
            OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_3_1_0, this, mLoaderCallback);
        }
    }

    @Override
    public void onCameraViewStarted(int width, int height) {
        frame=new Mat(height,width,CV_8UC4);

    }

    @Override
    public void onCameraViewStopped() {
        frame.release();
    }

    @Override
    public Mat onCameraFrame(CameraBridgeViewBase.CvCameraViewFrame inputFrame) {
        frame=inputFrame.rgba();

    }
}
</code>```

This code checks OpenCV properly imported or not and Checks permission for Camera.

And each input frames are saved in frame variable.

Body:
I want to do some image processing jobs and I want to get real-time image data from my camera(during preview state) instead of after taking pictures.

I looked on this post but don't know how to use this.

After setting this,

SurfaceHolder.Callback surfaceCallback=new SurfaceHolder.Callback()
{
    public void surfaceCreated(SurfaceHolder holder) {
       camera.setPreviewCallback(previewCallback);
    }
}

and this

private Camera.PreviewCallback  previewCallback= new Camera.PreviewCallback()
{
    @Override
    public void onPreviewFrame(byte[] data,Camera cam)
    {
            Camera.Size previewSize = cam.getParameters().getPreviewSize();
            YuvImage yuvImage = new YuvImage(data, ImageFormat.NV21,previewSize.width,previewSize.height, null);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            yuvImage.compressToJpeg(new Rect(0,0,previewSize.width,previewSize.height),80,baos);
            byte[] jdata = baos.toByteArray();
            Bitmap bitmap = BitmapFactory.decodeByteArray(jdata,0,jdata.length);
    }
};

How can I real-time get my image data? Could anyone please kindly give me an short example code?

Thanks

Body:
For doing image processing based operations you can use with OpenCV Library.
Here i given sample code to process the frames directly from camera using OpenCV

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;

import org.opencv.android.BaseLoaderCallback;
import org.opencv.android.CameraBridgeViewBase;
import org.opencv.android.JavaCameraView;
import org.opencv.android.LoaderCallbackInterface;
import org.opencv.android.OpenCVLoader;
import org.opencv.core.Mat;

import static org.opencv.core.CvType.CV_8UC1;

public class MainActivity extends AppCompatActivity implements CameraBridgeViewBase.CvCameraViewListener2 {

    private static final String TAG = "MainActivity";
    JavaCameraView javaCameraView;
    Mat frame;
    public static final int CAMERA_PERMISSION_REQUEST_CODE = 3;

    static {
        System.loadLibrary("MyOpenCVLibs");
    }

    private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {
        @Override
        public void onManagerConnected(int status) {
            switch(status){
                case LoaderCallbackInterface.SUCCESS:
                {
                    javaCameraView.enableView();
                } break;
                default:
                {
                    super.onManagerConnected(status);
                } break;
            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (ContextCompat.checkSelfPermission(this,Manifest.permission.CAMERA)!= PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.CAMERA},CAMERA_PERMISSION_REQUEST_CODE);
        }

        javaCameraView = (JavaCameraView) findViewById(R.id.java_camera_view);
        javaCameraView.setVisibility(View.VISIBLE);
        javaCameraView.setCvCameraViewListener(this);
    }

    @Override
    protected void onPause(){
        super.onPause();
        if(javaCameraView!=null)
            javaCameraView.disableView();
    }

    @Override
    protected void onDestroy(){
        super.onDestroy();
        if(javaCameraView!=null)
            javaCameraView.disableView();
    }

    @Override
    protected void  onResume(){

        super.onResume();
        if (OpenCVLoader.initDebug()) {
            Log.i(TAG, "OpenCV loaded successfully.");
            mLoaderCallback.onManagerConnected(LoaderCallbackInterface.SUCCESS);
        } else {
            Log.i(TAG, "OpenCV not loaded.");
            OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_3_1_0, this, mLoaderCallback);
        }
    }

    @Override
    public void onCameraViewStarted(int width, int height) {
        frame=new Mat(height,width,CV_8UC4);

    }

    @Override
    public void onCameraViewStopped() {
        frame.release();
    }

    @Override
    public Mat onCameraFrame(CameraBridgeViewBase.CvCameraViewFrame inputFrame) {
        frame=inputFrame.rgba();

    }
}

This code checks OpenCV properly imported or not and Checks permission for Camera.

And each input frames are saved in frame variable.


问:
How to find out what is initiating an (re)render in React
How can you trace what action, state change or dom manipulation is initiating a (re)render?

I'm using TransitionGroup to animate with JS, however before the callback of componentWillLeave(callback) is called, the page re-renders and I have no idea why. What kind can initiate a full page rerender beside forceUpdate() and state change of the top level component?

答:
You can use the lifecycle method componentWillUpdate which fires just before a component is re-rendered due to a change in props or state:

```<code>componentWillUpdate(nextProps, nextState) {
  // Inspect nextProps and nextState to see what triggered this
}
</code>```

Body:
You can use the lifecycle method componentWillUpdate which fires just before a component is re-rendered due to a change in props or state:

componentWillUpdate(nextProps, nextState) {
  // Inspect nextProps and nextState to see what triggered this
}


问:
Count number of appearances in JSON data for nested element
How I can get the appearance of elements in JSON data for nested element?

```<code>[
    {
            "client":"172.16.109.96",
            "check":
                    {
                            "command":"/var/lib/gems/1.9.1/gems/sensu-plugins-graphite-1.1.0/bin/check-graphite-stats.rb -h 172.16.109.96:8081 -t 'highestCurrent(scale(vcenter.*.*.*.*.cpu.usage_percent_average, 0.01), 5)'  -w 1 -c 6 -p -6hours",
                            "standalone":true,
                            "interval":5,
                            "name":"vm_cpu_average",
                            "issued":1490774610,
                            "executed":1490774610,
                            "duration":0.142,
                            "output":"CheckGraphiteStat WARNING: No data from Graphite\n",
                            "status":3,
                            "type":"standard"
                    }
    },
    {
            "client":"172.16.109.96",
            "check":
                    {
                            "command":"/var/lib/gems/1.9.1/gems/sensu-plugins-graphite-1.1.0/bin/check-graphite-stats.rb -h 172.16.109.96:8081 -t 'collectd.*.*.system.memory.used.pct' -w 50 -c 75 -p -6hours",
                            "standalone":true,
                            "interval":5,
                            "name":"mem_average",
                            "issued":1490774614,
                            "executed":1490774614,
                            "duration":0.223,
                            "output":"CheckGraphiteStat CRITICAL: collectd.DEMO.172_16_109_100.system.memory.used.pct is 94.44555555555556 \n",
                            "status":2,
                            "type":"standard"
                    }
    },
    {
            "client":"172.16.109.96",
            "check":
                    {
                            "command":"/var/lib/gems/1.9.1/gems/sensu-plugins-graphite-1.1.0/bin/check-graphite-stats.rb -h 172.16.109.96:8081 -t 'scale(vcenter.*.*.*.*.mem.usage_percent_average, 0.01)' -w 50 -c 75 -p -6hours",
                            "standalone":true,
                            "interval":5,
                            "name":"vm_mem_average",
                            "issued":1490774614,
                            "executed":1490774614,
                            "duration":0.216,
                            "output":"CheckGraphiteStat WARNING: No data from Graphite\n",
                            "status":3,
                            "type":"standard"
                    }
    },
    {
            "client":"172.16.109.96",
            "check":
                    {
                            "command":"/var/lib/gems/1.9.1/gems/sensu-plugins-graphite-1.1.0/bin/check-graphite-stats.rb -h 172.16.109.96:8081 -t 'absolute(offset(collectd.*.*.system.cpu.idle.pct, -100))'  -c 7 -p -6hours",
                            "standalone":true,
                            "interval":5,
                            "name":"cpu_average",
                            "issued":1490774613,
                            "executed":1490774613,
                            "duration":0.124,
                            "output":"CheckGraphiteStat CRITICAL: absolute(offset(collectd.DEMO.172_16_109_100.system.cpu.idle.pct,-100)) is 10.585147058823525 \n",
                            "status":2,
                            "type":"standard"
                    }
    }
</code>```

]

I need to count the number of appearances of WARNING and CRITICAL appeared, if it's appeared in output(check -> output).

Please excuse if this is a novice question. I'm new to this.

答:
You could iterate the array and check with a regular expression the wanted string. Then count accordingly.

var data = [{ client: "172.16.109.96", check: { command: "/var/lib/gems/1.9.1/gems/sensu-plugins-graphite-1.1.0/bin/check-graphite-stats.rb -h 172.16.109.96:8081 -t 'highestCurrent(scale(vcenter.*.*.*.*.cpu.usage_percent_average, 0.01), 5)'  -w 1 -c 6 -p -6hours", standalone: true, interval: 5, name: "vm_cpu_average", issued: 1490774610, executed: 1490774610, duration: 0.142, output: "CheckGraphiteStat WARNING: No data from Graphite\n", status: 3, type: "standard" } }, { client: "172.16.109.96", check: { command: "/var/lib/gems/1.9.1/gems/sensu-plugins-graphite-1.1.0/bin/check-graphite-stats.rb -h 172.16.109.96:8081 -t 'collectd.*.*.system.memory.used.pct' -w 50 -c 75 -p -6hours", standalone: true, interval: 5, name: "mem_average", issued: 1490774614, executed: 1490774614, duration: 0.223, output: "CheckGraphiteStat CRITICAL: collectd.DEMO.172_16_109_100.system.memory.used.pct is 94.44555555555556 \n", status: 2, type: "standard" } }, { client: "172.16.109.96", check: { command: "/var/lib/gems/1.9.1/gems/sensu-plugins-graphite-1.1.0/bin/check-graphite-stats.rb -h 172.16.109.96:8081 -t 'scale(vcenter.*.*.*.*.mem.usage_percent_average, 0.01)' -w 50 -c 75 -p -6hours", standalone: true, interval: 5, name: "vm_mem_average", issued: 1490774614, executed: 1490774614, duration: 0.216, output: "CheckGraphiteStat WARNING: No data from Graphite\n", status: 3, type: "standard" } }, { client: "172.16.109.96", check: { command: "/var/lib/gems/1.9.1/gems/sensu-plugins-graphite-1.1.0/bin/check-graphite-stats.rb -h 172.16.109.96:8081 -t 'absolute(offset(collectd.*.*.system.cpu.idle.pct, -100))'  -c 7 -p -6hours", standalone: true, interval: 5, name: "cpu_average", issued: 1490774613, executed: 1490774613, duration: 0.124, output: "CheckGraphiteStat CRITICAL: absolute(offset(collectd.DEMO.172_16_109_100.system.cpu.idle.pct,-100)) is 10.585147058823525 \n", status: 2, type: "standard" } }],
    count = {};

data.forEach(function (a) {
    var match = a.check.output.match(/CRITICAL|WARNING/);
    if (match) {
        count[match[0]] = (count[match[0]] || 0) + 1;
    }
});

console.log(count);```

Body:
How I can get the appearance of elements in JSON data for nested element?

[
    {
            "client":"172.16.109.96",
            "check":
                    {
                            "command":"/var/lib/gems/1.9.1/gems/sensu-plugins-graphite-1.1.0/bin/check-graphite-stats.rb -h 172.16.109.96:8081 -t 'highestCurrent(scale(vcenter.*.*.*.*.cpu.usage_percent_average, 0.01), 5)'  -w 1 -c 6 -p -6hours",
                            "standalone":true,
                            "interval":5,
                            "name":"vm_cpu_average",
                            "issued":1490774610,
                            "executed":1490774610,
                            "duration":0.142,
                            "output":"CheckGraphiteStat WARNING: No data from Graphite\n",
                            "status":3,
                            "type":"standard"
                    }
    },
    {
            "client":"172.16.109.96",
            "check":
                    {
                            "command":"/var/lib/gems/1.9.1/gems/sensu-plugins-graphite-1.1.0/bin/check-graphite-stats.rb -h 172.16.109.96:8081 -t 'collectd.*.*.system.memory.used.pct' -w 50 -c 75 -p -6hours",
                            "standalone":true,
                            "interval":5,
                            "name":"mem_average",
                            "issued":1490774614,
                            "executed":1490774614,
                            "duration":0.223,
                            "output":"CheckGraphiteStat CRITICAL: collectd.DEMO.172_16_109_100.system.memory.used.pct is 94.44555555555556 \n",
                            "status":2,
                            "type":"standard"
                    }
    },
    {
            "client":"172.16.109.96",
            "check":
                    {
                            "command":"/var/lib/gems/1.9.1/gems/sensu-plugins-graphite-1.1.0/bin/check-graphite-stats.rb -h 172.16.109.96:8081 -t 'scale(vcenter.*.*.*.*.mem.usage_percent_average, 0.01)' -w 50 -c 75 -p -6hours",
                            "standalone":true,
                            "interval":5,
                            "name":"vm_mem_average",
                            "issued":1490774614,
                            "executed":1490774614,
                            "duration":0.216,
                            "output":"CheckGraphiteStat WARNING: No data from Graphite\n",
                            "status":3,
                            "type":"standard"
                    }
    },
    {
            "client":"172.16.109.96",
            "check":
                    {
                            "command":"/var/lib/gems/1.9.1/gems/sensu-plugins-graphite-1.1.0/bin/check-graphite-stats.rb -h 172.16.109.96:8081 -t 'absolute(offset(collectd.*.*.system.cpu.idle.pct, -100))'  -c 7 -p -6hours",
                            "standalone":true,
                            "interval":5,
                            "name":"cpu_average",
                            "issued":1490774613,
                            "executed":1490774613,
                            "duration":0.124,
                            "output":"CheckGraphiteStat CRITICAL: absolute(offset(collectd.DEMO.172_16_109_100.system.cpu.idle.pct,-100)) is 10.585147058823525 \n",
                            "status":2,
                            "type":"standard"
                    }
    }

]

I need to count the number of appearances of WARNING and CRITICAL appeared, if it's appeared in output(check -> output).

Please excuse if this is a novice question. I'm new to this.


问:
Failed to capture snapshot of output files for task
Error:Failed to capture snapshot of output files for task 'transformClassesWithDexForDebug' property 'streamOutputFolder' during up-to-date check.

Failed to create MD5 hash for file 'C:\Users\GauravZone\AndroidStudioProjects\ZopporoStore\app\build\intermediates\transforms\dex\debug\folders\1000\10000\instant-run_83dbc65f4e3a4cd278807c089695c6b352698791\classes.dex'.

I am getting these errors don't know why, all application working fine earlier but suddenly getting this error in my all applications when try to run projects

答:
This is a Gradle issue and you can find it here.
So as of now just disable Instant Run.
It worked for me.</p>


问:
Return a promise from service
I have this service where I do like this

```<code>userRes.getCurrentUser = () => {
    return userRes.get({
        user: 1
    });
};
</code>```

Which I use in my controller like this

```<code>console.log(currUserService.getCurrentUser());
</code>```

and it works fine, I get back a promise and the object when it is resolved

BUT

I want to create a class after I get the data, so I do like this

```<code>userRes.getCurrentUser = () => {
    userRes.get({
        user: 1
    }).$promise.then(data => {
        return new User(data);
    });
};
</code>```

But then I get undefined

How can I make it return the class?

Thank you

Edit

```<code>let userRes = $resource('url', {}, {});
</code>```

答:
I'm not sure what exactly userRes is, but in general, .then() returns its promise chain.

Changing

```<code>userRes.getCurrentUser = () => {
    userRes.get({
        user: 1
    }).$promise.then(data => {
        return new User(data);
    });
};
</code>```

to

```<code>userRes.getCurrentUser = () => {
    return userRes.get({ // !! Notice the return statement here
        user: 1
    }).$promise.then(data => {
        return new User(data);
    });
};
</code>```

will give you the promise chain, which you can add another .then() onto  to utilize the new User returned previously.

Title: Return a promise from service

Body:
I have this service where I do like this

userRes.getCurrentUser = () => {
    return userRes.get({
        user: 1
    });
};

Which I use in my controller like this

console.log(currUserService.getCurrentUser());

and it works fine, I get back a promise and the object when it is resolved

BUT

I want to create a class after I get the data, so I do like this

userRes.getCurrentUser = () => {
    userRes.get({
        user: 1
    }).$promise.then(data => {
        return new User(data);
    });
};

But then I get undefined

How can I make it return the class?

Thank you

Edit

let userRes = $resource('url', {}, {});

Body:
I'm not sure what exactly userRes is, but in general, .then() returns its promise chain.

Changing

userRes.getCurrentUser = () => {
    userRes.get({
        user: 1
    }).$promise.then(data => {
        return new User(data);
    });
};

to

userRes.getCurrentUser = () => {
    return userRes.get({ // !! Notice the return statement here
        user: 1
    }).$promise.then(data => {
        return new User(data);
    });
};

will give you the promise chain, which you can add another .then() onto  to utilize the new User returned previously.


问:
Unable to fetch commit from github
The following commands fail to check out this commit:

```<code>$ git clone git@github.com:DefinitelyTyped/DefinitelyTyped.git
$ cd DefinitelyTyped
$ git checkout e90424c424ef9087d0589234e9e9cd0140bab0d7
fatal: reference is not a tree: e90424c424ef9087d0589234e9e9cd0140bab0d7
</code>```

Attempting to follow the advice given here results in the following:

```<code>$ git fetch origin e90424c424ef9087d0589234e9e9cd0140bab0d7
$ echo $?
1
</code>```

Is this failure something specific to GitHub / large repos on GitHub?  My git version is 2.10.1.

** edit **

```<code>$ git fetch origin e90424c424ef9087d0589234e9e9cd0140bab0d7:refs/remotes/origin/foo-commit
$ echo $?
1
$ git cat-file -p e90424c424ef9087d0589234e9e9cd0140bab0d7
fatal: Not a valid object name e90424c424ef9087d0589234e9e9cd0140bab0d7
$ git branch -a --contains e90424c424ef9087d0589234e9e9cd0140bab0d7
error: no such commit e90424c424ef9087d0589234e9e9cd0140bab0d7
$ git reset e90424c424ef9087d0589234e9e9cd0140bab0d7
fatal: Could not parse object 'e90424c424ef9087d0589234e9e9cd0140bab0d7'.
</code>```

答:
You can check whether e90424c424ef9087d0589234e9e9cd0140bab0d7 commit is the part of current branch or not.

```<code>git branch -a --contains e90424c424ef9087d0589234e9e9cd0140bab0d7
</code>```

With this, you can see list of all branches which contains this hash commit.

Also with "checkout" option works with branch names not with hash commit. Using hash commit with checkout either results in "detached head state" or "fatal: reference is not a tree."

If you want to navigate to specific commit in your current branch use git reset with soft/hard options.

```<code>git reset e90424c424ef9087d0589234e9e9cd0140bab0d7
git reset --hard e90424c424ef9087d0589234e9e9cd0140bab0d7
</code>```

This will update your HEAD pointer to specific commit.

Title: Unable to fetch commit from github

Body:
The following commands fail to check out this commit:

$ git clone git@github.com:DefinitelyTyped/DefinitelyTyped.git
$ cd DefinitelyTyped
$ git checkout e90424c424ef9087d0589234e9e9cd0140bab0d7
fatal: reference is not a tree: e90424c424ef9087d0589234e9e9cd0140bab0d7

Attempting to follow the advice given here results in the following:

$ git fetch origin e90424c424ef9087d0589234e9e9cd0140bab0d7
$ echo $?
1

Is this failure something specific to GitHub / large repos on GitHub?  My git version is 2.10.1.

** edit **

$ git fetch origin e90424c424ef9087d0589234e9e9cd0140bab0d7:refs/remotes/origin/foo-commit
$ echo $?
1
$ git cat-file -p e90424c424ef9087d0589234e9e9cd0140bab0d7
fatal: Not a valid object name e90424c424ef9087d0589234e9e9cd0140bab0d7
$ git branch -a --contains e90424c424ef9087d0589234e9e9cd0140bab0d7
error: no such commit e90424c424ef9087d0589234e9e9cd0140bab0d7
$ git reset e90424c424ef9087d0589234e9e9cd0140bab0d7
fatal: Could not parse object 'e90424c424ef9087d0589234e9e9cd0140bab0d7'.

Body:
You can check whether e90424c424ef9087d0589234e9e9cd0140bab0d7 commit is the part of current branch or not.

git branch -a --contains e90424c424ef9087d0589234e9e9cd0140bab0d7

With this, you can see list of all branches which contains this hash commit.

Also with "checkout" option works with branch names not with hash commit. Using hash commit with checkout either results in "detached head state" or "fatal: reference is not a tree."

If you want to navigate to specific commit in your current branch use git reset with soft/hard options.

git reset e90424c424ef9087d0589234e9e9cd0140bab0d7
git reset --hard e90424c424ef9087d0589234e9e9cd0140bab0d7

This will update your HEAD pointer to specific commit.


问:
Python 3 urlopen usage
I'm working on a python script that will communicate with the API of a CRM system I'm deploying right now. I can get data from the CRM server, but I can't seem to add (write) a new entry. I suspect I'm doing something silly because I'm fairly new to Python and programming in general, can someone point me in the right direction? The server does not reject the data, but it acts as if I was requesting data from /api/v1.0/payments as opposed to posting new data.

```<code>from urllib.request import Request, urlopen

headers = {
  'Content-Type': 'application/json',
  'X-Auth-App-Key': '[API key]'
}

values = b"""
  {
"clientId": 104,
"method": 3,
"checkNumber": "",
"createdDate": "2016-09-12T00:00:00+0000",
"amount": 40,
"note": "",
  }
"""

request = Request('http://[SERVER_URL]/api/v1.0/payments', data=values, headers=headers)

response_body = urlopen(request).read()
print(response_body)
</code>```

I'm working based on example code from the API documentation here:
http://docs.ucrm.apiary.io/#reference/payments/payments/post

Am I using urlopen correctly at the bottom?

答:
This question/answer may be your issue. Basically your POST request is being redirected to /api/v1.0/payments/ (note the trailing slash), when that happens your POST is redirected to a GET request, which is why the server is responding as if you were trying to retrieve all of the payments info.

Other things to note are your json data is actually invalid as it contains a trailing , after the 'note' value, so that may be an issue issue too. I think you may also be missing the Content-Length header in your headers. I'd recommend using the json module to create your json data:

```<code>values = json.dumps({
    "clientId": 104,
     "method": 3,
     "checkNumber": "",
     "createdDate": "2016-09-12T00:00:00+0000",
     "amount": 40,
     "note": ""
})

headers = {
  'Content-Type': 'application/json',
  'Content-Length': len(values),
  'X-Auth-App-Key': '[API key]'
}

request = Request('http://[SERVER_URL]/api/v1.0/payments/', data=values, headers=headers)
</code>```

Title: Python 3 urlopen usage

Body:
I'm working on a python script that will communicate with the API of a CRM system I'm deploying right now. I can get data from the CRM server, but I can't seem to add (write) a new entry. I suspect I'm doing something silly because I'm fairly new to Python and programming in general, can someone point me in the right direction? The server does not reject the data, but it acts as if I was requesting data from /api/v1.0/payments as opposed to posting new data.

from urllib.request import Request, urlopen

headers = {
  'Content-Type': 'application/json',
  'X-Auth-App-Key': '[API key]'
}

values = b"""
  {
"clientId": 104,
"method": 3,
"checkNumber": "",
"createdDate": "2016-09-12T00:00:00+0000",
"amount": 40,
"note": "",
  }
"""

request = Request('http://[SERVER_URL]/api/v1.0/payments', data=values, headers=headers)

response_body = urlopen(request).read()
print(response_body)

I'm working based on example code from the API documentation here:
http://docs.ucrm.apiary.io/#reference/payments/payments/post

Am I using urlopen correctly at the bottom?

Body:
This question/answer may be your issue. Basically your POST request is being redirected to /api/v1.0/payments/ (note the trailing slash), when that happens your POST is redirected to a GET request, which is why the server is responding as if you were trying to retrieve all of the payments info.

Other things to note are your json data is actually invalid as it contains a trailing , after the 'note' value, so that may be an issue issue too. I think you may also be missing the Content-Length header in your headers. I'd recommend using the json module to create your json data:

values = json.dumps({
    "clientId": 104,
     "method": 3,
     "checkNumber": "",
     "createdDate": "2016-09-12T00:00:00+0000",
     "amount": 40,
     "note": ""
})

headers = {
  'Content-Type': 'application/json',
  'Content-Length': len(values),
  'X-Auth-App-Key': '[API key]'
}

request = Request('http://[SERVER_URL]/api/v1.0/payments/', data=values, headers=headers)


问:
How to deep copy a class without marking it as Serializable
Given the following class:

```<code>class A
{
    public List<B> ListB;

    // etc...
}
</code>```

where B is another class that may inherit/contain some other classes.

Given this scenario:

A is a large class and contains many reference types

I cannot mark B as [Serializable] as I don't have access to source code of B

The following methods to perform deep copying do not work:

I cannot use ICloneable or MemberwiseClone as class A contains many reference types

I cannot write a copy constructor for A, as the class is large and continuously being added to, and contains classes (like B) that cannot be deep copied

I cannot use serialization as I cannot mark a contained class (like B, where no source code available) as [Serializable]

How can I deep copy class A?

答:
Try using a memory stream to get a deep copy of your object:

```<code> public static T MyDeepCopy<T>(this T source)
            {
                try
                {

                    //Throw if passed object has nothing
                    if (source == null) { throw new Exception("Null Object cannot be cloned"); }

                    // Don't serialize a null object, simply return the default for that object
                    if (Object.ReferenceEquals(source, null))
                    {
                        return default(T);
                    }

                    //variable declaration
                    T copy;
                    var obj = new DataContractSerializer(typeof(T));
                    using (var memStream = new MemoryStream())
                    {
                        obj.WriteObject(memStream, source);
                        memStream.Seek(0, SeekOrigin.Begin);
                        copy = (T)obj.ReadObject(memStream);
                    }
                    return copy;
                }
                catch (Exception)
                {
                    throw;
                }
            }
</code>```

Here is more.

Body:
Given the following class:

class A
{
    public List ListB;

    // etc...
}

where B is another class that may inherit/contain some other classes.

Given this scenario:

A is a large class and contains many reference types

I cannot mark B as [Serializable] as I don't have access to source code of B

The following methods to perform deep copying do not work:

I cannot use ICloneable or MemberwiseClone as class A contains many reference types

I cannot write a copy constructor for A, as the class is large and continuously being added to, and contains classes (like B) that cannot be deep copied

I cannot use serialization as I cannot mark a contained class (like B, where no source code available) as [Serializable]

How can I deep copy class A?

Body:
Try using a memory stream to get a deep copy of your object:

 public static T MyDeepCopy<T>(this T source)
            {
                try
                {

                    //Throw if passed object has nothing
                    if (source == null) { throw new Exception("Null Object cannot be cloned"); }

                    // Don't serialize a null object, simply return the default for that object
                    if (Object.ReferenceEquals(source, null))
                    {
                        return default(T);
                    }

                    //variable declaration
                    T copy;
                    var obj = new DataContractSerializer(typeof(T));
                    using (var memStream = new MemoryStream())
                    {
                        obj.WriteObject(memStream, source);
                        memStream.Seek(0, SeekOrigin.Begin);
                        copy = (T)obj.ReadObject(memStream);
                    }
                    return copy;
                }
                catch (Exception)
                {
                    throw;
                }
            }

Here is more.


问:
@ionic-native/network value capture from observable
I am using the @ionic-native/network with the cordova-plugin-network-information plugin for checking online-offline status. However i'm having difficulty updating the network status.

home.ts

```<code>import { Network } from '@ionic-native/network';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
public online:boolean=false;
  constructor(public navCtrl: NavController,private network: Network) {
      this.network.onDisconnect().subscribe(() => {
         this.online=false;
         console.log(this.online);      });
      this.network.onConnect().subscribe(() => {
          this.online=true;
        console.log(this.online);
      });
  }

}
</code>```

home.html

```<code><ion-header>
  <ion-navbar>
    <ion-title>
      Ionic Blank
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
  <h1>{{online}}</h1>
</ion-content>
</code>```

However on running the application, it only shows false, yet the console.log(this.online) shows true-false changes whenever i toggle the wifi. Any suggestions on how to make the interface values to changes as well.

答:
Try and use ChangeDetectorRef, if change detection for some reason isn't happening in template:

import { ChangeDetectorRef } from '@angular/core';

constructor(private ref: ChangeDetectorRef) { }

  this.network.onDisconnect().subscribe(() => {
     this.online = false;
     console.log(this.online);
     this.ref.detectChanges(); // run
  });
  this.network.onConnect().subscribe(() => {
      this.online=true;
      console.log(this.online);
      this.ref.detectChanges(); // run
  });
}
```

Body:
I am using the @ionic-native/network with the cordova-plugin-network-information plugin for checking online-offline status. However i'm having difficulty updating the network status.

home.ts

import { Network } from '@ionic-native/network';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
public online:boolean=false;
  constructor(public navCtrl: NavController,private network: Network) {
      this.network.onDisconnect().subscribe(() => {
         this.online=false;
         console.log(this.online);      });
      this.network.onConnect().subscribe(() => {
          this.online=true;
        console.log(this.online);
      });
  }

}

home.html

<ion-header>
  <ion-navbar>
    <ion-title>
      Ionic Blank
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>

{{online}}

</ion-content>

However on running the application, it only shows false, yet the console.log(this.online) shows true-false changes whenever i toggle the wifi. Any suggestions on how to make the interface values to changes as well.


问:
Object oriented design in javascript and 'this' pointer
I am creating a object in javascript like this

```<code>function myobject() {
   this.myvar1 = 0;
   this.myvar2 = 0;
}

myobject.prototype.a = function(){
    this.myvar1 +=1;
    $('#button').click(function () {  // 'this' is undefined
        alert(this.myvar1)
     })
}

var mything = new myobject();
mything.a()
</code>```

What is the proper way to pass the this pointer to an anonymous function?

答:
For updated question:
The issue is that inside that event handler, this refers to the element you clicked on, rather than your myobject, so just keep a reference to it, like this:

```<code>myobject.prototype.a = function(){
    this.myvar1 +=1;
    var self = this;
    $('#button').click(function () {
        alert(self.myvar1)
    });
}
</code>```

You can test it out here.

For previous question:
What you have should work (exactly as you have it), you can test it here.

Body:
I am creating a object in javascript like this

function myobject() {
   this.myvar1 = 0;
   this.myvar2 = 0;
}

myobject.prototype.a = function(){
    this.myvar1 +=1;
    $('#button').click(function () {  // 'this' is undefined
        alert(this.myvar1)
     })
}

var mything = new myobject();
mything.a()

What is the proper way to pass the this pointer to an anonymous function?

Body:
For updated question:
The issue is that inside that event handler, this refers to the element you clicked on, rather than your myobject, so just keep a reference to it, like this:

myobject.prototype.a = function(){
    this.myvar1 +=1;
    var self = this;
    $('#button').click(function () {
        alert(self.myvar1)
    });
}

You can test it out here.

For previous question:
What you have should work (exactly as you have it), you can test it here.


问:
Find if a JSONObject contains a particular JSONARray
I am working on a spring MVC application. I am using org.json jar to deal with jsonObjects. I am trying to find if a JSONObject contains a JSON array. Can any one please help me in this:

Say i have a JSON Object:

```<code>{"Object":{
   "array":["",""]
}
}
</code>```

So i want to know if array exists in that json object as some times the JSONObject will be :

```<code>{"Object":{
   "array11":["",""]
}
}
</code>```

Please help me.

答:
You can use org.json (https://github.com/stleary/JSON-java) to do this. You can simply use this code to create the JSON Object:

```<code>JSONObject object = new JSONObject(String);
</code>```

And then you can use the isNull(String) method to check if a value exists in the object. You can get the array using the getJSONArray(String) method, create a loop (such as a for loop) and loop through the array (which accepts ints instead of Strings).

Body:
I am working on a spring MVC application. I am using org.json jar to deal with jsonObjects. I am trying to find if a JSONObject contains a JSON array. Can any one please help me in this:

Say i have a JSON Object:

{"Object":{
   "array":["",""]
}
}

So i want to know if array exists in that json object as some times the JSONObject will be :

{"Object":{
   "array11":["",""]
}
}

Please help me.

Body:
You can use org.json (https://github.com/stleary/JSON-java) to do this. You can simply use this code to create the JSON Object:

JSONObject object = new JSONObject(String);

And then you can use the isNull(String) method to check if a value exists in the object. You can get the array using the getJSONArray(String) method, create a loop (such as a for loop) and loop through the array (which accepts ints instead of Strings).


问:
What is vendor_id in CloudJobTicket (CJT)?
How is this vendor Id gonna use when creating a cloudJobTicket & sending the print job to cloud? what can it do?

link -> https://developers.google.com/cloud-print/docs/cdd#cjt

答:
vendor_id

vendor_id is an attribute that appears in some CDD as well as CJT items (color, media size, dpi, etc). Generally, it holds an internal ID that the printer uses to disambiguate same values that need to have different behaviour on the printer.

For example, a printer may support 1 resolution (300dpi) but 3 quality settings (draft, normal, best). Since there's no quality setting either on CDD or CJT, their CDD could look like:

```<code>{
    "version": "1.0",
    "print": {
        "dpi": {
            "option": [
                {
                    "horizontal_dpi": 300,
                    "vertical_dpi": 300,
                    "vendor_id": "draft300dpi"
                    "custom_display_name": "300dpi - DRAFT"
                },
                {
                    "horizontal_dpi": 300,
                    "vertical_dpi": 300,
                    "is_default": true,
                    "vendor_id": "normal300dpi"
                    "custom_display_name": "300dpi - NORMAL"
                },
                {
                    "horizontal_dpi": 300,
                    "vertical_dpi": 300,
                    "vendor_id": "best300dpi"
                    "custom_display_name": "300dpi - BEST"
                }
            ]
        },
        (...)
    }
}
</code>```

If in you set the first option for the CJT, it will look like:

```<code>{
    "version": "1.0",
    "print": {
        "dpi": {
            "horizontal_dpi": 300,
            "vertical_dpi": 300,
            "vendor_id": "normal300dpi"
        }
    }
}
</code>```

If you don't set up vendor_id in your CJT, printer will not be able to disambiguate between its internal options, and may not decide what you really selected.

vendor_id is always optional for a printer to provide it in the CDD. As a consequence, it is also optional for a client to provide it in the CJT (check in the documentation, it is always preceded by the optional keyword). My recommendation is that you forward the same value the printer is providing to you for the setting you select in your CJT, in case it provides something.

VendorTicketItem

On the other hand, then there is the VendorTicketItem, which can be used by a printer to expose additional capabilities that are not covered by the items that the specification provides. Printers can use it to advertise these additional features in their CDD, and clients can set them in the CJT.

Body:
vendor_id

vendor_id is an attribute that appears in some CDD as well as CJT items (color, media size, dpi, etc). Generally, it holds an internal ID that the printer uses to disambiguate same values that need to have different behaviour on the printer.

For example, a printer may support 1 resolution (300dpi) but 3 quality settings (draft, normal, best). Since there's no quality setting either on CDD or CJT, their CDD could look like:

{
    "version": "1.0",
    "print": {
        "dpi": {
            "option": [
                {
                    "horizontal_dpi": 300,
                    "vertical_dpi": 300,
                    "vendor_id": "draft300dpi"
                    "custom_display_name": "300dpi - DRAFT"
                },
                {
                    "horizontal_dpi": 300,
                    "vertical_dpi": 300,
                    "is_default": true,
                    "vendor_id": "normal300dpi"
                    "custom_display_name": "300dpi - NORMAL"
                },
                {
                    "horizontal_dpi": 300,
                    "vertical_dpi": 300,
                    "vendor_id": "best300dpi"
                    "custom_display_name": "300dpi - BEST"
                }
            ]
        },
        (...)
    }
}

If in you set the first option for the CJT, it will look like:

{
    "version": "1.0",
    "print": {
        "dpi": {
            "horizontal_dpi": 300,
            "vertical_dpi": 300,
            "vendor_id": "normal300dpi"
        }
    }
}

If you don't set up vendor_id in your CJT, printer will not be able to disambiguate between its internal options, and may not decide what you really selected.

vendor_id is always optional for a printer to provide it in the CDD. As a consequence, it is also optional for a client to provide it in the CJT (check in the documentation, it is always preceded by the optional keyword). My recommendation is that you forward the same value the printer is providing to you for the setting you select in your CJT, in case it provides something.

VendorTicketItem

On the other hand, then there is the VendorTicketItem, which can be used by a printer to expose additional capabilities that are not covered by the items that the specification provides. Printers can use it to advertise these additional features in their CDD, and clients can set them in the CJT.


问:
Performant way to convert adjacency list to links for undirected graph
I have an adjacency list like below:

```<code>const list = [
 [1, 6, 8],
 [0, 4, 6, 9],
 [4, 6],
 [4, 5, 8],
 // ...
];
</code>```

I need to create a set of links for an undirected graph without duplicates (example bellow).
Such links as [0,1] and [1,0] are considered duplicates.

```<code>const links = [
 [ 0, 1 ], // duplicates
 [ 0, 6 ],
 [ 0, 8 ],
 [ 1, 0 ], // duplicates
 [ 1, 4 ],
 // ...
]
</code>```

Right now I do it this way:

```<code>const links = new Set;
const skip = [];

list.forEach( (v, i) => {
    v.forEach( j => {
        if (skip.indexOf(j) === -1) {
            links.add([i, j]);
        }
    })
    skip.push(i);
})
</code>```

I am wondering if there is a better pattern to solve this kind of task on massive arrays.

答:
You can use one object to store value: index that has already been used and then check that object before adding to array.

const list = [[1, 6, 8],[0, 4, 6, 9],[4, 6],[4, 5, 8],];
var o = {},r = []

list.forEach(function(e, i) {
  e.forEach(function(a) {
    if (o[i] != a) {
      r.push([i, a])
      o[a] = i
    }
  })
})

console.log(JSON.stringify(r))```
</div>
</div>
</p>

<p>With ES6 arrow functions you can write the same like this.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const list = [[1, 6, 8], [0, 4, 6, 9], [4, 6], [4, 5, 8],];
var o = {}, r = []

list.forEach((e, i) => e.forEach(a => o[i] != a ? (r.push([i, a]), o[a] = i) : null))
console.log(JSON.stringify(r))</code>```

Body:
I have an adjacency list like below:

const list = [
 [1, 6, 8],
 [0, 4, 6, 9],
 [4, 6],
 [4, 5, 8],
 // ...
];

I need to create a set of links for an undirected graph without duplicates (example bellow).
Such links as [0,1] and [1,0] are considered duplicates.

const links = [
 [ 0, 1 ], // duplicates
 [ 0, 6 ],
 [ 0, 8 ],
 [ 1, 0 ], // duplicates
 [ 1, 4 ],
 // ...
]

Right now I do it this way:

const links = new Set;
const skip = [];

list.forEach( (v, i) => {
    v.forEach( j => {
        if (skip.indexOf(j) === -1) {
            links.add([i, j]);
        }
    })
    skip.push(i);
})

I am wondering if there is a better pattern to solve this kind of task on massive arrays.

Body:
You can use one object to store value: index that has already been used and then check that object before adding to array.

const list = [[1, 6, 8],[0, 4, 6, 9],[4, 6],[4, 5, 8],];
var o = {},r = []

list.forEach(function(e, i) {
  e.forEach(function(a) {
    if (o[i] != a) {
      r.push([i, a])
      o[a] = i
    }
  })
})

console.log(JSON.stringify(r))

With ES6 arrow functions you can write the same like this.

const list = [[1, 6, 8], [0, 4, 6, 9], [4, 6], [4, 5, 8],];
var o = {}, r = []

list.forEach((e, i) => e.forEach(a => o[i] != a ? (r.push([i, a]), o[a] = i) : null))
console.log(JSON.stringify(r))


问:
Do null pointer deference and uninitialized memory belong to memory corruption
In wikipedia, memory corruption is defined as follows:

Memory corruption occurs in a computer program when the contents of a
  memory location are unintentionally modified due to programming
  errors; this is termed violating memory safety.

But in the subsequent description, null pointer dereference and uninitialized memory are considered memory corruption.

I'm a little confused. Null pointer dereference and uninitialized memory do not unintentionally modify the contents of a memory location. Why are they regarded as memory corruption?

答:
"Memory corruption" is not a formal term, so it is not very meaningful to go look for a formal definition. Also, Wikipedia is not necessarily a canonical source of information.

A null pointer access may or may not lead to memory corruption. Mostly this depends on if the system allows writes to address 0 or not1).

Similarly, using an uninitialized or "dangling" pointer that points at any random location can cause any kind of behavior, including memory corruption.

These all fall under the formal term undefined behavior, which means that anything can happen should you invoke such behavior.

1) In theory, the C language forbids the compiler to give a null pointer an address that might correspond to a real address on the target. In practice, compilers most often don't do this but just use the address zero. Which is a valid address on many microcontroller systems or other such computers that allow direct access to physical memory.


问:
C- gethostbyaddr & Valgrind
For some reason valgrind keeps throwing the following error:

```<code>==6263== Invalid read of size 4
==6263==    at 0x40151B9: (within /lib/ld-2.7.so)
==6263==    by 0x4005C29: (within /lib/ld-2.7.so)
==6263==    by 0x4007A47: (within /lib/ld-2.7.so)
==6263==    by 0x40114F3: (within /lib/ld-2.7.so)
==6263==    by 0x400D585: (within /lib/ld-2.7.so)
==6263==    by 0x4010F0D: (within /lib/ld-2.7.so)
==6263==    by 0x4141391: (within /lib/tls/i686/cmov/libc-2.7.so)
==6263==    by 0x400D585: (within /lib/ld-2.7.so)
==6263==    by 0x4141554: __libc_dlopen_mode (in /lib/tls/i686/cmov/libc-2.7.so)
==6263==    by 0x411B286: __nss_lookup_function (in /lib/tls/i686/cmov/libc-2.7.so)
==6263==    by 0x411B39F: (within /lib/tls/i686/cmov/libc-2.7.so)
==6263==    by 0x411CFC5: __nss_hosts_lookup (in /lib/tls/i686/cmov/libc-2.7.so)
==6263==  Address 0x4183d24 is 36 bytes inside a block of size 37 alloc'd
==6263==    at 0x4022AB8: malloc (vg_replace_malloc.c:207)
</code>```

Here is the way I'm doing it. Any reasons why this is happening? Thanks

```<code>#include <arpa/inet.h>
#include <netdb.h>
#include <stdio.h>
#include <string.h>

char *IPtoHostname(const char *ipaddress)
{
    struct hostent *host;
    unsigned int ip = 0;
    ip = inet_addr (ipaddress);
    host = gethostbyaddr ((char *) &ip, sizeof (unsigned int), AF_INET);
    if (host == NULL) return NULL;
    return strdup(host->h_name);
}

int main () {
   const char *ip = "65.55.4.170";
   char *a =  NULL;
   a = IPtoHostname(ip);
   printf ("%s\n", a);
   free (a);

   return 0;
}
</code>```

Update: It happens when I run it under Linux hardy 2.6.24-16-generic It does not happen under Ubuntu 9.10

答:
Your code is OK (although you should really be using in_addr_t instead of unsigned int for the variable ip in IPtoHostname()).

The Valgrind report is a well-known issue - either a false positive or a bug in glibc.

Title: C- gethostbyaddr & Valgrind

Body:
For some reason valgrind keeps throwing the following error:

==6263== Invalid read of size 4
==6263==    at 0x40151B9: (within /lib/ld-2.7.so)
==6263==    by 0x4005C29: (within /lib/ld-2.7.so)
==6263==    by 0x4007A47: (within /lib/ld-2.7.so)
==6263==    by 0x40114F3: (within /lib/ld-2.7.so)
==6263==    by 0x400D585: (within /lib/ld-2.7.so)
==6263==    by 0x4010F0D: (within /lib/ld-2.7.so)
==6263==    by 0x4141391: (within /lib/tls/i686/cmov/libc-2.7.so)
==6263==    by 0x400D585: (within /lib/ld-2.7.so)
==6263==    by 0x4141554: __libc_dlopen_mode (in /lib/tls/i686/cmov/libc-2.7.so)
==6263==    by 0x411B286: __nss_lookup_function (in /lib/tls/i686/cmov/libc-2.7.so)
==6263==    by 0x411B39F: (within /lib/tls/i686/cmov/libc-2.7.so)
==6263==    by 0x411CFC5: __nss_hosts_lookup (in /lib/tls/i686/cmov/libc-2.7.so)
==6263==  Address 0x4183d24 is 36 bytes inside a block of size 37 alloc'd
==6263==    at 0x4022AB8: malloc (vg_replace_malloc.c:207)

Here is the way I'm doing it. Any reasons why this is happening? Thanks

#include <arpa/inet.h>
#include <netdb.h>
#include <stdio.h>
#include <string.h>

char *IPtoHostname(const char *ipaddress)
{
    struct hostent *host;
    unsigned int ip = 0;
    ip = inet_addr (ipaddress);
    host = gethostbyaddr ((char *) &ip, sizeof (unsigned int), AF_INET);
    if (host == NULL) return NULL;
    return strdup(host->h_name);
}

int main () {
   const char *ip = "65.55.4.170";
   char *a =  NULL;
   a = IPtoHostname(ip);
   printf ("%s\n", a);
   free (a);

   return 0;
}

Update: It happens when I run it under Linux hardy 2.6.24-16-generic It does not happen under Ubuntu 9.10


问:
How to add miliseconds to my timer?
I try to put milliseconds to my timer, but they act like seconds instead of milliseconds. They're already after the seconds. But there not acting like the milliseconds. Also I have been trying to make the percentage see how far the countdown is. So how can I fix this?

This is the link with the whole script: http://embed.plnkr.co/hUeAAzBBszAnCq7FdeGO/

// Code goes here
window.addEventListener('load', start);

function start() {
  countdown();
}

function isNumberKey(evt) {
  var charCode = (evt.which) ? evt.which : event.keyCode;
  if (charCode > 31 && (charCode < 48 || charCode > 57))
  //if charcode is keycode more then 31 and keycode less then 48 and more then 57 return false
  {
    return false;
    //aren't numbers
  } else {
    return true;
    //only can type numbers
  }
}

function countdown(val) {
  var counter = parseInt(val);
  var myVar = setInterval(function() {
    if (counter >= 0) {
      document.getElementById("timer").innerHTML = Math.floor(counter / 60) + ":" + ("0" + Math.floor(counter) % 60).slice(-2) + "." + Math.floor((counter % 1000) * 1000) / 1000;
      //counter/60 calculates the minute and counter%60 calculates the seconds.
      counter--;
    }
    if (counter < 0) {
      document.getElementById("timer").innerHTML = "That was the countdown";
    }
  }, 1000)
}

var stop = 0;

function decrease() {
  var percent = Number($('#counter span').text());
  if (percent > stop) {
    $('#counter span').text(--percent);
    var t = setTimeout(decrease, 1000);
  }
}

setTimeout(decrease, 1000);

function count() {
  var input = document.getElementById("number_input").value;
  countdown(input);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

only numbers please :
<input type="text" placeholder="type in a number" id="number_input" onkeypress="return isNumberKey(event)" />
<button onclick="count()">tel af</button>

<p id="timer">0</p>
<div id="counter">
  <p><span>100</span>%</p>
</div></code>```

答:
You are using 1000 in your Timeout and Interval.  That number is in Milliseconds. You will have to do some math to count down seconds and milliseconds at the same time.

Not related to your question: You are using JQuery and getElementById. Why not change

```<code>document.getElementById("timer").innerHTML
</code>```

into

```<code>$("#timer").html(...)
</code>```

Title: How to add miliseconds to my timer?

Body:
I try to put milliseconds to my timer, but they act like seconds instead of milliseconds. They're already after the seconds. But there not acting like the milliseconds. Also I have been trying to make the percentage see how far the countdown is. So how can I fix this?

This is the link with the whole script: http://embed.plnkr.co/hUeAAzBBszAnCq7FdeGO/

// Code goes here
window.addEventListener('load', start);

function start() {
  countdown();
}

function isNumberKey(evt) {
  var charCode = (evt.which) ? evt.which : event.keyCode;
  if (charCode > 31 && (charCode < 48 || charCode > 57))
  //if charcode is keycode more then 31 and keycode less then 48 and more then 57 return false
  {
    return false;
    //aren't numbers
  } else {
    return true;
    //only can type numbers
  }
}

function countdown(val) {
  var counter = parseInt(val);
  var myVar = setInterval(function() {
    if (counter >= 0) {
      document.getElementById("timer").innerHTML = Math.floor(counter / 60) + ":" + ("0" + Math.floor(counter) % 60).slice(-2) + "." + Math.floor((counter % 1000) * 1000) / 1000;
      //counter/60 calculates the minute and counter%60 calculates the seconds.
      counter--;
    }
    if (counter < 0) {
      document.getElementById("timer").innerHTML = "That was the countdown";
    }
  }, 1000)
}

var stop = 0;

function decrease() {
  var percent = Number($('#counter span').text());
  if (percent > stop) {
    $('#counter span').text(--percent);
    var t = setTimeout(decrease, 1000);
  }
}

setTimeout(decrease, 1000);

function count() {
  var input = document.getElementById("number_input").value;
  countdown(input);
}

only numbers please :
<input type="text" placeholder="type in a number" id="number_input" onkeypress="return isNumberKey(event)" />
<button onclick="count()">tel af</button>

0

100%

Body:
You are using 1000 in your Timeout and Interval.  That number is in Milliseconds. You will have to do some math to count down seconds and milliseconds at the same time.

Not related to your question: You are using JQuery and getElementById. Why not change

document.getElementById("timer").innerHTML

into

$("#timer").html(...)


问:
Consume SOAP service in mule flow

This is my first time that i am using mule.
I had created a simple flow in anypoint studio to consume WSDL. I am able to make contact with WSDL service and generate XML, when the WSDL sends simple string in xml but when WSDL sends user defined object via xml then problem starts, in section of webservice consumer the payload shows error:
"The actual payload metadata does not match the expected one".

It suggest me to add DataMapper element to transform one form to another.

Then i tried mapping and experimenting in Transfprm message component, but unable to resolve the issue.

Please suggest me what to do and how to resolve this.
Below is snap of web service consumer component where payload shows the error:

Below is image of tansform Message component:

Thanks.

答:
If you are using Community Runtime then DataWeaver is not supported. Instead try using CXF component. In order to consume webservice, instead of using HTTP as endpoint, if possible use servlet endpoint.

I had similar scenario where I have published a SOAP and in the implementation of WebMethod I have consumed another SOAP. Please let me know if you need extra information on my approach.

Title: Consume SOAP service in mule flow


问:
UWP RichEditBox equivalent of GetCharIndexFromPosition
It seems like the GetCharIndexFromPosition is missing in UWP's richeditbox. I want to display a tooltip when a certain range is hovered over in a RichEditBox. Is this possible with UWP?</p>

答:
In UWP, we can use GetRangeFromPoint(Point, PointOptions) method as the equivalent of GetCharIndexFromPosition. This method retrieves the degenerate (empty) text range at, or nearest to, a particular point on the screen. It returns a ITextRange object and the StartPosition property of ITextRange is similar to the character index returned by GetCharIndexFromPosition method.

The following is a simple sample:

XAML:

```<code><Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <RichEditBox x:Name="editor" />
</Grid>
</code>```

Code-behind:

```<code>public MainPage()
{
    this.InitializeComponent();
    editor.Document.SetText(Windows.UI.Text.TextSetOptions.None, @"This is a text for testing.");
    editor.AddHandler(PointerMovedEvent, new PointerEventHandler(editor_PointerMoved), true);
}

private void editor_PointerMoved(object sender, PointerRoutedEventArgs e)
{
    var position = e.GetCurrentPoint(editor).Position;

    var range = editor.Document.GetRangeFromPoint(position, Windows.UI.Text.PointOptions.ClientCoordinates);

    System.Diagnostics.Debug.WriteLine(range.StartPosition);
}
</code>```

Body:
In UWP, we can use GetRangeFromPoint(Point, PointOptions) method as the equivalent of GetCharIndexFromPosition. This method retrieves the degenerate (empty) text range at, or nearest to, a particular point on the screen. It returns a ITextRange object and the StartPosition property of ITextRange is similar to the character index returned by GetCharIndexFromPosition method.

The following is a simple sample:

XAML:

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <RichEditBox x:Name="editor" />
</Grid>

Code-behind:

public MainPage()
{
    this.InitializeComponent();
    editor.Document.SetText(Windows.UI.Text.TextSetOptions.None, @"This is a text for testing.");
    editor.AddHandler(PointerMovedEvent, new PointerEventHandler(editor_PointerMoved), true);
}

private void editor_PointerMoved(object sender, PointerRoutedEventArgs e)
{
    var position = e.GetCurrentPoint(editor).Position;

    var range = editor.Document.GetRangeFromPoint(position, Windows.UI.Text.PointOptions.ClientCoordinates);

    System.Diagnostics.Debug.WriteLine(range.StartPosition);
}


问:
Escape character in WCF service calls
I am implementing WCF Rest Service for  a mobile app.

This is one of the property of return object which I get on response of a service call:

```<code>"flagURL":"http:\/\/localhost\/testservice\/img\/CountryFlags\/Ireland.png"
</code>```

When I  debug the code there is no escape character '/',and json looks like this

```<code>"flagURL":"http:\\localhost\testservice\img\CountryFlags\Ireland.png"
</code>```

How does the service add an escape character to above property ? What should I do to fix this ?

答:
Your JSON is getting double-serialized. (The extra backslashes in the JSON are symptomatic of this.) To make it work, you need to ensure that the output is only serialized once.

there is a simple solution for that. just return stream except string:

```<code>  public stream checkSymbolExistJson(string pSymbol)
  {
        Person p    = new Person();
        p.name      = pSymbol;
        p.age       = 15;

    string json = JsonConvert.SerializeObject(p);
    return new MemoryStream(Encoding.UTF8.GetBytes(json));
  }
</code>```

Title: Escape character in WCF service calls

Body:
I am implementing WCF Rest Service for  a mobile app.

This is one of the property of return object which I get on response of a service call:

"flagURL":"http:\/\/localhost\/testservice\/img\/CountryFlags\/Ireland.png"

When I  debug the code there is no escape character '/',and json looks like this

"flagURL":"http:\\localhost\testservice\img\CountryFlags\Ireland.png"

How does the service add an escape character to above property ? What should I do to fix this ?

Body:
Your JSON is getting double-serialized. (The extra backslashes in the JSON are symptomatic of this.) To make it work, you need to ensure that the output is only serialized once.

there is a simple solution for that. just return stream except string:

  public stream checkSymbolExistJson(string pSymbol)
  {
        Person p    = new Person();
        p.name      = pSymbol;
        p.age       = 15;

    string json = JsonConvert.SerializeObject(p);
    return new MemoryStream(Encoding.UTF8.GetBytes(json));
  }


答:
In your last example it doesn't return anything, you should return a Promise there by adding return.

After you return Promise<User> in the service, in the class where you call it, you should do something like this:

```<code>var userPromise = currUserService.getCurrentUser(); // Promise<User> type
userPromise.then(user => { /* do something with the user when it is resolved*/});
</code>```

Title: Return a promise from service

Body:
I have this service where I do like this

userRes.getCurrentUser = () => {
    return userRes.get({
        user: 1
    });
};

Which I use in my controller like this

console.log(currUserService.getCurrentUser());

and it works fine, I get back a promise and the object when it is resolved

BUT

I want to create a class after I get the data, so I do like this

userRes.getCurrentUser = () => {
    userRes.get({
        user: 1
    }).$promise.then(data => {
        return new User(data);
    });
};

But then I get undefined

How can I make it return the class?

Thank you

Edit

let userRes = $resource('url', {}, {});

Body:
In your last example it doesn't return anything, you should return a Promise there by adding return.

After you return Promise<User> in the service, in the class where you call it, you should do something like this:

var userPromise = currUserService.getCurrentUser(); // Promise<User> type
userPromise.then(user => { /* do something with the user when it is resolved*/});


问:
Segmentation Fault in linkedlist and debugging options for Linux
full code: ( https://github.com/martin-varbanov96/fmi_summer_2017/tree/master/daa/bfs )

So I have to do a graph BFS, but first I have to make a fully working linkedList and I have a problem with the segmentation fault.

The real problem here is that I am using Linux and trying to learn vim and so I have no good way of debugging and I have to use gdb.

The general problem is that I have a node struct and I want to assign it a value but it gives a Segmentation fault. Here is the node:

```<code>struct node{
        int value;
        node* next;
};
</code>```

and than in the main function, program crashes in the assigment:

```<code>int main(){
        node* b;
        b->value=1;
        linkedList a;
         ...
</code>```

this is the gdb result:

```<code>Wed Mar 29; 15:59:29; marton;~/documents/github/fmi_summer_2017/daa/bfs ;  $  gdb a.out
GNU gdb (GDB; openSUSE Leap 42.1) 7.11.1
Copyright (C) 2016 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "x86_64-suse-linux".
Type "show configuration" for configuration details.
For bug reporting instructions, please see:
<http://bugs.opensuse.org/>.
Find the GDB manual and other documentation resources online at:
<http://www.gnu.org/software/gdb/documentation/>.
For help, type "help".
Type "apropos word" to search for commands related to "word"...
Reading symbols from a.out...done.
(gdb) start
Temporary breakpoint 1 at 0x4008f5: file main.cpp, line 5.
Starting program: /home/marton/documents/github/fmi_summer_2017/daa/bfs/a.out
step
Temporary breakpoint 1, main () at main.cpp:5
5               b->value=1;
(gdb) step

Program received signal SIGSEGV, Segmentation fault.
0x00000000004008f9 in main () at main.cpp:5
5               b->value=1;
(gdb)

Program terminated with signal SIGSEGV, Segmentation fault.
The program no longer exists.
(gdb)
</code>```

So my question is what is the problem with my code and what do I need to do to fix it and is there a better way to debug my things in the future?

EDIT:

changes main, as said:

```<code>int main(){
        node* b=new node();
        b->value=1;
</code>```

gdb:

```<code>Temporary breakpoint 1, main () at main.cpp:4
4               node* b=new node();
(gdb) step
operator new (sz=16) at ../../../../libstdc++-v3/libsupc++/new_op.cc:43
43      ../../../../libstdc++-v3/libsupc++/new_op.cc: No such file or directory.
(gdb)
48      in ../../../../libstdc++-v3/libsupc++/new_op.cc
(gdb)
43      in ../../../../libstdc++-v3/libsupc++/new_op.cc
(gdb)
48      in ../../../../libstdc++-v3/libsupc++/new_op.cc
(gdb)
50      in ../../../../libstdc++-v3/libsupc++/new_op.cc
(gdb)

__GI___libc_malloc (bytes=16) at malloc.c:2897
2897    malloc.c: No such file or directory.
(gdb)
2902    in malloc.c
(gdb)
2903    in malloc.c
(gdb)
2906    in malloc.c
(gdb)
2908    in malloc.c
(gdb)
_int_malloc (av=av@entry=0x7ffff753a620 <main_arena>, bytes=bytes@entry=16) at malloc.c:3325
3325    in malloc.c
(gdb)
3355    in malloc.c
(gdb)
3359    in malloc.c
(gdb)
3373    in malloc.c
(gdb)
3375    in malloc.c
</code>```

Real problem is how to debug properly with vim and linux

答:
You should initialize b pointer before assign value to it</p>

```<code>node *b = new node();
b->value = 1;
</code>```

Body:
full code: ( https://github.com/martin-varbanov96/fmi_summer_2017/tree/master/daa/bfs )

So I have to do a graph BFS, but first I have to make a fully working linkedList and I have a problem with the segmentation fault.

The real problem here is that I am using Linux and trying to learn vim and so I have no good way of debugging and I have to use gdb.

The general problem is that I have a node struct and I want to assign it a value but it gives a Segmentation fault. Here is the node:

struct node{
        int value;
        node* next;
};

and than in the main function, program crashes in the assigment:

int main(){
        node* b;
        b->value=1;
        linkedList a;
         ...

this is the gdb result:

Wed Mar 29; 15:59:29; marton;~/documents/github/fmi_summer_2017/daa/bfs ;  $  gdb a.out
GNU gdb (GDB; openSUSE Leap 42.1) 7.11.1
Copyright (C) 2016 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "x86_64-suse-linux".
Type "show configuration" for configuration details.
For bug reporting instructions, please see:
<http://bugs.opensuse.org/>.
Find the GDB manual and other documentation resources online at:
<http://www.gnu.org/software/gdb/documentation/>.
For help, type "help".
Type "apropos word" to search for commands related to "word"...
Reading symbols from a.out...done.
(gdb) start
Temporary breakpoint 1 at 0x4008f5: file main.cpp, line 5.
Starting program: /home/marton/documents/github/fmi_summer_2017/daa/bfs/a.out
step
Temporary breakpoint 1, main () at main.cpp:5
5               b->value=1;
(gdb) step

Program received signal SIGSEGV, Segmentation fault.
0x00000000004008f9 in main () at main.cpp:5
5               b->value=1;
(gdb)

Program terminated with signal SIGSEGV, Segmentation fault.
The program no longer exists.
(gdb)

So my question is what is the problem with my code and what do I need to do to fix it and is there a better way to debug my things in the future?

EDIT:

changes main, as said:

int main(){
        node* b=new node();
        b->value=1;

gdb:

Temporary breakpoint 1, main () at main.cpp:4
4               node* b=new node();
(gdb) step
operator new (sz=16) at ../../../../libstdc++-v3/libsupc++/new_op.cc:43
43      ../../../../libstdc++-v3/libsupc++/new_op.cc: No such file or directory.
(gdb)
48      in ../../../../libstdc++-v3/libsupc++/new_op.cc
(gdb)
43      in ../../../../libstdc++-v3/libsupc++/new_op.cc
(gdb)
48      in ../../../../libstdc++-v3/libsupc++/new_op.cc
(gdb)
50      in ../../../../libstdc++-v3/libsupc++/new_op.cc
(gdb)

__GI___libc_malloc (bytes=16) at malloc.c:2897
2897    malloc.c: No such file or directory.
(gdb)
2902    in malloc.c
(gdb)
2903    in malloc.c
(gdb)
2906    in malloc.c
(gdb)
2908    in malloc.c
(gdb)
_int_malloc (av=av@entry=0x7ffff753a620 <main_arena>, bytes=bytes@entry=16) at malloc.c:3325
3325    in malloc.c
(gdb)
3355    in malloc.c
(gdb)
3359    in malloc.c
(gdb)
3373    in malloc.c
(gdb)
3375    in malloc.c

Real problem is how to debug properly with vim and linux

Body:
You should initialize b pointer before assign value to it

node *b = new node();
b->value = 1;


问:
Comparing variables from file
script is in python and it is used to create a file that saves username and password, I understand that there are flaws in the overall script but I want to know:
when script is executed, a username and password is saved into a file separated with ','. each line is a start of a new username. When login function is called, the list is searched and compared with the entered username, after found is positive: password is checked and this is where my script doesn't work as intended.
Why can't I get a positive when comparing 2 variables (for password in login function), they should be identical.(note y, is the line read from file of usernames & passwords, where the first element is username and second password)

```<code>def function():

    username=input('enter username')
    password=input('enter password')

    file=open('users1','a')
    file.write(username + ',' + password +'\n')

def login():

    user=input('username')
    passw=input('password')

    file=open('users','r')
    searchline=file.readline()

    for line in file:
        if user in line:
            x=line
            y=x.split(',')
            print(y[1])
            if user == y[1]:
                print('access confirmed')
            else:
                print('pass=', y[1])

function()

login()
</code>```

答:
The file you writing to and reading from have different names (users1 and users). Each line read from the file has an end of line character (\n) need to strip that out before comparing the passwords.

```<code>def function():

        username = input('enter username')
        password = input('enter password')

        file = open('users','a')
        file.write(username + ',' + password + '\n')

def login():

        username = input('username')
        password = input('password')

        file = open('users','r')

        for line in file:
            if username in line:
                y = line.rstrip().split(',')
                print(y[1])
                if password == y[1]:
                    print('access confirmed')
                else:
                    print('password =', y[1])

function()

login()
</code>```

checkout the python documentation on rstrip

Title: Comparing variables from file

Body:
script is in python and it is used to create a file that saves username and password, I understand that there are flaws in the overall script but I want to know:
when script is executed, a username and password is saved into a file separated with ','. each line is a start of a new username. When login function is called, the list is searched and compared with the entered username, after found is positive: password is checked and this is where my script doesn't work as intended.
Why can't I get a positive when comparing 2 variables (for password in login function), they should be identical.(note y, is the line read from file of usernames & passwords, where the first element is username and second password)

def function():

    username=input('enter username')
    password=input('enter password')

    file=open('users1','a')
    file.write(username + ',' + password +'\n')

def login():

    user=input('username')
    passw=input('password')

    file=open('users','r')
    searchline=file.readline()

    for line in file:
        if user in line:
            x=line
            y=x.split(',')
            print(y[1])
            if user == y[1]:
                print('access confirmed')
            else:
                print('pass=', y[1])

function()

login()

Body:
The file you writing to and reading from have different names (users1 and users). Each line read from the file has an end of line character (\n) need to strip that out before comparing the passwords.

def function():

        username = input('enter username')
        password = input('enter password')

        file = open('users','a')
        file.write(username + ',' + password + '\n')

def login():

        username = input('username')
        password = input('password')

        file = open('users','r')

        for line in file:
            if username in line:
                y = line.rstrip().split(',')
                print(y[1])
                if password == y[1]:
                    print('access confirmed')
                else:
                    print('password =', y[1])

function()

login()

checkout the python documentation on rstrip