问:
Reading user-space address address when debugging kext
I'd like to read user space address from lldb when debugging remote machine driver (kext) via kdp. I know that in code I could use copyin in order to move the code to kernel space and read it easily, so as expected when I've tried to read user memory directly it failed :

```<code>(lldb) memory read 0x000070000d15a024
error: kdp read memory failed (error 4)
</code>```

is there some alternative to copyin during runtime debugging session to convert my data somewhere I could read it from the debugger ?

thanks

答:
Assuming you load the debug scripts for the specific kernel you use (should be in the appropriate KDK), you have the printuserdata command.

This is its description:

```<code>printuserdata:
    Read userspace data for given task and print based on format provided.
    Syntax: (lldb) printuserdata <task_t> <uspace_address> <format_specifier>
    params:
        <task_t> : pointer to task
        <uspace_address> : address to user space memory
        <format_specifier> : String representation for processing the data and printing it.
                             e.g Q -> unsigned long long, q -> long long, I -> unsigned int, i -> int
                             10i -> 10 ints, 20s -> 20 character string, s -> null terminated string
                             See: https://docs.python.org/2/library/struct.html#format-characters
    options:
        -X : print all values in hex.
        -O <file path>: Save data to file
</code>```

Example invocation:

```<code>(lldb) printuserdata 0xffffff8013257d80 0x00007fff941f5000 10c
</code>```

Body:
I'd like to read user space address from lldb when debugging remote machine driver (kext) via kdp. I know that in code I could use copyin in order to move the code to kernel space and read it easily, so as expected when I've tried to read user memory directly it failed :

(lldb) memory read 0x000070000d15a024
error: kdp read memory failed (error 4)

is there some alternative to copyin during runtime debugging session to convert my data somewhere I could read it from the debugger ?

thanks

Body:
Assuming you load the debug scripts for the specific kernel you use (should be in the appropriate KDK), you have the printuserdata command.

This is its description:

printuserdata:
    Read userspace data for given task and print based on format provided.
    Syntax: (lldb) printuserdata <task_t> <uspace_address> <format_specifier>
    params:
        <task_t> : pointer to task
        <uspace_address> : address to user space memory
        <format_specifier> : String representation for processing the data and printing it.
                             e.g Q -> unsigned long long, q -> long long, I -> unsigned int, i -> int
                             10i -> 10 ints, 20s -> 20 character string, s -> null terminated string
                             See: https://docs.python.org/2/library/struct.html#format-characters
    options:
        -X : print all values in hex.
        -O <file path>: Save data to file

Example invocation:

(lldb) printuserdata 0xffffff8013257d80 0x00007fff941f5000 10c


来源: stackexchange

问:
Escape JavaScript encoded strings in PHP
I am receiving a snippet of javascript from a POST request. Here is (part) as an example

```<code>iCart.updateBlock($$('div.cart', 'div.layout-1column'), "<div class=\"cart\">\n\n    <div class=\"page-title title-buttons\">\n        <h1>Basket<\/h1>\n
</code>```

I can probably strip the javascript using basic php string manipulation if the javascript code is consistent between calls. So then I am left with the javascript encoded string

```<code><div class=\"cart\">\n\n    <div class=\"page-title title-buttons\">\n        <h1>Basket<\/h1>\n
</code>```

I basically want to do what this site explains in reverse

Horizontal Tab is replaced with \t

Vertical Tab is replaced with \v

Nul char is replaced with \0

Backspace is replaced with \b

Form feed is replaced with \f

Newline is replaced with \n

Carriage return is replaced with \r

Single quote is replaced with \'

Double quote is replaced with \"

Backslash is replaced with \

Is there a PHP function that does this? I don't particularly want to write a parser to do this. Result being

```<code><div class="cart"><div class="page-title title-buttons"><h1>Basket<\/h1>
</code>```

I can only provide a small snippet of the returned javascript. When the full string is run through the site linked, the HTML that is un-escaped is complete and valid.

ContentLicense: CC BY-SA 3.0

Body:
I am receiving a snippet of javascript from a POST request. Here is (part) as an example

iCart.updateBlock($$('div.cart', 'div.layout-1column'), "
\n\n
\n
Basket<\/h1>\n

I can probably strip the javascript using basic php string manipulation if the javascript code is consistent between calls. So then I am left with the javascript encoded string

\n\n
\n
Basket<\/h1>\n

I basically want to do what this site explains in reverse

Horizontal Tab is replaced with \t

Vertical Tab is replaced with \v

Nul char is replaced with \0

Backspace is replaced with \b

Form feed is replaced with \f

Newline is replaced with \n

Carriage return is replaced with \r

Single quote is replaced with \'

Double quote is replaced with \"

Backslash is replaced with \

Is there a PHP function that does this? I don't particularly want to write a parser to do this. Result being

Basket<\/h1>

I can only provide a small snippet of the returned javascript. When the full string is run through the site linked, the HTML that is un-escaped is complete and valid.

Body:
For my purposes, this was good enough

$html = strtr($html, [
    "\t"    => '',
    "\v"    => '',
    "\n"    => '',
    "\\\\"  => "\\",
    "\\\""  => "\"",
    "\'"    => "'",
    "\r"    => '',
    "\b"    => '',
    "\f"    => '',
    "\/"    => '/',
]);


问:
onclick not working with selectpicker multiselect dropdown
I have a selectpicker multiselect dropdown. I'm not able to invoke 'onclick' when I select any option. But this works with the normal html multiple dropdown. How to make it work with selectpicker?

Here's the code:

```<code> <!DOCTYPE html>
   <html>
     <head>
       <meta charset="utf-8">
       <meta name="viewport" content="width=device-width, initial-scale=1">

       <link rel="stylesheet"
       href="//cdnjs.cloudflare.com/ajax/libs/bootstrap-
       select/1.6.3/css/bootstrap-select.min.css" />
       <link rel="stylesheet" href="https:
       //maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
       <script
         src=
         "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
       </script>
       <script
         src=
       "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"
 >
       </script>
       <script src="//cdnjs.cloudflare.com/ajax/libs/bootstrap-
         select/1.6.3/js/bootstrap-select.min.js"></script>
     </head>
     <body>

       <form action="/action_page.php">
         <select class="selectpicker" name="cars"  multiple>
         <option value="volvo" onclick="myFunction(this)">Volvo</option>
         <option value="bmw" onclick="myFunction(this)">Bmw</option>
         <option value="opel" onclick="myFunction(this)">Opel</option>
         <option value="audi" onclick="myFunction(this)">Audi</option>
         </select>
         <input type="submit">
       </form>

       <p>Hold down the Ctrl (windows) / Command (Mac) button to select
        multiple options.</p>

       <script type="text/javascript">
         function myFunction(option) {

           if (option.selected) {
             alert(option.text);
           }
         }

       </script>
   </body>

 </html>
</code>```

答:
try this, use forEach to find selected option

var selectEl = document.querySelector('.selectpicker');
var options = document.querySelectorAll('.selectpicker option');
selectEl.addEventListener('change', function() {
    options.forEach(function(option) {
      if(option.selected) { alert(option.value); }
    })
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><select class="selectpicker" name="cars"  multiple>
 <option value="volvo">Volvo</option>
 <option value="bmw">Bmw</option>
 <option value="opel">Opel</option>
 <option value="audi">Audi</option>
 </select></code>```

or use jQuery find :select

$('.selectpicker').change(function() {
   var thisValue = $(this).find(':selected').attr('value') ;
   alert(thisValue);
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<select class="selectpicker" name="cars"  multiple>
 <option value="volvo">Volvo</option>
 <option value="bmw">Bmw</option>
 <option value="opel">Opel</option>
 <option value="audi">Audi</option>
 </select></code>```

Hope help :)

Body:
I have a selectpicker multiselect dropdown. I'm not able to invoke 'onclick' when I select any option. But this works with the normal html multiple dropdown. How to make it work with selectpicker?

Here's the code:

 <!DOCTYPE html>

       <meta charset="utf-8">
       <meta name="viewport" content="width=device-width, initial-scale=1">

       <link rel="stylesheet"
       href="//cdnjs.cloudflare.com/ajax/libs/bootstrap-
       select/1.6.3/css/bootstrap-select.min.css" />
       <link rel="stylesheet" href="https:
       //maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

       <form action="/action_page.php">
         <select class="selectpicker" name="cars"  multiple>
         <option value="volvo" onclick="myFunction(this)">Volvo</option>
         <option value="bmw" onclick="myFunction(this)">Bmw</option>
         <option value="opel" onclick="myFunction(this)">Opel</option>
         <option value="audi" onclick="myFunction(this)">Audi</option>
         </select>
         <input type="submit">
       </form>

Hold down the Ctrl (windows) / Command (Mac) button to select
        multiple options.

Body:
try this, use forEach to find selected option

var selectEl = document.querySelector('.selectpicker');
var options = document.querySelectorAll('.selectpicker option');
selectEl.addEventListener('change', function() {
    options.forEach(function(option) {
      if(option.selected) { alert(option.value); }
    })
})

<select class="selectpicker" name="cars"  multiple>
 <option value="volvo">Volvo</option>
 <option value="bmw">Bmw</option>
 <option value="opel">Opel</option>
 <option value="audi">Audi</option>
 </select>

or use jQuery find :select

$('.selectpicker').change(function() {
   var thisValue = $(this).find(':selected').attr('value') ;
   alert(thisValue);
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<select class="selectpicker" name="cars"  multiple>
 <option value="volvo">Volvo</option>
 <option value="bmw">Bmw</option>
 <option value="opel">Opel</option>
 <option value="audi">Audi</option>
 </select>

Hope help :)


问:
Karaf configuration
When installing karaf in one computer and shifting it to another, lot of base directories have deafult path made during installation.
how to change the variables KARAF_BASE, KARAF_ETC, KARAF_DATA in karaf?</p>

答:
In karaf–folder/bin/karaf.bat, you can override these variables.

Example:

```<code>-Dkaraf.etc="%KARAF_HOME%\..."
</code>```

Note: you can also customize the KARAF_HOME variable at the begin of the karaf.bat script.

Title: Karaf configuration

Body:
In karaf–folder/bin/karaf.bat, you can override these variables.

Example:

-Dkaraf.etc="%KARAF_HOME%\..."

Note: you can also customize the KARAF_HOME variable at the begin of the karaf.bat script.


问:
Equivalent to CryptoStream .NET in Java?
I have an encrypted string in visual basic. NET 2008, the functions to encrypt and decrypt are the following:

```<code>Imports System.Security.Cryptography

 Public Shared Function Encriptar(ByVal strValor As String) As String
    Dim strEncrKey As String = "key12345"
    Dim byKey() As Byte = {}
    Dim IV() As Byte = {&H12, &H34, &H56, &H78, &H90, &HAB, &HCD, &HEF}
    Try
        byKey = System.Text.Encoding.UTF8.GetBytes(strEncrKey)
        Dim des As New DESCryptoServiceProvider
        Dim inputByteArray() As Byte = Encoding.UTF8.GetBytes(strValor)
        Dim ms As New MemoryStream
        Dim cs As New CryptoStream(ms, des.CreateEncryptor(byKey, IV), CryptoStreamMode.Write)
        cs.Write(inputByteArray, 0, inputByteArray.Length)
        cs.FlushFinalBlock()
        Return Convert.ToBase64String(ms.ToArray())
    Catch ex As Exception
        Return ""
    End Try
End Function

Public Shared Function Desencriptar(ByVal strValor As String) As String
    Dim sDecrKey As String = "key12345"
    Dim byKey() As Byte = {}
    Dim IV() As Byte = {&H12, &H34, &H56, &H78, &H90, &HAB, &HCD, &HEF}
    Dim inputByteArray(strValor.Length) As Byte
    Try
        byKey = System.Text.Encoding.UTF8.GetBytes(sDecrKey)
        Dim des As New DESCryptoServiceProvider
        If Trim(strValor).Length = 0 Then
            Throw New Exception("Password No debe estar en Blanco")
        End If
        inputByteArray = Convert.FromBase64String(strValor)
        Dim ms As New MemoryStream
        Dim cs As New CryptoStream(ms, des.CreateDecryptor(byKey, IV), CryptoStreamMode.Write)
        cs.Write(inputByteArray, 0, inputByteArray.Length)
        cs.FlushFinalBlock()
        Dim encoding As System.Text.Encoding = System.Text.Encoding.UTF8
        Return encoding.GetString(ms.ToArray(), 0, ms.ToArray.Count)
    Catch ex As Exception
        Return ""
    End Try
End Function
</code>```

for example the word "android" encrypted with this function gives me the result "B3xogi/Qfsc="

now I need to decrypt the string "B3xogi/Qfsc=" it from java, by the same key, which is "key12345", and the result should be "android"...anyone know how to do this?

Thanks in advance.

答:
You're using DES encryption.

Here is an example on how to encrypt and decrypt with DES.

The main point is to create a SecretKey, a Cipher using it, and decrypt your String with it.

Mmmh...

I found another article that may best suit your question, because it uses IVBytes :)

ContentLicense: CC BY-SA 2.5

Body:
I have an encrypted string in visual basic. NET 2008, the functions to encrypt and decrypt are the following:

Imports System.Security.Cryptography

 Public Shared Function Encriptar(ByVal strValor As String) As String
    Dim strEncrKey As String = "key12345"
    Dim byKey() As Byte = {}
    Dim IV() As Byte = {&H12, &H34, &H56, &H78, &H90, &HAB, &HCD, &HEF}
    Try
        byKey = System.Text.Encoding.UTF8.GetBytes(strEncrKey)
        Dim des As New DESCryptoServiceProvider
        Dim inputByteArray() As Byte = Encoding.UTF8.GetBytes(strValor)
        Dim ms As New MemoryStream
        Dim cs As New CryptoStream(ms, des.CreateEncryptor(byKey, IV), CryptoStreamMode.Write)
        cs.Write(inputByteArray, 0, inputByteArray.Length)
        cs.FlushFinalBlock()
        Return Convert.ToBase64String(ms.ToArray())
    Catch ex As Exception
        Return ""
    End Try
End Function

Public Shared Function Desencriptar(ByVal strValor As String) As String
    Dim sDecrKey As String = "key12345"
    Dim byKey() As Byte = {}
    Dim IV() As Byte = {&H12, &H34, &H56, &H78, &H90, &HAB, &HCD, &HEF}
    Dim inputByteArray(strValor.Length) As Byte
    Try
        byKey = System.Text.Encoding.UTF8.GetBytes(sDecrKey)
        Dim des As New DESCryptoServiceProvider
        If Trim(strValor).Length = 0 Then
            Throw New Exception("Password No debe estar en Blanco")
        End If
        inputByteArray = Convert.FromBase64String(strValor)
        Dim ms As New MemoryStream
        Dim cs As New CryptoStream(ms, des.CreateDecryptor(byKey, IV), CryptoStreamMode.Write)
        cs.Write(inputByteArray, 0, inputByteArray.Length)
        cs.FlushFinalBlock()
        Dim encoding As System.Text.Encoding = System.Text.Encoding.UTF8
        Return encoding.GetString(ms.ToArray(), 0, ms.ToArray.Count)
    Catch ex As Exception
        Return ""
    End Try
End Function

for example the word "android" encrypted with this function gives me the result "B3xogi/Qfsc="

now I need to decrypt the string "B3xogi/Qfsc=" it from java, by the same key, which is "key12345", and the result should be "android"...anyone know how to do this?

Thanks in advance.


问:
Find the position of a bitmap in android imageview when container view scaled centerInside
I have an RelativeLayout that contains a custom ImageView, the scaleType="centerInside", I load in a bitmap (usually smaller than the imageView). How can I get the top/left position of where the bitmap was drawn? I need to be able addView's on top a positions relative to the bitmap.

```<code>   RelativeLayout view = (RelativeLayout) inflater.inflate(R.layout.scroll_scaled, container, false);
ContentImageView image = (ContentImageView) view.findViewById(R.id.base_page);
Bitmap bm = mInterfaceActivity.getPageImage(mPageNumber);
image.setImageBitmap(bm);`
</code>```

The layout file scrolled_scaled

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
    android:scaleType="centerInside"
    android:id="@+id/base_page"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ff00ff00"
    android:contentDescription="@string/product_page"
    android:src="@android:drawable/ic_menu_report_image" >
</ImageView>
</RelativeLayout>
</code>```

答:
This method returns the bounds of image inside imageView.</p>

```<code>/**
 * Helper method to get the bounds of image inside the imageView.
 *
 * @param imageView the imageView.
 * @return bounding rectangle of the image.
 */
public static RectF getImageBounds(ImageView imageView) {
    RectF bounds = new RectF();
    Drawable drawable = imageView.getDrawable();
    if (drawable != null) {
        imageView.getImageMatrix().mapRect(bounds, new RectF(drawable.getBounds()));
    }
    return bounds;
}
</code>```

Body:
I have an RelativeLayout that contains a custom ImageView, the scaleType="centerInside", I load in a bitmap (usually smaller than the imageView). How can I get the top/left position of where the bitmap was drawn? I need to be able addView's on top a positions relative to the bitmap.

   RelativeLayout view = (RelativeLayout) inflater.inflate(R.layout.scroll_scaled, container, false);
ContentImageView image = (ContentImageView) view.findViewById(R.id.base_page);
Bitmap bm = mInterfaceActivity.getPageImage(mPageNumber);
image.setImageBitmap(bm);`

The layout file scrolled_scaled

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
    android:scaleType="centerInside"
    android:id="@+id/base_page"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ff00ff00"
    android:contentDescription="@string/product_page"
    android:src="@android:drawable/ic_menu_report_image" >
</ImageView>
</RelativeLayout>

Body:
This method returns the bounds of image inside imageView.

/**
 * Helper method to get the bounds of image inside the imageView.
 *
 * @param imageView the imageView.
 * @return bounding rectangle of the image.
 */
public static RectF getImageBounds(ImageView imageView) {
    RectF bounds = new RectF();
    Drawable drawable = imageView.getDrawable();
    if (drawable != null) {
        imageView.getImageMatrix().mapRect(bounds, new RectF(drawable.getBounds()));
    }
    return bounds;
}


问:
How to unit test a state machine in C using mocks of timers function?
I have a function that implements a state machine, test_hw(), i e. First state is idle, and it has not calling any mocked function inside. But this machine has 6 states more. The idea is that machine goes from first state to the last sequently, when certainly condition specially, timer result conditions, occures.
In the test I have only one mocked function that returns a time value. But this function must be called at every state as a part of condition to return the next state value. It also will be called inside of some states implementation.

First I tried to test every state as a test case. After run it, too much fails the test have found. I started to think that testing states machine will be a special testing case. I was following a TDD book but it doesn't talk about testing machine states.

The second thing I tried was testing all the test_hw machine as a only test case. But it failed again because test intercept more than 6 calls from source code and the test has only 6 (one call to this mocked function per state in test code). I don't understand why source code (production code) call it more than one time per state. But this is what happens. I guess due this is not the correct policy for unit testing a state machine.

I will share with you a reduced state machine based on mine one:

```<code> eError TestHW()
 {
   static unsigned char last_state = FMINUS_DONE; //IDLE state
   ......... //more needed var declaration

  if (FLAG_busy==OFF)
  {
      if (last_state==FMINUS_DONE)          /*IDLE */
      {
          ...... //some assignations
          timerfcentral=CaptureTimer(); //timer function to be mocked in test mode
          last_state= FCENTRAL_COUNT;

      }

     if ((CaptureTimer()-timerfcentral>=STABLISH_TIME) && (last_state==FCENTRAL_COUNT)) //timer function call to be mocked in test mode
     {    //next state
          last_state =FCENTRAL_DONE;
          ......//some assignments
     }
     else if (last_state ==FCENTRAL_DONE)
     {    //next state

          timerfplus=CaptureTimer(); //timer function to be mocked in test mode
          last_state= FPLUS_COUNT;
          .....//some assignments
     }
     else if ((last_state ==FPLUS_COUNT) && (CaptureTimer()-timerfminus>=STABLISH_TIME)) //timer function to be mocked in test mode
    {
          .....//some assignments
          last_state = FMINUS_DONE;
    }

   return last_state;

   }
   else     //FLAG_busy=1
     {
           last_state= FMINUS_DONE; //machine state loop is closed
           return last_state; /* busy system */
     }

}
</code>```

test code:

```<code> TEST(TestHW,TestHW_main)
 {

   unsigned char error_val;
   FLAG_busy =1;

   error_val=TestHW();
   CHECK_EQUAL(error_val,FMINUS_DONE);  //check busy state
   mock().enable();

   FLAG_busy =0;

   mock().expectOneCall("CaptureTimer").andReturnValue(1000);
   error_val=TestHW();
   CHECK_EQUAL(error_val,FCENTRAL_COUNT)    /*check state idle*/

   mock().expectOneCall("CapturaTimer").andReturnValue(15000);
   error_val=TestHW();
   CHECK_EQUAL(error_val,FCENTRAL_DONE);//check first state

   mock().expectOneCall("CaptureTimer").andReturnValue(15000);
   error_val=TestHW();
   CHECK_EQUAL(error_val,FPLUS_COUNT);//check second state

   mock().expectOneCall("CaptureTimer").andReturnValue(30000);
   error_val=TestHW();
   CHECK_EQUAL(error_val,FMINUS_DONE);//check last state

   mock().disable();

}
</code>```

mocked timer function implementation in Mock.c file:

```<code>unsigned long CaptureTimer(void)
{
     mock().actualCall("CaptureTimer");
     return mock().unsignedIntReturnValue();
}
</code>```

As I said before, this test fails due to "second not expected mocked call is produced".

What could be a correct strategy? --> if no test cases for every state, nor only one test entity, which one? Hence, is there any suggestion about the way of implementing a test code for the state machine shown above?

Could someone improve this test code?

答:
If I understand your code correctly, once FLAG_busy is not 1 anymore the CaptureTimer() function is called at least once and the remaining time twice. Just after your first test the state is at FMINUS_DONE which in the next cycle calls CaptureTimer() twice and that is why you have the error.

I believe you are using cpputest and I don't think you can have a mock called twice inside a single function call, someone can gladly correct me if I am wrong.

Body:
I have a function that implements a state machine, test_hw(), i e. First state is idle, and it has not calling any mocked function inside. But this machine has 6 states more. The idea is that machine goes from first state to the last sequently, when certainly condition specially, timer result conditions, occures.
In the test I have only one mocked function that returns a time value. But this function must be called at every state as a part of condition to return the next state value. It also will be called inside of some states implementation.

First I tried to test every state as a test case. After run it, too much fails the test have found. I started to think that testing states machine will be a special testing case. I was following a TDD book but it doesn't talk about testing machine states.

The second thing I tried was testing all the test_hw machine as a only test case. But it failed again because test intercept more than 6 calls from source code and the test has only 6 (one call to this mocked function per state in test code). I don't understand why source code (production code) call it more than one time per state. But this is what happens. I guess due this is not the correct policy for unit testing a state machine.

I will share with you a reduced state machine based on mine one:

 eError TestHW()
 {
   static unsigned char last_state = FMINUS_DONE; //IDLE state
   ......... //more needed var declaration

  if (FLAG_busy==OFF)
  {
      if (last_state==FMINUS_DONE)          /*IDLE */
      {
          ...... //some assignations
          timerfcentral=CaptureTimer(); //timer function to be mocked in test mode
          last_state= FCENTRAL_COUNT;

      }

     if ((CaptureTimer()-timerfcentral>=STABLISH_TIME) && (last_state==FCENTRAL_COUNT)) //timer function call to be mocked in test mode
     {    //next state
          last_state =FCENTRAL_DONE;
          ......//some assignments
     }
     else if (last_state ==FCENTRAL_DONE)
     {    //next state

          timerfplus=CaptureTimer(); //timer function to be mocked in test mode
          last_state= FPLUS_COUNT;
          .....//some assignments
     }
     else if ((last_state ==FPLUS_COUNT) && (CaptureTimer()-timerfminus>=STABLISH_TIME)) //timer function to be mocked in test mode
    {
          .....//some assignments
          last_state = FMINUS_DONE;
    }

   return last_state;

   }
   else     //FLAG_busy=1
     {
           last_state= FMINUS_DONE; //machine state loop is closed
           return last_state; /* busy system */
     }

}

test code:

 TEST(TestHW,TestHW_main)
 {

   unsigned char error_val;
   FLAG_busy =1;

   error_val=TestHW();
   CHECK_EQUAL(error_val,FMINUS_DONE);  //check busy state
   mock().enable();

   FLAG_busy =0;

   mock().expectOneCall("CaptureTimer").andReturnValue(1000);
   error_val=TestHW();
   CHECK_EQUAL(error_val,FCENTRAL_COUNT)    /*check state idle*/

   mock().expectOneCall("CapturaTimer").andReturnValue(15000);
   error_val=TestHW();
   CHECK_EQUAL(error_val,FCENTRAL_DONE);//check first state

   mock().expectOneCall("CaptureTimer").andReturnValue(15000);
   error_val=TestHW();
   CHECK_EQUAL(error_val,FPLUS_COUNT);//check second state

   mock().expectOneCall("CaptureTimer").andReturnValue(30000);
   error_val=TestHW();
   CHECK_EQUAL(error_val,FMINUS_DONE);//check last state

   mock().disable();

}

mocked timer function implementation in Mock.c file:

unsigned long CaptureTimer(void)
{
     mock().actualCall("CaptureTimer");
     return mock().unsignedIntReturnValue();
}

As I said before, this test fails due to "second not expected mocked call is produced".

What could be a correct strategy? --> if no test cases for every state, nor only one test entity, which one? Hence, is there any suggestion about the way of implementing a test code for the state machine shown above?

Could someone improve this test code?


问:
android TabItem onClick doesn't work
I have function cityClick,
if I call this function from a textView its working ok, but if I call cityClick from TabItem it doesn't work, what is going on?

Java

```<code>public class Kategorie extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {

protected void cityClick(View view) {
    Toast.makeText(this, "Hello", Toast.LENGTH_LONG).show();
}
</code>```

Layout

```<code>    <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:clickable="true"
        android:onClick="cityClick"
        app:tabMode="fixed">

        <android.support.design.widget.TabItem
            android:layout_height="wrap_content"
            android:layout_width="match_parent"
            android:textAlignment="center"
            android:textSize="18sp"
            android:onClick="cityClick"
            android:clickable="true"
            android:text="GDAŃSK" />

        <android.support.design.widget.TabItem
            android:layout_height="wrap_content"
            android:layout_width="match_parent"
            android:textAlignment="center"
            android:textSize="18sp"
            android:onClick="cityClick"
            android:clickable="true"
            android:text="SOPOT" />

        <android.support.design.widget.TabItem
            android:layout_height="wrap_content"
            android:layout_width="match_parent"
            android:textAlignment="center"
            android:textSize="18sp"
            android:onClick="cityClick"
            android:clickable="true"
            android:text="GDYNIA" />

    </android.support.design.widget.TabLayout>
</code>```

I was searching on this forum, but no found anything to help me.

答:
Try this,</p>

```<code>  tabs.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                Toast.makeText(mActivity, "hai", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
</code>```

Title: android TabItem onClick doesn't work

Body:
I have function cityClick,
if I call this function from a textView its working ok, but if I call cityClick from TabItem it doesn't work, what is going on?

Java

public class Kategorie extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {

protected void cityClick(View view) {
    Toast.makeText(this, "Hello", Toast.LENGTH_LONG).show();
}

Layout

    <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:clickable="true"
        android:onClick="cityClick"
        app:tabMode="fixed">

        <android.support.design.widget.TabItem
            android:layout_height="wrap_content"
            android:layout_width="match_parent"
            android:textAlignment="center"
            android:textSize="18sp"
            android:onClick="cityClick"
            android:clickable="true"
            android:text="GDAŃSK" />

        <android.support.design.widget.TabItem
            android:layout_height="wrap_content"
            android:layout_width="match_parent"
            android:textAlignment="center"
            android:textSize="18sp"
            android:onClick="cityClick"
            android:clickable="true"
            android:text="SOPOT" />

        <android.support.design.widget.TabItem
            android:layout_height="wrap_content"
            android:layout_width="match_parent"
            android:textAlignment="center"
            android:textSize="18sp"
            android:onClick="cityClick"
            android:clickable="true"
            android:text="GDYNIA" />

    </android.support.design.widget.TabLayout>

I was searching on this forum, but no found anything to help me.

Body:
Try this,

  tabs.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                Toast.makeText(mActivity, "hai", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });


问:
Crate DB Timestamp query
I have created a table in crate DB with timestamp column. However while inserting records into it, there is not timezone information passed along as mentioned in the docs.

```<code>insert into t1 values(2,'2017-06-30T02:21:20');
</code>```

this gets stored as:

```<code>2   | 1498789280000 (Fri, 30 Jun 2017 02:21:20 GMT)
</code>```

Now my queries are all failing as the timestamp has got recorded as GMT and my queries are all in localtime timezone (Asia/Kolkata)

If anyone has run into this problem, could you please let me know whats the best way to modify the column to change values from GMT to IST without losing it, It has couple of millions of important records which cannot be lost or corrupted.

cheers!

答:
CrateDB always assumes that timestamps are UTC when they are stored without timezone information. This is due to the internal representation as a simple long data type - which means that your timestamp is stored as a simple number: https://crate.io/docs/reference/en/latest/sql/data_types.html#timestamp
CrateDB also accepts the timezone information in your ISO string, so just inserting insert into t1 values(2,'2017-06-30T02:21:20+05:30'); will convert it to the appropriate UTC value.

For records that are already stored, you can make the DB aware of the timezone when querying for the field and convert the output back by passing the corresponding timezone value into a date_trunc or date_format function: https://crate.io/docs/reference/en/latest/sql/scalar.html#date-and-time-functions

Title: Crate DB Timestamp query

Body:
I have created a table in crate DB with timestamp column. However while inserting records into it, there is not timezone information passed along as mentioned in the docs.

insert into t1 values(2,'2017-06-30T02:21:20');

this gets stored as:

2   | 1498789280000 (Fri, 30 Jun 2017 02:21:20 GMT)

Now my queries are all failing as the timestamp has got recorded as GMT and my queries are all in localtime timezone (Asia/Kolkata)

If anyone has run into this problem, could you please let me know whats the best way to modify the column to change values from GMT to IST without losing it, It has couple of millions of important records which cannot be lost or corrupted.

cheers!


问:
FormRequest failed validation returns 500 error instead of 422 with errors (after 5.2 upgrade)
After updating from L5.1 to L5.2, I no longer receive a JSON object as response on a failed FormRequest (i.e. on an AJAX post request).

Usually I would receive a 422 response like:

```<code>[
    email: 'E-mail is invalid',
    firstname: 'Firstname must be at least 2 characters'
]
</code>```

But now I receive a 500 error page:

I have ensured that my AJAX calls have application/json as Accept header.

Update

And no,  I am not manually catching this exception. I am using the default FormRequest that Laravel provides. As they state in documentation: When using the validate method during an AJAX request, Laravel will not generate a redirect response. Instead, Laravel generates a JSON response containing all of the validation errors. This JSON response will be sent with a 422 HTTP status code.

Like so: php artisan make:request StoreBlogPostRequest (https://laravel.com/docs/5.1/validation#form-request-validation)

答:
@Mattias!

I've recently had the same issue and I wasted more than 2 hours trying to understand what actually causes this problem. Disabling debugging in .env file causes form validation to display 500 since the FormValidator throws ValidationException (and it is unhandled). The solution for this issue was:
Open app\Exceptions\Handler.php

```<code>private function handleExceptions($e)
    {
       // Add anywhere in this method the following code
       // It does what the FormValidator does.

        if($e instanceof ValidationException) {

            return redirect()->back()->withErrors($e->validator->getMessageBag()->toArray());
        }

        return response()->view('errors.500', [], 500);
    }
</code>```

Body:
After updating from L5.1 to L5.2, I no longer receive a JSON object as response on a failed FormRequest (i.e. on an AJAX post request).

Usually I would receive a 422 response like:

[
    email: 'E-mail is invalid',
    firstname: 'Firstname must be at least 2 characters'
]

But now I receive a 500 error page:

I have ensured that my AJAX calls have application/json as Accept header.

Update

And no,  I am not manually catching this exception. I am using the default FormRequest that Laravel provides. As they state in documentation: When using the validate method during an AJAX request, Laravel will not generate a redirect response. Instead, Laravel generates a JSON response containing all of the validation errors. This JSON response will be sent with a 422 HTTP status code.

Like so: php artisan make:request StoreBlogPostRequest (https://laravel.com/docs/5.1/validation#form-request-validation)

Body:
@Mattias!

I've recently had the same issue and I wasted more than 2 hours trying to understand what actually causes this problem. Disabling debugging in .env file causes form validation to display 500 since the FormValidator throws ValidationException (and it is unhandled). The solution for this issue was:
Open app\Exceptions\Handler.php

private function handleExceptions($e)
    {
       // Add anywhere in this method the following code
       // It does what the FormValidator does.

        if($e instanceof ValidationException) {

            return redirect()->back()->withErrors($e->validator->getMessageBag()->toArray());
        }

        return response()->view('errors.500', [], 500);
    }


问:
Change Dialog Window Width in Lightswitch HTML Client
In the MS Lightswitch HTML Client, when a dialog menu option has too many characters for the dialog window's length, the text is truncated and the missing characters replaced with (...).

Is there anyway to add a scroll bar or alter the text size when this occurs? I havent found a way to address this single element using JQuery either.

答:
On the screen.lsml, for example AddEditSite, you can change it on here, see screen shot below. This should format the text in terms of multi-line, so all the data can be seen

the next image shows the properties window which will let you add a label (this appears when the field is highlighted with a small blue line around it, such as Site Email in my example. Normally in your type of window you would set the label to top or left.

Please see the adjustment below for the details picker. If you set this to Row, within the details picker, and then within that group, click on your label, this will let you change it to a paragraph like shown above.

if you require additional information let me know.


问:
Why DataTable TableTools export to pdf or excel or csv button are not visible only print button is visible?
I have created the datatable with tabletools but I'm not able to view all the buttons like export to pdf or excel or copy or csv only print button is visible.

Here is my code:

```<code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.2/jquery.js"></script>
<script src="//cdn.datatables.net/1.10.7/js/jquery.dataTables.min.js"></script>
<script src="//cdn.datatables.net/tabletools/2.2.4/js/dataTables.tableTools.min.js"></script>

$(document).ready(function()
    {
        var table = $('#datatable').dataTable();
        var tableTools = new $.fn.dataTable.TableTools(table, {
            "aButtons" : [ "copy", "csv","copy", "pdf", "print" ],
            'sSwfPath': '//cdn.datatables.net/tabletools/2.2.4/swf/copy_csv_xls_pdf.swf'
        });
        $(tableTools.fnContainer()).insertBefore('#datatable_wrapper');
    });
</code>```

My output is ::

Here I need all the option for exporting.

plz help.

答:
I had the same problem with Chrome.

Enabling flash worked for me. Click on the "View site information" icon on the left hand side of the URL, then always allow flash for the specific site. Or go to chrome://settings/content/flash and disable "Ask first".

ContentLicense: CC BY-SA 4.0

Body:
I have created the datatable with tabletools but I'm not able to view all the buttons like export to pdf or excel or copy or csv only print button is visible.

Here is my code:

$(document).ready(function()
    {
        var table = $('#datatable').dataTable();
        var tableTools = new $.fn.dataTable.TableTools(table, {
            "aButtons" : [ "copy", "csv","copy", "pdf", "print" ],
            'sSwfPath': '//cdn.datatables.net/tabletools/2.2.4/swf/copy_csv_xls_pdf.swf'
        });
        $(tableTools.fnContainer()).insertBefore('#datatable_wrapper');
    });

My output is ::

Here I need all the option for exporting.

plz help.


问:
What is wrong with putting Using Blocks in Repository?
I have using blocks in each method of my repository. If I want to cross reference methods, it seems it would be against best practices to initialize another Datacontext  What am i doing wrong? If I declare a Datacontext in the class instead of using blocks in methods will I not lose power to dispose ??</p>

```<code>public IList<something> GetSomething()
{
   using (DB db=new DB())

   { ...GetListofSomethingElse(id)

   }
}

public IList<somethingelse> GetListofSomethingElse(int id)
{
    using (DB db=new DB())
   {
     ... return IList

   }
}
</code>```

答: You can call .Dispose() on a class without using a 'using' statement - usually you'll do this in the Dispose method of your repository, if you've got one.</p>

OwnerDisplayName: zsharp

Body:
I have using blocks in each method of my repository. If I want to cross reference methods, it seems it would be against best practices to initialize another Datacontext  What am i doing wrong? If I declare a Datacontext in the class instead of using blocks in methods will I not lose power to dispose ??

public IList<something> GetSomething()
{
   using (DB db=new DB())

   { ...GetListofSomethingElse(id)

   }
}

public IList<somethingelse> GetListofSomethingElse(int id)
{
    using (DB db=new DB())
   {
     ... return IList

   }
}

OwnerDisplayName: Erik


问:
Problem with too many try catch
Is it possible to write a method like outType? TryDo(func, out exception, params) that call func(arg1,arg2,arg3,...) which params contains arg1,arg2,arg3,... and then it return func return value and if any exception occurred return null and set the exception?

Can this be done better by another function signature?

for example I have
string Foo1(int i) { return i.ToString()}

void Foo2(int[] a) {throw new Exception();}

and then call

string t = TryDo(Foo1, out ex, {i});

TryDo(Foo2, out ex, {});

-----------Edited------------------

```<code>        string t;
        SomeClass c;
        try
        {
            t = Foo1(4, 2, new OtherClass());
        }
        catch (Exception ex)
        {
            Log(ex);
            if (/*ex has some features*/)
                throw ex;
        }

        try
        {
            Foo2();
        }
        catch (Exception ex)
        {
            Log(ex);
            if (/*ex has some features*/)
                throw ex;
        }
        .
        .
        .
</code>```

I want to make it like this.

```<code>        string t = TryDo(Foo1, out ex, {4, 2, new OtherClass());
        Examine(ex);
        SomeClass c = TryDo(Foo2, out ex, {});
        Examine(ex);
</code>```

答:
Yes it is, but why would you want that?</p>

```<code>int? TryDo(delegate d, out Exception e, params object[] par)
{
   try
   {
      int res = d.Invoke(par);
      e = null;
      return res;
   }
   catch(Exception ex) { e = ex; return null; }
}
</code>```

Title: Problem with too many try catch

Body:
Is it possible to write a method like outType? TryDo(func, out exception, params) that call func(arg1,arg2,arg3,...) which params contains arg1,arg2,arg3,... and then it return func return value and if any exception occurred return null and set the exception?

Can this be done better by another function signature?

for example I have
string Foo1(int i) { return i.ToString()}

void Foo2(int[] a) {throw new Exception();}

and then call

string t = TryDo(Foo1, out ex, {i});

TryDo(Foo2, out ex, {});

-----------Edited------------------

        string t;
        SomeClass c;
        try
        {
            t = Foo1(4, 2, new OtherClass());
        }
        catch (Exception ex)
        {
            Log(ex);
            if (/*ex has some features*/)
                throw ex;
        }

        try
        {
            Foo2();
        }
        catch (Exception ex)
        {
            Log(ex);
            if (/*ex has some features*/)
                throw ex;
        }
        .
        .
        .

I want to make it like this.

        string t = TryDo(Foo1, out ex, {4, 2, new OtherClass());
        Examine(ex);
        SomeClass c = TryDo(Foo2, out ex, {});
        Examine(ex);

Body:
Yes it is, but why would you want that?

int? TryDo(delegate d, out Exception e, params object[] par)
{
   try
   {
      int res = d.Invoke(par);
      e = null;
      return res;
   }
   catch(Exception ex) { e = ex; return null; }
}


问:
In Python, why is a tuple hashable but not a list?
Here below when I try to hash a list, it gives me an error but works with a tuple. Guess it has something to do with immutability. Can someone explain this in detail ?

List

```<code> x = [1,2,3]
 y = {x: 9}
  Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
 TypeError: unhashable type: 'list'
</code>```

Tuple

```<code>z = (5,6)
y = {z: 89}
print(y)
{(5, 6): 89}
</code>```

答:
Based on Python Glossary

An object is hashable if it has a hash value which never changes during its lifetime (it needs a __hash__() method), and can be compared to other objects (it needs an __eq__() method). Hashable objects which compare equal must have the same hash value.

All of Python’s immutable built-in objects are hashable; mutable containers (such as lists or dictionaries) are not.

Body:
Here below when I try to hash a list, it gives me an error but works with a tuple. Guess it has something to do with immutability. Can someone explain this in detail ?

List

 x = [1,2,3]
 y = {x: 9}
  Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
 TypeError: unhashable type: 'list'

Tuple

z = (5,6)
y = {z: 89}
print(y)
{(5, 6): 89}


问:
How to create mode_rewrite rule on Apache Server FreeBSD 8.1
I'm Working on a server running apache version 2.2.25 on FreeBSD 8.1.
Lets say I have the the following url: this.domain.com/html/folder/index.php
And I want to rewrite it as this: this.domain.com/index

How specifically would I create the rewrite rule? Should I create the rewrite rule in the httpd.conf file or the .htaccess file, or does it not really matter?
Also, is there a way to change the domain name "this.domain.com" to something else?

答:
Try this</p>

```<code>RewriteRule ^/index$ /html/folder/index.php [PT]
</code>```

Body:
Try this

RewriteRule ^/index$ /html/folder/index.php [PT]


问:
Oracle How to return a string in a particular format
I have one requirement where i want to return output in a particular format based on one column(Idx). In one column we have date range based on that loop should execute.

```<code>drop table t_table_test;
create table t_table_test ( ID NUMBER, NM VARCHAR2(4000), VAL VARCHAR2(4000), IDX NUMBER);
select * from t_table_test;
INSERT INTO t_table_test VALUES (1,'CNTRY', 'USA',1);
INSERT INTO t_table_test VALUES (1,'DT', '2017-01-01,2017-01-02',2);
INSERT INTO t_table_test VALUES (1,'PART', 'NA',3);
</code>```

If Input is below

```<code>ID NM            VAL                   IDX
1   CNTRY       USA                   1
1   DT        2017-01-01,2017-01-02   2
1   PART        NA                    3
</code>```

Output should be this will be based on IDX column

```<code>CNTRY:USA,DT:2017-01-01,PART:NA?CNTRY:USA,DT:2017-01-02,PART:NA
</code>```

I/P

```<code>ID NM       VAL                   IDX
1   DT        2017-01-01,2017-01-02 1
1   CNTRY       USA                   2
1   PART        NA                    3

 DT:2017-01-01,CNTRY:USA,PART:NA?DT:2017-01-02,CNTRY:USA,PART:NA
</code>```

DELETE FROM t_table_test WHERE idx=3;
commit;
O/P     DT:2017-01-01,CNTRY:USA?DT:2017-01-02,CNTRY:USA
DELETE FROM t_table_test WHERE idx=1;
commit;
O/P     DT:2017-01-01?DT:2017-01-02
Need query which work in all above cases .

答:
Perhaps you can try this:

```<code>select rtrim(XMLAGG(XMLELEMENT(E,val||'?')).EXTRACT('//text()'),',') from (
with dates as (SELECT distinct NM||':'||trim(regexp_substr(val, '[^,]+', 1, level)) val
from t_table_test where nm='DT' CONNECT BY instr(val, ',', 1, level - 1) > 0),
parts as (select NM||':'||VAL val FROM t_table_test where nm='PART')
SELECT NM||':'||t.VAL||','||d.VAL||','||p.val val from t_table_test t, dates d, parts p
where NM='CNTRY');
</code>```

It does rely on the names being fixed - having only DT being a comma separated list of values, for instance - but I think it might help you format your results. You can use this as a basis for building many similar formatting solutions.

Body:
I have one requirement where i want to return output in a particular format based on one column(Idx). In one column we have date range based on that loop should execute.

drop table t_table_test;
create table t_table_test ( ID NUMBER, NM VARCHAR2(4000), VAL VARCHAR2(4000), IDX NUMBER);
select * from t_table_test;
INSERT INTO t_table_test VALUES (1,'CNTRY', 'USA',1);
INSERT INTO t_table_test VALUES (1,'DT', '2017-01-01,2017-01-02',2);
INSERT INTO t_table_test VALUES (1,'PART', 'NA',3);

If Input is below

ID NM            VAL                   IDX
1   CNTRY       USA                   1
1   DT        2017-01-01,2017-01-02   2
1   PART        NA                    3

Output should be this will be based on IDX column

CNTRY:USA,DT:2017-01-01,PART:NA?CNTRY:USA,DT:2017-01-02,PART:NA

I/P

ID NM       VAL                   IDX
1   DT        2017-01-01,2017-01-02 1
1   CNTRY       USA                   2
1   PART        NA                    3

 DT:2017-01-01,CNTRY:USA,PART:NA?DT:2017-01-02,CNTRY:USA,PART:NA

DELETE FROM t_table_test WHERE idx=3;
commit;
O/P     DT:2017-01-01,CNTRY:USA?DT:2017-01-02,CNTRY:USA
DELETE FROM t_table_test WHERE idx=1;
commit;
O/P     DT:2017-01-01?DT:2017-01-02
Need query which work in all above cases .

Body:
Perhaps you can try this:

select rtrim(XMLAGG(XMLELEMENT(E,val||'?')).EXTRACT('//text()'),',') from (
with dates as (SELECT distinct NM||':'||trim(regexp_substr(val, '[^,]+', 1, level)) val
from t_table_test where nm='DT' CONNECT BY instr(val, ',', 1, level - 1) > 0),
parts as (select NM||':'||VAL val FROM t_table_test where nm='PART')
SELECT NM||':'||t.VAL||','||d.VAL||','||p.val val from t_table_test t, dates d, parts p
where NM='CNTRY');

It does rely on the names being fixed - having only DT being a comma separated list of values, for instance - but I think it might help you format your results. You can use this as a basis for building many similar formatting solutions.


问:
What common database is used with ASP?
I know PHP and how to use MySQL with it but now I am moving onto ASP but which common database is used with ASP (ie. the equivalent to MySQL)?</p>

答:
Usually it's Microsoft SQL Server.

If you want a free alternative you could try with Microsoft SQL Server Express, which is a scaled down version.

Here you can find more informations about the different versions.

Title: What common database is used with ASP?


问:
How to convert Java Swagger Annotation to Swagger json schema?
How to generate JSON file from java files containing Swagger specific annotations, so that Swagger-UI can read it.</p>

答:
As you say "I don't want to do it manually", use the Swagger Maven plugin:

```<code><plugin>
    <groupId>com.github.kongchen</groupId>
    <artifactId>swagger-maven-plugin</artifactId>
    <version>3.1.4</version>
    <configuration>
        <apiSources>
            <apiSource>
                <springmvc>true / false</springmvc>
                <locations>
                    <location>com.yourpackage.something</location>
                </locations>
                <host>yourhost.com</host>
                <basePath>/some/path</basePath>
                <info>
                    <title>Your Project Title</title>
                    <version>${project.version}</version>
                    <description>Some nice stuff</description>
                    <termsOfService>...</termsOfService>
                    <contact>
                        <email>someone@somewhere.com</email>
                        <name>Your Name</name>
                        <url>www.where.to.find.you</url>
                    </contact>
                </info>
                <swaggerDirectory>path/to/swagger/output</swaggerDirectory>
                <outputFormats>json</outputFormats>
            </apiSource>
        </apiSources>
    </configuration>
    <executions>
        <execution>
            <phase>compile</phase>
            <goals>
                <goal>generate</goal>
            </goals>
        </execution>
    </executions>
</plugin>
</code>```

Then you can do mvn compile and it will generate the swagger.json file.

Body:
As you say "I don't want to do it manually", use the Swagger Maven plugin:

<plugin>
    <groupId>com.github.kongchen</groupId>
    <artifactId>swagger-maven-plugin</artifactId>
    <version>3.1.4</version>
    <configuration>
        <apiSources>
            <apiSource>
                <springmvc>true / false</springmvc>
                <locations>
                    <location>com.yourpackage.something</location>
                </locations>
                <host>yourhost.com</host>
                <basePath>/some/path</basePath>
                <info>
                    <title>Your Project Title</title>
                    <version>${project.version}</version>
                    <description>Some nice stuff</description>
                    <termsOfService>...</termsOfService>
                    <contact>
                        <email>someone@somewhere.com</email>
                        <name>Your Name</name>
                        <url>www.where.to.find.you</url>
                    </contact>
                </info>
                <swaggerDirectory>path/to/swagger/output</swaggerDirectory>
                <outputFormats>json</outputFormats>
            </apiSource>
        </apiSources>
    </configuration>
    <executions>
        <execution>
            <phase>compile</phase>
            <goals>
                <goal>generate</goal>
            </goals>
        </execution>
    </executions>
</plugin>

Then you can do mvn compile and it will generate the swagger.json file.


问:
OnCheckedChanged not being fired on re-population of the form
I have a Gridview that has two buttons Edit & Delete.

On Edit, the row command calls a function called "Populate()" that populates a form located above the grid in a Panel (sets visible = true ).

Problem:

I have a checkbox "cbX", a textbox "txtX", and a dropdownlist "ddlX"(Visible = false)

if cbX is selected => ddlX.Visible = true and txtX.Enabled = false (I have an onCheckChangeed function)

When i chose to edit the entry, in the grid, that originally has cbX.Checked = true  I face a problem when the user attempts to uncheck the checkbox. No error is returned it simply does not call the onCheckChanged when I need it to hide the ddlX and Enable the txtX

```<code><asp:TextBox runat="server" ID="txtX" Width="180px"></asp:TextBox>

<asp:CheckBox runat="server" ID="cbX" AutoPostBack="true" Text="Unable to Obtain " OnCheckedChanged="cbX_CheckedChanged" />

<asp:DropDownList runat="server" ID="ddlX" DataTextField="Name" DataValueField="Code" AppendDataBoundItems="True" OnSelectedIndexChanged="ddlX_SelectedIndexChanged" Width="350px" AutoPostBack="true" CausesValidation="true" Enabled="false" Visible="false"></asp:DropDownList>
</code>```

答:
Figured it out.
I needed to manually add this:

```<code>cbX.CheckedChanged += new EventHandler(this.cbX_CheckedChanged);
</code>```

in the function that repopulates the form.

Body:
I have a Gridview that has two buttons Edit & Delete.

On Edit, the row command calls a function called "Populate()" that populates a form located above the grid in a Panel (sets visible = true ).

Problem:

I have a checkbox "cbX", a textbox "txtX", and a dropdownlist "ddlX"(Visible = false)

if cbX is selected => ddlX.Visible = true and txtX.Enabled = false (I have an onCheckChangeed function)

When i chose to edit the entry, in the grid, that originally has cbX.Checked = true  I face a problem when the user attempts to uncheck the checkbox. No error is returned it simply does not call the onCheckChanged when I need it to hide the ddlX and Enable the txtX

<asp:TextBox runat="server" ID="txtX" Width="180px"></asp:TextBox>

<asp:CheckBox runat="server" ID="cbX" AutoPostBack="true" Text="Unable to Obtain " OnCheckedChanged="cbX_CheckedChanged" />

<asp:DropDownList runat="server" ID="ddlX" DataTextField="Name" DataValueField="Code" AppendDataBoundItems="True" OnSelectedIndexChanged="ddlX_SelectedIndexChanged" Width="350px" AutoPostBack="true" CausesValidation="true" Enabled="false" Visible="false"></asp:DropDownList>

Body:
Figured it out.
I needed to manually add this:

cbX.CheckedChanged += new EventHandler(this.cbX_CheckedChanged);

in the function that repopulates the form.


问:
AWS Api Gateway + Lambda + custom domain (Route53) Missing Authentication Token issue
I am aware that many similar questions have been posted and answered here but none of them is quite the same with what I am experiencing.

I have a Lambda function that handles incoming requests (GET and POST). I also set up an api gateway as public facing endpoint. Additionally, I set up custom domain following Set up Custom Domain Name for API Host Name

The testing call works in both of lambda and api gateway console. Everything also works using the invoke URL but not with the custom domain I've set up.

Here are some more details:

Invoke URL (Works) :

```<code>https://{api gateway id}.execute-api.us-west-2.amazonaws.com/prod/endpoint
</code>```

Custom domain endpint (Doesn't work):

```<code>https://api.{my domain}.com/endpoint
</code>```

Base Path Mapping:

```<code>/endpoint   endpoint:prod
</code>```

All Method Auth:

```<code>Authorization None
API Key Not required
</code>```

Route53:

```<code>A record as alias that points api.{my domain}.com to the cloudfront distribution domain name as alias target.
</code>```

I'd really appreciate if anyone knows what's going out here.

答:
I found the issue is misunderstanding of how base path mapping works.

All my configurations are correct.

My API resource is not under / but under /endpoint

To use the custom domain, instead of visiting https://api.{my domain}.com/endpoint, it needs to go to https://api.{my domain}.com/endpoint/endpoint

Of course this is silly and redundant.

I have two options. I either set up the base path mapping to / instead of /endpoint or I can just user the API resource / instead of /endpoint.

I go with the latter because if base path mapping is set to /, my api.{my domain}.com will only be able to host just one API (I can still use resources under the same API, but why wasting the extra layer of abstraction?).

This seems dump but I am still glad I figured it out.

Body:
I am aware that many similar questions have been posted and answered here but none of them is quite the same with what I am experiencing.

I have a Lambda function that handles incoming requests (GET and POST). I also set up an api gateway as public facing endpoint. Additionally, I set up custom domain following Set up Custom Domain Name for API Host Name

The testing call works in both of lambda and api gateway console. Everything also works using the invoke URL but not with the custom domain I've set up.

Here are some more details:

Invoke URL (Works) :

https://{api gateway id}.execute-api.us-west-2.amazonaws.com/prod/endpoint

Custom domain endpint (Doesn't work):

https://api.{my domain}.com/endpoint

Base Path Mapping:

/endpoint   endpoint:prod

All Method Auth:

Authorization None
API Key Not required

Route53:

A record as alias that points api.{my domain}.com to the cloudfront distribution domain name as alias target.

I'd really appreciate if anyone knows what's going out here.


问:
Return data from different database and output in form
I have an app in PHP/ SQL Server connected to database A. In a form, i want to populate a dropdown list with data from database B (same server).

What i made:

In config.php file i typed:

```<code>try {
$handler = new PDO("sqlsrv:Server=server1;Database=attstocuri;ConnectionPooling=0", "sa", "");
$handler -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (Exception $ex) {
echo $ex->getMessage();
die();
}
</code>```

and

```<code>try {
$handler2 = new PDO("sqlsrv:Server=server1;Database=Legend;ConnectionPooling=0", "sa", "");
$handler2 -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (Exception $ex) {
echo $ex->getMessage();
die();
}
</code>```

In index.php file (where is located the form):

```<code><form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<select name="customerid">

<?php
$stmt2 = $handler2 -> query ('SELECT customer.id, customer.name from Legend.dbo.Customer');
while ($row = $stmt2 ->fetch()){
echo "<option value='".$row["customer.id"]."'>".$row["customer.name"]."</option>";
}
?>
</select>
<input type="text" class="form-control" name="productcode" placeholder="Cod articol" value="<?php if(isset($error)){ echo $_POST['productcode'];} ?>"></input><br/>
<input type="number" class="form-control" name="quantity" placeholder="Cantitate fara stoc" value="<?php if(isset($error)){ echo $_POST['quantity'];} ?>"></input><br/>
<input type="submit" name="submit" class="btn btn-primary">
</form>
</code>```

The select should return the info from the second database, but it's not showing anything ... what am i doing wrong ?

Thank you.

答:
Hi I'm no PHP dev but you can potentially resolve this from a DB perspective. If both databases are in the same SQL server instance then simply create a view in the App DB refrencing the drop down options you want to use and use this the same in your app as any other table or view.

In attstocuri run

```<code>CREATE VIEW MyDropDown AS
SELECT
customer.id
, customer.name
FROM Legend.dbo.Customer
GO
</code>```

Then you can reference it from the same connection. You will need to ensure the permissions for the user the app connects to attstocuri with have permission on the Customer table in Legend though.

If the databases were not on the same server or the other database was not SQL server then you could still use this method after setting up a linked server.

Body:
I have an app in PHP/ SQL Server connected to database A. In a form, i want to populate a dropdown list with data from database B (same server).

What i made:

In config.php file i typed:

try {
$handler = new PDO("sqlsrv:Server=server1;Database=attstocuri;ConnectionPooling=0", "sa", "");
$handler -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (Exception $ex) {
echo $ex->getMessage();
die();
}

and

try {
$handler2 = new PDO("sqlsrv:Server=server1;Database=Legend;ConnectionPooling=0", "sa", "");
$handler2 -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (Exception $ex) {
echo $ex->getMessage();
die();
}

In index.php file (where is located the form):

<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<select name="customerid">

<?php
$stmt2 = $handler2 -> query ('SELECT customer.id, customer.name from Legend.dbo.Customer');
while ($row = $stmt2 ->fetch()){
echo "<option value='".$row["customer.id"]."'>".$row["customer.name"]."</option>";
}
?>
</select>
<input type="text" class="form-control" name="productcode" placeholder="Cod articol" value="<?php if(isset($error)){ echo $_POST['productcode'];} ?>"></input>

<input type="number" class="form-control" name="quantity" placeholder="Cantitate fara stoc" value="<?php if(isset($error)){ echo $_POST['quantity'];} ?>"></input>

<input type="submit" name="submit" class="btn btn-primary">
</form>

The select should return the info from the second database, but it's not showing anything ... what am i doing wrong ?

Thank you.

Body:
Hi I'm no PHP dev but you can potentially resolve this from a DB perspective. If both databases are in the same SQL server instance then simply create a view in the App DB refrencing the drop down options you want to use and use this the same in your app as any other table or view.

In attstocuri run

CREATE VIEW MyDropDown AS
SELECT
customer.id
, customer.name
FROM Legend.dbo.Customer
GO

Then you can reference it from the same connection. You will need to ensure the permissions for the user the app connects to attstocuri with have permission on the Customer table in Legend though.

If the databases were not on the same server or the other database was not SQL server then you could still use this method after setting up a linked server.


问:
Can't load cast_framework.js on Chrome Sender
So a couple of month back I wrote a test sender to get some experience with Cast senders. It worked fine and I could send images and videos to my Chromecasts.

I now need to create a custom receiver and I wanted to use my old sender to test my receiver code. However, my sender doesn't work anymore eventhough I didn't change anything since then.

The errors i'm now getting in Chrome's console are the following:

GET file://www.gstatic.com/cast/sdk/libs/sender/1.0/cast_framework.js net::ERR_FILE_NOT_FOUND

Uncaught ReferenceError: cast is not defined

at window.__onGCastApiAvailable (script.js:84)

at chrome.cast.cb (cast_sender.js:99)

When I look at the "Network" tab I can see that the cast_framework.js file failed to load after 22s.

I then tried to use the sample on Google's Github to see if it was my sender that was at fault but I get the same error.

I also can reach the devices with the Cast button in Chrome's menu.

What is going on with that file? Is it my browser that has a problem? Is it my devices?

答:
So the problem was the following:

As you can see the browser was looking for the file with file://. This happens because I launched my HTML file locally so the url in the browser was file:///home/.../index.html and I guess when it loads the framework file it guesses that it has to use file:// too instead of html://.

Someone told me that I should serve the file from a server so I made a brief Node server with express.static to serve the file and it then worked again when I loaded the page via localhost:4000.

I still don't know how it worked a couple of month ago but I guess I was just lucky in some way.


问:
C# - Google Drive API not redirecting
I have chosen Installed Application as project in Google Console. After making Windows Form project, i am trying to authenticate user which i successfully did it but only for once. It did not redirected me to Google authentication site for the second time.

Please help me. Am i making any mistake in code?

答:
The Google .net client library uses fileDatastore to store your credentials for "user"  you are sending Enviorment.Username.  So it knows its the same user and will not request your authentication again.   Your code is working correctly.

Credentials are being stored in your %appData% directory

I have a full article on how filedatastore works here if you are interested in learning more about it Google .net – FileDatastore demystified

Title: C# - Google Drive API not redirecting


问:
Is there a way to run EF Core RC2 tools from published DLL?
After publishing a .Net Core RC1 application, commands specified in the project.json had corresponding .cmd files created for them which could be executed after deployment (e.g. web.cmd and ef.cmd). In my case, I want to run the following Entity Framework command on my deployment target:

```<code>dotnet ef database update -c MyContext
</code>```

This works fine when I run this from the folder containing the source code, however after publishing, it doesn't appear to find the command within the compiled DLLs. My understanding of the change in commands with RC2 is that 'tools' can be compiled as standalone applications named dotnet-*.dll and can be executed via the CLI. How can the Entity Framework Core tools be exposed as executable DLLs in the published output?

FYI, my build/deployment workflow is as follows:

TeamCity

dotnet restore => dotnet build => dotnet test => dotnet publish

Octopus Deploy

Upload Package => EF Update Database => etc

答:
There is an extremely useful post with a solution to this problem here.

It worked for me (I had to tweak the commands a little bit, but it gave me a good basis to start).

In sum:  you can replicate the dotnet ef database update command by passing the ef.dll (e.g. directly from your nuget folder (or from somewhere else if you don’t have nuget, since you are on a prod machine..)) with your .dll containing the migrations with some additional parameters (see below) to dotnet.exe (or the linux equivalent).

For completeness here is the .cmd (also from the blogpost!)

```<code>set EfMigrationsNamespace=%1
set EfMigrationsDllName=%1.dll
set EfMigrationsDllDepsJson=%1.deps.json
set DllDir=%cd%
set PathToNuGetPackages=%USERPROFILE%\.nuget\packages
set PathToEfDll=%PathToNuGetPackages%\microsoft.entityframeworkcore.tools.dotnet\1.0.0\tools\netcoreapp1.0\ef.dll

dotnet exec --depsfile .\%EfMigrationsDllDepsJson% --additionalprobingpath %PathToNuGetPackages% %PathToEfDll% database update --assembly .\%EfMigrationsDllName% --startup-assembly .\%EfMigrationsDllName% --project-dir . --content-root %DllDir% --data-dir %DllDir% --verbose --root-namespace %EfMigrationsNamespace%
</code>```

(A bash version if this cmd is in the blogpost)

Btw. this approach was also mentioned in many github issues: https://github.com/aspnet/EntityFramework.Docs/issues/328
https://github.com/aspnet/EntityFramework.Docs/issues/180

ps: I found this in the blog of Ben Day, so all credit goes to Ben!

Body:
After publishing a .Net Core RC1 application, commands specified in the project.json had corresponding .cmd files created for them which could be executed after deployment (e.g. web.cmd and ef.cmd). In my case, I want to run the following Entity Framework command on my deployment target:

dotnet ef database update -c MyContext

This works fine when I run this from the folder containing the source code, however after publishing, it doesn't appear to find the command within the compiled DLLs. My understanding of the change in commands with RC2 is that 'tools' can be compiled as standalone applications named dotnet-*.dll and can be executed via the CLI. How can the Entity Framework Core tools be exposed as executable DLLs in the published output?

FYI, my build/deployment workflow is as follows:

TeamCity

dotnet restore => dotnet build => dotnet test => dotnet publish

Octopus Deploy

Upload Package => EF Update Database => etc

Body:
There is an extremely useful post with a solution to this problem here.

It worked for me (I had to tweak the commands a little bit, but it gave me a good basis to start).

In sum:  you can replicate the dotnet ef database update command by passing the ef.dll (e.g. directly from your nuget folder (or from somewhere else if you don’t have nuget, since you are on a prod machine..)) with your .dll containing the migrations with some additional parameters (see below) to dotnet.exe (or the linux equivalent).

For completeness here is the .cmd (also from the blogpost!)

set EfMigrationsNamespace=%1
set EfMigrationsDllName=%1.dll
set EfMigrationsDllDepsJson=%1.deps.json
set DllDir=%cd%
set PathToNuGetPackages=%USERPROFILE%\.nuget\packages
set PathToEfDll=%PathToNuGetPackages%\microsoft.entityframeworkcore.tools.dotnet\1.0.0\tools\netcoreapp1.0\ef.dll

dotnet exec --depsfile .\%EfMigrationsDllDepsJson% --additionalprobingpath %PathToNuGetPackages% %PathToEfDll% database update --assembly .\%EfMigrationsDllName% --startup-assembly .\%EfMigrationsDllName% --project-dir . --content-root %DllDir% --data-dir %DllDir% --verbose --root-namespace %EfMigrationsNamespace%

(A bash version if this cmd is in the blogpost)

Btw. this approach was also mentioned in many github issues: https://github.com/aspnet/EntityFramework.Docs/issues/328
https://github.com/aspnet/EntityFramework.Docs/issues/180

ps: I found this in the blog of Ben Day, so all credit goes to Ben!


答:
Microsoft SQL Server.

This is commonly known as WISA (Windows, IIS, SQL Server, ASP) stack.

Title: What common database is used with ASP?

Body: I know PHP and how to use MySQL with it but now I am moving onto ASP but which common database is used with ASP (ie. the equivalent to MySQL)?


问:
Adding list items to observable collection list
Hi I am trying to add list items to an observable collection list.
I have a model where I setup a list property

```<code>public class DisplayList
{
   public List<string> listItem { get; set; }
}
</code>```

then on my main page I have an observable collection

```<code> private ObservableCollection<DisplayList> ListDisplay;
</code>```

which I instantiate on page load

```<code> public MainPage()
    {

        this.InitializeComponent();

        location = new ObservableCollection<storeLocations>();
        ListDisplay = new ObservableCollection<DisplayList>();
        // location = manager.getStoreLocations();
        var dbList = db.Bales.Where(b => b.Location != null).Select(b => b.Location).ToList();
        InitialLoad(dbList, null);

    }
</code>```

I am using suggestion boxes and want to filter results based on the selection made. The filtered results then display in a list on screen and this is where I am having a bit of trouble. I get it to display on screen, but it is displaying
System.Collection.Generic.List'1[S....... instead of the actual item in the list.

I am thinking I am not enumerating properly, but cant seem to pin point the error in my ways.

This is the method that is meant to populate the list based on selection of suggestion box.

```<code> public ObservableCollection<DisplayList>BaleList(List<string> CatNo)
    {

        foreach (var item in CatNo)
        {

            ListDisplay.Add(new DisplayList {listItem = CatNo.ToList()});
        }

        lstBales.IsItemClickEnabled = true;

        return ListDisplay;
    }
</code>```

it takes in a parameter of type list which is gotten from the suggestion box. so the parameter value is basically what I want to display in the list on screen. e.g. CP1354-2 and second item CP1355-3 So those values come into the method. I want to apply those values to the observable collection as the listbox control is bound to the observable collection.

EDIT
adding binding in XAML

```<code>  <ListView x:Name="lstBales" ItemsSource="{x:Bind ListDisplay}">
                        <ListView.ItemTemplate>
                            <DataTemplate  x:Name="TemplateListName" x:DataType="data:DisplayList">
                                <Grid>
                                    <TextBlock Text="{x:Bind listItem}"/>
                                </Grid>

                            </DataTemplate>
                        </ListView.ItemTemplate>
                    </ListView>
</code>```

答:
```<code>ListDisplay.Add(new DisplayList {listItem = CatNo.ToList()});
</code>```

and  <TextBlock Text="{x:Bind listItem}"/>

You are binding a list to a TextBlock due to which ToString()is implicitly called and you don't get the actual values. According to your requirements, you can either change listItem to a string or create a nested ListView

Body:
Hi I am trying to add list items to an observable collection list.
I have a model where I setup a list property

public class DisplayList
{
   public List<string> listItem { get; set; }
}

then on my main page I have an observable collection

 private ObservableCollection<DisplayList> ListDisplay;

which I instantiate on page load

 public MainPage()
    {

        this.InitializeComponent();

        location = new ObservableCollection<storeLocations>();
        ListDisplay = new ObservableCollection<DisplayList>();
        // location = manager.getStoreLocations();
        var dbList = db.Bales.Where(b => b.Location != null).Select(b => b.Location).ToList();
        InitialLoad(dbList, null);

    }

I am using suggestion boxes and want to filter results based on the selection made. The filtered results then display in a list on screen and this is where I am having a bit of trouble. I get it to display on screen, but it is displaying
System.Collection.Generic.List'1[S....... instead of the actual item in the list.

I am thinking I am not enumerating properly, but cant seem to pin point the error in my ways.

This is the method that is meant to populate the list based on selection of suggestion box.

 public ObservableCollection<DisplayList>BaleList(List<string> CatNo)
    {

        foreach (var item in CatNo)
        {

            ListDisplay.Add(new DisplayList {listItem = CatNo.ToList()});
        }

        lstBales.IsItemClickEnabled = true;

        return ListDisplay;
    }

it takes in a parameter of type list which is gotten from the suggestion box. so the parameter value is basically what I want to display in the list on screen. e.g. CP1354-2 and second item CP1355-3 So those values come into the method. I want to apply those values to the observable collection as the listbox control is bound to the observable collection.

EDIT
adding binding in XAML

  <ListView x:Name="lstBales" ItemsSource="{x:Bind ListDisplay}">
                        <ListView.ItemTemplate>
                            <DataTemplate  x:Name="TemplateListName" x:DataType="data:DisplayList">
                                <Grid>
                                    <TextBlock Text="{x:Bind listItem}"/>
                                </Grid>

                            </DataTemplate>
                        </ListView.ItemTemplate>
                    </ListView>

Body:
ListDisplay.Add(new DisplayList {listItem = CatNo.ToList()});

and  <TextBlock Text="{x:Bind listItem}"/>

You are binding a list to a TextBlock due to which ToString()is implicitly called and you don't get the actual values. According to your requirements, you can either change listItem to a string or create a nested ListView


问:
Change wpf element after event callback
I'm reading the weight on a scale connected over a serial port. When the weight changed the scale returns an event. This event is working great but I can't change the value of a WPF element in the event handler (tried both labels and textboxes) with the new weight.

The event handler is inside the correct window class.

When I call a messagebox to display the weight all is fine.

Can anyone explain to me how to change the wpf elements after the event callback. This is my callback function.

```<code>public void OnWeightUpdate(string weight) {
    if(String.IsNullOrEmpty(weight)) {
        MessageBox.Show("Empty weight string, possible bad connection with scale");
    }
    else {
        MessageBox.Show(weight);
        LblScaleAmount.Content = weight;
    }
}
</code>```

答:
Since you receive weight information from serial port - there is a high chance that your callback runs on background (non-UI thread). You cannot update interface controls from background thread, so you need to dispatch update operation back to UI thread:</p>

```<code>Dispatcher.Invoke(() => LblScaleAmount.Content = weight);
</code>```

Title: Change wpf element after event callback

Body:
I'm reading the weight on a scale connected over a serial port. When the weight changed the scale returns an event. This event is working great but I can't change the value of a WPF element in the event handler (tried both labels and textboxes) with the new weight.

The event handler is inside the correct window class.

When I call a messagebox to display the weight all is fine.

Can anyone explain to me how to change the wpf elements after the event callback. This is my callback function.

public void OnWeightUpdate(string weight) {
    if(String.IsNullOrEmpty(weight)) {
        MessageBox.Show("Empty weight string, possible bad connection with scale");
    }
    else {
        MessageBox.Show(weight);
        LblScaleAmount.Content = weight;
    }
}

Body:
Since you receive weight information from serial port - there is a high chance that your callback runs on background (non-UI thread). You cannot update interface controls from background thread, so you need to dispatch update operation back to UI thread:

Dispatcher.Invoke(() => LblScaleAmount.Content = weight);


问:
WPF Why button's background is blinking after press?
I created a UserControl, and added a Button inside it removing the Background and Text properties:

```<code><Button x:Name="Button"
        HorizontalAlignment="Center"
        Height="40"
        VerticalAlignment="Center"
        Width="40"
        RenderTransformOrigin="0,-2"
        Margin="0,0,0,0"
        BorderBrush="{x:Null}"
        Click="Button_Click"
        Background="{x:Null}"/>
</code>```

I also hadled the Button Click event as below:

```<code>private void Button_Click(object sender, RoutedEventArgs e)
{
    Button.Content = new cross();
}
</code>```

The above code fills the Button content with another UserControl which is a simple cross pic.

I have placed the UserControl with the Button into a MainWindow app and after pressing Button, it starts blinking - background is fluently changing between two colours. Beside my functionality from code works good. I just don't know how to get rid of that blinking background.

Before click:

After click:

答:
You could set Focusable="False" at your Button to achive this.

But you should read about the Focusableproperty in the MSDN to check if it's ok for you. I guess you can't focus the Buttonusing the tab key anymore. But maybe that's not a problem for you.

Body:
I created a UserControl, and added a Button inside it removing the Background and Text properties:

<Button x:Name="Button"
        HorizontalAlignment="Center"
        Height="40"
        VerticalAlignment="Center"
        Width="40"
        RenderTransformOrigin="0,-2"
        Margin="0,0,0,0"
        BorderBrush="{x:Null}"
        Click="Button_Click"
        Background="{x:Null}"/>

I also hadled the Button Click event as below:

private void Button_Click(object sender, RoutedEventArgs e)
{
    Button.Content = new cross();
}

The above code fills the Button content with another UserControl which is a simple cross pic.

I have placed the UserControl with the Button into a MainWindow app and after pressing Button, it starts blinking - background is fluently changing between two colours. Beside my functionality from code works good. I just don't know how to get rid of that blinking background.

Before click:

After click:


问:
How to move data from H2 Database(InMemory DB) to actual Database over JDBC Adapter?
I am using H2 database as a inmemory database for my java webapplication and I want to push the data into the actual database in background over JDBC.

One solution i found over is to use ThreadPoolExecutor and scheduling some threads. Is this the best option or do we have any alternate solutions?

Any Help is appreciated.Thanks

答:
have a look at Talend Data Integration Free Tool. It allows you to

transfer Data from one source to another

crate a jar which you can include in your project

With the included JAR you can call there the create Job which will transfer the Data from your in Memory DB to the source DB.


问:
How do I select an element with special characters in the ID?
I have a page with a grid containing a lot if input with "strange names" to simulate an array:

```<code> <input type="text" id="Punteggi[@counter].Descrizione" readonly="readonly" tabindex="-1" name="Punteggi[@counter].Descrizione" class="{validate: {required:true}}" value="@item.Descrizione" />
</code>```

How can I set the value of these inputs with jQuery, specifically, how would I select them? I tried in a lot of ways but nothing works.

答:
You need to escape the [, ], @ and . characters in the id selector. To do that, use \\ like this:

var val = $('#Punteggi\\[\\@counter\\]\\.Descrizione').val();

console.log(val);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="Punteggi[@counter].Descrizione" readonly="readonly" tabindex="-1" name="Punteggi[@counter].Descrizione" class="{validate: {required:true}}" value="@item.Descrizione" /></code>```

Body:
I have a page with a grid containing a lot if input with "strange names" to simulate an array:

 <input type="text" id="Punteggi[@counter].Descrizione" readonly="readonly" tabindex="-1" name="Punteggi[@counter].Descrizione" class="{validate: {required:true}}" value="@item.Descrizione" />

How can I set the value of these inputs with jQuery, specifically, how would I select them? I tried in a lot of ways but nothing works.

Body:
You need to escape the [, ], @ and . characters in the id selector. To do that, use \\ like this:

var val = $('#Punteggi\\[\\@counter\\]\\.Descrizione').val();

console.log(val);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="Punteggi[@counter].Descrizione" readonly="readonly" tabindex="-1" name="Punteggi[@counter].Descrizione" class="{validate: {required:true}}" value="@item.Descrizione" />


问:
Access AJAX method through JavaScript code
Here is my sendMessage function:

```<code>sendMessage:function(message)
       {
        var that = this;
        $.ajax({
              url: '/ajax/add_msg.php',
              method:'post',
              data: {msg: message},
       success: function(data) {
              $('#myTextArea').val('');
              that.getMessages();
                            }
             });
       }
</code>```

I am trying to call this page but it doesn't work.

```<code>   <?php
     alert("reached to the add_messages");
     session_start();
  if (isset($_POST['msg']))
     {
         require_once __DIR__ . '/../../core/FbChatMock.php';
         $userId = (int) $_SESSION['user_id'];
         // Escape the message string
         $msg = htmlentities($_POST['msg'],  ENT_NOQUOTES);
         $chat = new FbChatMock();
         $result = $chat->addMessage($userId, $msg);
      }
   ?>
</code>```

The path is correct.

答:
As you said you receive 404 (Not found) for POST localhost:8080/ajax/add_msg.php

You should check is your folder ajax located at the very begin of www directory or it has some folders to get to ajax. And then is your filename -> add_msg.php correct, or you missed something.

After that from PHP remove the line with alert("..."); it will cause 500 Internal Error, because PHP has no alert function except you were created the same, but as no includes to any php file before i guess you didn't created it...

And for outputing in PHP you can use echo "I came to add_msg.php!";

Best regards & happy coding..

Body:
Here is my sendMessage function:

sendMessage:function(message)
       {
        var that = this;
        $.ajax({
              url: '/ajax/add_msg.php',
              method:'post',
              data: {msg: message},
       success: function(data) {
              $('#myTextArea').val('');
              that.getMessages();
                            }
             });
       }

I am trying to call this page but it doesn't work.

   <?php
     alert("reached to the add_messages");
     session_start();
  if (isset($_POST['msg']))
     {
         require_once __DIR__ . '/../../core/FbChatMock.php';
         $userId = (int) $_SESSION['user_id'];
         // Escape the message string
         $msg = htmlentities($_POST['msg'],  ENT_NOQUOTES);
         $chat = new FbChatMock();
         $result = $chat->addMessage($userId, $msg);
      }
   ?>

The path is correct.


问:
Select from multiple tables with same condition, avoid ambiguity error
How can I do something like this but avoid the error column common_reference is ambiguous? I know it's ambiguous, I want to select from table_one all the results for common_reference there, and table_two the same.

SELECT * FROM table_one, table_two WHERE common_reference = 42

This is obviously not going to work, so how do I use subqueries to achieve what I need?

答:
Start with...

```<code>SELECT * FROM table_one, table_two WHERE table_one.common_reference = 42
</code>```

...and continue this road:

```<code>SELECT * FROM table_one as T1, table_two as T2 WHERE T1.common_reference = 42
</code>```

Body:
Start with...

SELECT * FROM table_one, table_two WHERE table_one.common_reference = 42

...and continue this road:

SELECT * FROM table_one as T1, table_two as T2 WHERE T1.common_reference = 42


问:
Android Studio using a horizontally scrolling recycler view to display 5 items at a time
I have a horizontally scrolling recycler view that is displaying one row at a time very well. I want to know if it is possible to have the recycler view display five rows in a vertical list format, and then still have it scroll horizontally. Or should I just use paging? </p>

答: Use GridLayoutManager for multiple Rows. LinearLayoutManager layouts all the items in a single row.</p>


问:
archive for required library can not be read
I created my first maven project and I get Java build path problem in it.

```<code>Description Resource    Path    Location    Type
Archive for required library: 'C:/Users/simran/.m2/repository/org/glassfish/extras/glassfish-embedded-web/3.1.1/glassfish-embedded-web-3.1.1.jar' in project 'RestfulMessenger' cannot be read or is not a valid ZIP file   RestfulMessenger        Build path  Build Path Problem
</code>```

This jar is present in the location mentioned, I tried deleteing it from there , cleaning the project and updating the maven but nothing fixed the error.

What seems wrong?

答: Deleting the corresponding .jar files from local repository and reissuing the maven command did the trick. It seems the .jar files got corrupted while downloading.</p>

Body:
I created my first maven project and I get Java build path problem in it.

Description Resource    Path    Location    Type
Archive for required library: 'C:/Users/simran/.m2/repository/org/glassfish/extras/glassfish-embedded-web/3.1.1/glassfish-embedded-web-3.1.1.jar' in project 'RestfulMessenger' cannot be read or is not a valid ZIP file   RestfulMessenger        Build path  Build Path Problem

This jar is present in the location mentioned, I tried deleteing it from there , cleaning the project and updating the maven but nothing fixed the error.

What seems wrong?


问:
Handling items on RecyclerView OnClick Method
I am trying to make a biography app  which includes cardviews. I can not achieve that when I click on each item on RecyclerView, second activity which contains of detail info must be opened. Here is my code.
Where am I doing wrong? Thank you so much...</p>

```<code>public class SimpleRecyclerAdapter extends RecyclerView.Adapter<SimpleRecyclerAdapter.ViewHolder>{

    private static final String TAG = "debug";
    private Context mContext;
    List<Person> list = new ArrayList<>();

    public SimpleRecyclerAdapter(Context mContext, List<Person>list){
    this.list=list;
    }

    public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

        public TextView person_name;
        public TextView person_year;
        public ImageView person_img;
        public CardView card_view;

        public ViewHolder(final View view) {
        super(view);

            card_view = (CardView) view.findViewById(R.id.card_view);
            person_name = (TextView) view.findViewById(R.id.person_name);
            person_year = (TextView) view.findViewById(R.id.person_year);
            person_img = (ImageView) view.findViewById(R.id.person_photo);

            view.setOnClickListener(this);

            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Toast.makeText(v.getContext(), "inside viewholder position = " + getAdapterPosition(), Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(v.getContext(), DetailActivity.class);

                    v.getContext().startActivity(intent);
                }
            });

        }

        @Override
        public void onClick(View v) {

        }

    } // Closing inner class: Viewholder

    @Override
    public SimpleRecyclerAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        // create a new view
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_view_layout, parent, false);
        // create ViewHolder
        ViewHolder view_holder = new ViewHolder(v);
        return view_holder;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {

        holder.person_name.setText(list.get(position).getName());
        holder.person_year.setText(list.get(position).getYear());
        holder.person_img.setImageResource(list.get(position).getPhoto_id());
    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    @Override
    public void onAttachedToRecyclerView(RecyclerView recyclerView) {
        super.onAttachedToRecyclerView(recyclerView);
    }
} // Closing outer class: SimpleRecyclerAdapter
</code>```

答:
Remove this from ViewHolder class :

```<code>view.setOnClickListener(this);

        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(v.getContext(), "inside viewholder position = " + getAdapterPosition(), Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(v.getContext(), DetailActivity.class);

                v.getContext().startActivity(intent);
            }
        });

    }

    @Override
    public void onClick(View v) {

    }
</code>```

And in onBindViewHolder(ViewHolder holder, int position) do like this :

```<code>        holder.card_view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Toast.makeText(mContext, "inside viewholder position = " + position, Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(mContext,DetailActivity.class);
                    mContext.startActivity(intent);
                }
            });
</code>```

Body:
I am trying to make a biography app  which includes cardviews. I can not achieve that when I click on each item on RecyclerView, second activity which contains of detail info must be opened. Here is my code.
Where am I doing wrong? Thank you so much...

public class SimpleRecyclerAdapter extends RecyclerView.Adapter<SimpleRecyclerAdapter.ViewHolder>{

    private static final String TAG = "debug";
    private Context mContext;
    List<Person> list = new ArrayList<>();

    public SimpleRecyclerAdapter(Context mContext, List<Person>list){
    this.list=list;
    }

    public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

        public TextView person_name;
        public TextView person_year;
        public ImageView person_img;
        public CardView card_view;

        public ViewHolder(final View view) {
        super(view);

            card_view = (CardView) view.findViewById(R.id.card_view);
            person_name = (TextView) view.findViewById(R.id.person_name);
            person_year = (TextView) view.findViewById(R.id.person_year);
            person_img = (ImageView) view.findViewById(R.id.person_photo);

            view.setOnClickListener(this);

            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Toast.makeText(v.getContext(), "inside viewholder position = " + getAdapterPosition(), Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(v.getContext(), DetailActivity.class);

                    v.getContext().startActivity(intent);
                }
            });

        }

        @Override
        public void onClick(View v) {

        }

    } // Closing inner class: Viewholder

    @Override
    public SimpleRecyclerAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        // create a new view
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_view_layout, parent, false);
        // create ViewHolder
        ViewHolder view_holder = new ViewHolder(v);
        return view_holder;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {

        holder.person_name.setText(list.get(position).getName());
        holder.person_year.setText(list.get(position).getYear());
        holder.person_img.setImageResource(list.get(position).getPhoto_id());
    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    @Override
    public void onAttachedToRecyclerView(RecyclerView recyclerView) {
        super.onAttachedToRecyclerView(recyclerView);
    }
} // Closing outer class: SimpleRecyclerAdapter

Body:
Remove this from ViewHolder class :

view.setOnClickListener(this);

        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(v.getContext(), "inside viewholder position = " + getAdapterPosition(), Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(v.getContext(), DetailActivity.class);

                v.getContext().startActivity(intent);
            }
        });

    }

    @Override
    public void onClick(View v) {

    }

And in onBindViewHolder(ViewHolder holder, int position) do like this :

        holder.card_view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Toast.makeText(mContext, "inside viewholder position = " + position, Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(mContext,DetailActivity.class);
                    mContext.startActivity(intent);
                }
            });