问:
How to change Azure Git CI deployment default python version
Azure only supports Python version 2.7 and 3.4 in the Application settings, and I installed newer Python 3.6.2 via App Service for my django application. I followed the setup for continuous integration with Azure & GitHub and found out that deployment failed when Azure is running deployment command. Below is part of the log that shows Azure decided to use default 2.7 even tho I specified to use 3.6.2 in web.config file

```<code>Detected requirements.txt.  You can skip Python specific steps with a .skipPythonDeployment file.
Detecting Python runtime from site configuration
Detected python-2.7
Creating python-2.7 virtual environment.
...
#(and it just continue and install the requirements.txt with pip using python-2.7 which failed)
</code>```

Azure will determine the version of Python to use for its virtual
  environment with the following priority:

version specified in runtime.txt in the root folder

version specified by Python setting in the web app configuration
  (the Settings > Application Settings blade for your web app in the
  Azure Portal)

python-2.7 is the default if none of the above are specified

I can't specify the version using runtime.txt since 3.6.2 is not a valid value for the content. It looks like Azure ignored my web.config and just jump to use 2.7 as the default since none of the above are specified.

As of now, I had to go in Kudu console and manually deploy my app using 3.6.2. How can I set it to use 3.6.2 as the default when deploying my code from Github?

Below is my web.config file

```<code><?xml version="1.0" encoding="utf-8"?>
<configuration>
  <appSettings>
    <add key="PYTHONPATH" value="D:\home\site\wwwroot"/>
    <!-- Django apps only: change the project name to match your app -->
    <add key="WSGI_HANDLER" value="django.core.wsgi.get_wsgi_application()"/>
    <add key="DJANGO_SETTINGS_MODULE" value="mysite.settings" />
    <add key="WSGI_LOG" value="D:\home\LogFiles\wfastcgi.log"/>
  </appSettings>
  <system.webServer>
    <handlers>
      <add name="PythonHandler" path="*" verb="*" modules="FastCgiModule"
           scriptProcessor="D:\home\python362x86\python.exe|D:\home\python362x86\wfastcgi.py"
           resourceType="Unspecified" requireAccess="Script"/>
    </handlers>
  </system.webServer>
</configuration>
</code>```

答:
Per my experience , if you're using python Extensions in the Azure Python web app , you do not have to choose Python versions in the application settings.

Please refer to the steps I did as below:

Step 1 : Create azure web app and add Extensions(here is Python 3.6.2 x86)

Step 2 : Prepare your django project and add the web.config.

web.config:

```<code><configuration>
  <appSettings>
    <add key="WSGI_HANDLER" value="django.core.wsgi.get_wsgi_application()"/>
    <add key="PYTHONPATH" value="D:\home\site\wwwroot"/>
    <add key="WSGI_LOG" value="D:\home\LogFiles\wfastcgi.log"/>
    <add key="DJANGO_SETTINGS_MODULE" value="<your project name>.settings" />
  </appSettings>
  <system.webServer>
    <handlers>
      <add name="PythonHandler" path="handler.fcgi" verb="*" modules="FastCgiModule" scriptProcessor="D:\home\python362x86\python.exe|D:\home\python362x86\wfastcgi.py" resourceType="Unspecified" requireAccess="Script"/>
    </handlers>
    <rewrite>
      <rules>
        <rule name="Static Files" stopProcessing="true">
          <conditions>
            <add input="true" pattern="false" />
          </conditions>
        </rule>
        <rule name="Configure Python" stopProcessing="true">
          <match url="(.*)" ignoreCase="false" />
          <conditions>
            <add input="{REQUEST_URI}" pattern="^/static/.*" ignoreCase="true" negate="true" />
          </conditions>
          <action type="Rewrite" url="handler.fcgi/{R:1}" appendQueryString="true" />
        </rule>
      </rules>
    </rewrite>
  </system.webServer>
</configuration>
</code>```

Step 3 : Add your site URL domain to ALLOWED_HOSTS in settings.py in your django project

```<code>ALLOWED_HOSTS = ['***.azurewebsites.net']
</code>```

Step 4 : Publish your django project via FTP or Git.

Step 5: Switch to the Kudu CMD and commands cd Python362x86 and touch get-pip.py and copy the content of the url https://bootstrap.pypa.io/get-pip.py into the get-pip.py via Edit button, then run python get-pip.py to install the pip tool.

Step 6 : Install django package or any packages you need via python -m pip install ***

Then access your domain url successfully.

You could also refer to the official tutorial.

Hope it helps you.

Update Answer:

According to  the screenshots and logs you provide, I see that the Python is 2.7 version is detected by the application in runtime .

I check the environment variable on KUDU and find the Python 2.7 version.

I recommend that you overwrite the Python version in environment variable with the version of the extensions Python version you used.

Please try again.

Body:
Azure only supports Python version 2.7 and 3.4 in the Application settings, and I installed newer Python 3.6.2 via App Service for my django application. I followed the setup for continuous integration with Azure & GitHub and found out that deployment failed when Azure is running deployment command. Below is part of the log that shows Azure decided to use default 2.7 even tho I specified to use 3.6.2 in web.config file

Detected requirements.txt.  You can skip Python specific steps with a .skipPythonDeployment file.
Detecting Python runtime from site configuration
Detected python-2.7
Creating python-2.7 virtual environment.
...
#(and it just continue and install the requirements.txt with pip using python-2.7 which failed)

Azure will determine the version of Python to use for its virtual
  environment with the following priority:

version specified in runtime.txt in the root folder

version specified by Python setting in the web app configuration
  (the Settings > Application Settings blade for your web app in the
  Azure Portal)

python-2.7 is the default if none of the above are specified

I can't specify the version using runtime.txt since 3.6.2 is not a valid value for the content. It looks like Azure ignored my web.config and just jump to use 2.7 as the default since none of the above are specified.

As of now, I had to go in Kudu console and manually deploy my app using 3.6.2. How can I set it to use 3.6.2 as the default when deploying my code from Github?

Below is my web.config file

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <appSettings>
    <add key="PYTHONPATH" value="D:\home\site\wwwroot"/>

    <add key="WSGI_HANDLER" value="django.core.wsgi.get_wsgi_application()"/>
    <add key="DJANGO_SETTINGS_MODULE" value="mysite.settings" />
    <add key="WSGI_LOG" value="D:\home\LogFiles\wfastcgi.log"/>
  </appSettings>
  <system.webServer>
    <handlers>
      <add name="PythonHandler" path="*" verb="*" modules="FastCgiModule"
           scriptProcessor="D:\home\python362x86\python.exe|D:\home\python362x86\wfastcgi.py"
           resourceType="Unspecified" requireAccess="Script"/>
    </handlers>
  </system.webServer>
</configuration>

Body:
Per my experience , if you're using python Extensions in the Azure Python web app , you do not have to choose Python versions in the application settings.

Please refer to the steps I did as below:

Step 1 : Create azure web app and add Extensions(here is Python 3.6.2 x86)

Step 2 : Prepare your django project and add the web.config.

web.config:

<configuration>
  <appSettings>
    <add key="WSGI_HANDLER" value="django.core.wsgi.get_wsgi_application()"/>
    <add key="PYTHONPATH" value="D:\home\site\wwwroot"/>
    <add key="WSGI_LOG" value="D:\home\LogFiles\wfastcgi.log"/>
    <add key="DJANGO_SETTINGS_MODULE" value="<your project name>.settings" />
  </appSettings>
  <system.webServer>
    <handlers>
      <add name="PythonHandler" path="handler.fcgi" verb="*" modules="FastCgiModule" scriptProcessor="D:\home\python362x86\python.exe|D:\home\python362x86\wfastcgi.py" resourceType="Unspecified" requireAccess="Script"/>
    </handlers>
    <rewrite>
      <rules>
        <rule name="Static Files" stopProcessing="true">
          <conditions>
            <add input="true" pattern="false" />
          </conditions>
        </rule>
        <rule name="Configure Python" stopProcessing="true">
          <match url="(.*)" ignoreCase="false" />
          <conditions>
            <add input="{REQUEST_URI}" pattern="^/static/.*" ignoreCase="true" negate="true" />
          </conditions>
          <action type="Rewrite" url="handler.fcgi/{R:1}" appendQueryString="true" />
        </rule>
      </rules>
    </rewrite>
  </system.webServer>
</configuration>

Step 3 : Add your site URL domain to ALLOWED_HOSTS in settings.py in your django project

ALLOWED_HOSTS = ['***.azurewebsites.net']

Step 4 : Publish your django project via FTP or Git.

Step 5: Switch to the Kudu CMD and commands cd Python362x86 and touch get-pip.py and copy the content of the url https://bootstrap.pypa.io/get-pip.py into the get-pip.py via Edit button, then run python get-pip.py to install the pip tool.

Step 6 : Install django package or any packages you need via python -m pip install ***

Then access your domain url successfully.

You could also refer to the official tutorial.

Hope it helps you.

Update Answer:

According to  the screenshots and logs you provide, I see that the Python is 2.7 version is detected by the application in runtime .

I check the environment variable on KUDU and find the Python 2.7 version.

I recommend that you overwrite the Python version in environment variable with the version of the extensions Python version you used.

Please try again.


来源: stackexchange

问:
jQuery: resetting .animated divs position
I am using the following code to expand and center on div on :hover

```<code>    $(document).ready(function(){

    //animation on hover

        $('#sliding_grid li').hover(function() {
          $(this).addClass('highlight');
        }, function() {
          //$(this).removeClass('highlight');
        });

        $(".highlight").live("hover", function(){
            $(this).animate({"width": "454px", "height":"282px", "top: ":"94px", "left":"152px", "margin-top: ":"-94px", "margin-left":"-152px"}, 500);

        });

        $(".highlight").live("mouseout", function(){
            $(this).animate({"width": "148px", "height":"90px", "top: ":"0px", "left":"0px", "margin-top: ":"0", "margin-left":"0"}, 500, function(){
             $(this).removeClass('highlight');
            });

        });

    });
</code>```

My problem is two things:

1) I'm not sure how to reset the "top" and "left" css coordinates to their original value on mouseOut.  To see a working demo, go here:

http://jsfiddle.net/kTFvj/1/

2) The z-index (see here: http://jsfiddle.net/kTFvj/1/) is not affecting the :hovered grid elements.  Not sure why.

答:
as Martin said, store the values when the animation begins using a variable, and restore when done.

about z-Index: just have a variable called maxZIndex=0
and everytime an animation begins, set the object's zIndex property to maxZIndex++

ContentLicense: CC BY-SA 2.5

Body:
I am using the following code to expand and center on div on :hover

    $(document).ready(function(){

    //animation on hover

        $('#sliding_grid li').hover(function() {
          $(this).addClass('highlight');
        }, function() {
          //$(this).removeClass('highlight');
        });

        $(".highlight").live("hover", function(){
            $(this).animate({"width": "454px", "height":"282px", "top: ":"94px", "left":"152px", "margin-top: ":"-94px", "margin-left":"-152px"}, 500);

        });

        $(".highlight").live("mouseout", function(){
            $(this).animate({"width": "148px", "height":"90px", "top: ":"0px", "left":"0px", "margin-top: ":"0", "margin-left":"0"}, 500, function(){
             $(this).removeClass('highlight');
            });

        });

    });

My problem is two things:

1) I'm not sure how to reset the "top" and "left" css coordinates to their original value on mouseOut.  To see a working demo, go here:

http://jsfiddle.net/kTFvj/1/

2) The z-index (see here: http://jsfiddle.net/kTFvj/1/) is not affecting the :hovered grid elements.  Not sure why.


问:
Promise fulfilled inspite of rejection
I am using bluebird settle method to check results for promises regardless of any rejections. In the secondMethod  I have rejected the promise still I get    isFulfilled() true.

```<code>var Promise = require('bluebird');

Promise.settle([firstMethod, secondMethod]).then(function(results){
    console.log(results[0].isFulfilled());
    console.log(results[1].isFulfilled());
   // console.log(results[1].reason());
}).catch(function(error){
    console.log(error);
});

    var firstMethod = function() {
   var promise = new Promise(function(resolve, reject){
      setTimeout(function() {
         resolve({data: '123'});
      }, 2000);
   });
   return promise;
};

var secondMethod = function() {
   var promise = new Promise(function(resolve, reject){
      setTimeout(function() {
         reject((new Error('fail')));
      }, 2000);
   });
   return promise;
};
</code>```

答:
settle API is been deprecated. Refer the github link and this for info. Use reflect API instead as pointed in the documentation.

Secondly, documentation points out with an example:

Using .reflect() to implement settleAll (wait until all promises in an array are either rejected or fulfilled) functionality

```<code>var promises = [getPromise(), getPromise(), getPromise()];
Promise.all(promises.map(function(promise) {
    return promise.reflect();
})).each(function(inspection) {
    if (inspection.isFulfilled()) {
        console.log("A promise in the array was fulfilled with", inspection.value());
    } else {
        console.error("A promise in the array was rejected with", inspection.reason());
    }
});
</code>```

Explanation of above code:

In the above example author is iterating through array of promises using map which returns reflect and inspecting each promise is isRejected or isFulfilled.

ContentLicense: CC BY-SA 3.0

Title: Promise fulfilled inspite of rejection

Body:
I am using bluebird settle method to check results for promises regardless of any rejections. In the secondMethod  I have rejected the promise still I get    isFulfilled() true.

var Promise = require('bluebird');

Promise.settle([firstMethod, secondMethod]).then(function(results){
    console.log(results[0].isFulfilled());
    console.log(results[1].isFulfilled());
   // console.log(results[1].reason());
}).catch(function(error){
    console.log(error);
});

    var firstMethod = function() {
   var promise = new Promise(function(resolve, reject){
      setTimeout(function() {
         resolve({data: '123'});
      }, 2000);
   });
   return promise;
};

var secondMethod = function() {
   var promise = new Promise(function(resolve, reject){
      setTimeout(function() {
         reject((new Error('fail')));
      }, 2000);
   });
   return promise;
};

Body:
settle API is been deprecated. Refer the github link and this for info. Use reflect API instead as pointed in the documentation.

Secondly, documentation points out with an example:

Using .reflect() to implement settleAll (wait until all promises in an array are either rejected or fulfilled) functionality

var promises = [getPromise(), getPromise(), getPromise()];
Promise.all(promises.map(function(promise) {
    return promise.reflect();
})).each(function(inspection) {
    if (inspection.isFulfilled()) {
        console.log("A promise in the array was fulfilled with", inspection.value());
    } else {
        console.error("A promise in the array was rejected with", inspection.reason());
    }
});

Explanation of above code:

In the above example author is iterating through array of promises using map which returns reflect and inspecting each promise is isRejected or isFulfilled.


问:
Converting a result of Integer to String or Word in C
so i have a problem here. I am working on my class assignment which is create a calculator but every result must be in a word, example :

```<code>int a,b,c;
printf("Input first number:");
scanf("%d", &a);
printf("Input second number:"):
scanf("%d", &b);
c=a+b;
printf("The result are: %d", c);
printf("If in words, it is  = ");
switch(c){
case 0:printf("abcdef");break;
case 1:printf("bc");break;
case 2:printf("abged");break;
case 3:printf("abgcd");break;
case 4:printf("fbgc");break;
case 5:printf("afgod");break;
case 6:printf("fgcde");break;
case 7:printf("abc");break;
case 8:printf("abcdefg");break;
case 9:printf("abcdfg");break;
default :printf("error");break;
</code>```

So the result from this when im running it is :

Input first number : 12

input second number : 12

The result are: 24

If in words, it is = error

so what I'm confused here is how I did print the c result as a word? so what i want from my output is

Input first number : 12

input second number : 12

The result are : 24

If in words, it is = abged fbcg

so far I'm searching for answers but I cannot find it. If anyone here can help me, please do.

Thanks in advance

*edited

答:
what i want from my output is

```<code>Input first number : 12

input second number : 12

The result are : 24

If in words, it is = abged fbcg
</code>```

The question would be much clearer if you had written "two four" instead of "abged fbcg"...

You apparently want to print the "tens" and the "ones" separately. (Probably the  "hundreds" as well.)

As this is a homework assignment, I will only give you some hints instead of a complete solution:

If you divide c by 10, you get the "tens". If you divide that result by 10 again, you get the "hundreds".

If something like "two four" would be acceptable, you can use the same lookup for "tens" and "ones". If you actually need "twenty four", you need a lookup for "tens" and a different one for "ones".

You need to print the words for the highest-order (leftmost) digit first, but you get it last from the by-10 divisions I mentioned above. So you need to "store" the lookup result for "ones" somewhere while you do the lookup for "tens" (and, perhaps, "hundreds"). Storage could be...

...an array. Be careful to check the numbers entered against the space in the array (so you don't overflow if someone enters too-large numbers). If you do it right, you do not need to store the strings you looked up, as you could store pointers to those strings.

...a recursive function. (One that calls itself with the value divided by 10, then does the lookup for the "ones" of the value it was called with -- you get that via the modulo operator, c % 10.)

Body:
so i have a problem here. I am working on my class assignment which is create a calculator but every result must be in a word, example :

int a,b,c;
printf("Input first number:");
scanf("%d", &a);
printf("Input second number:"):
scanf("%d", &b);
c=a+b;
printf("The result are: %d", c);
printf("If in words, it is  = ");
switch(c){
case 0:printf("abcdef");break;
case 1:printf("bc");break;
case 2:printf("abged");break;
case 3:printf("abgcd");break;
case 4:printf("fbgc");break;
case 5:printf("afgod");break;
case 6:printf("fgcde");break;
case 7:printf("abc");break;
case 8:printf("abcdefg");break;
case 9:printf("abcdfg");break;
default :printf("error");break;

So the result from this when im running it is :

Input first number : 12

input second number : 12

The result are: 24

If in words, it is = error

so what I'm confused here is how I did print the c result as a word? so what i want from my output is

Input first number : 12

input second number : 12

The result are : 24

If in words, it is = abged fbcg

so far I'm searching for answers but I cannot find it. If anyone here can help me, please do.

Thanks in advance

*edited

Body:
what i want from my output is

Input first number : 12

input second number : 12

The result are : 24

If in words, it is = abged fbcg

The question would be much clearer if you had written "two four" instead of "abged fbcg"...

You apparently want to print the "tens" and the "ones" separately. (Probably the  "hundreds" as well.)

As this is a homework assignment, I will only give you some hints instead of a complete solution:

If you divide c by 10, you get the "tens". If you divide that result by 10 again, you get the "hundreds".

If something like "two four" would be acceptable, you can use the same lookup for "tens" and "ones". If you actually need "twenty four", you need a lookup for "tens" and a different one for "ones".

You need to print the words for the highest-order (leftmost) digit first, but you get it last from the by-10 divisions I mentioned above. So you need to "store" the lookup result for "ones" somewhere while you do the lookup for "tens" (and, perhaps, "hundreds"). Storage could be...

...an array. Be careful to check the numbers entered against the space in the array (so you don't overflow if someone enters too-large numbers). If you do it right, you do not need to store the strings you looked up, as you could store pointers to those strings.

...a recursive function. (One that calls itself with the value divided by 10, then does the lookup for the "ones" of the value it was called with -- you get that via the modulo operator, c % 10.)


问:
C# - SetupDiGetDeviceInterfaceDetail will get the strange String
Recently, I want to use C# to get the HID device. But I meet some trouble.

When I use SetupDiGetDeviceInterfaceDetail() function, I will get the wrong path.

My code of get path function as below.

```<code>private string GetDevicePath(IntPtr hDeviceInfo, ref SP_DEVICE_INTERFACE_DATA devInterfaceData)
    {
        uint nRequiredSize = 0;
        //basically, the first device detailed will return the false... it the really thing.
        if (!SetupDiGetDeviceInterfaceDetail(hDeviceInfo, ref devInterfaceData, IntPtr.Zero, (uint)0, ref nRequiredSize, IntPtr.Zero))
        {

            ///Declare Sample 3:
            SP_DEVICE_INTERFACE_DETAIL_DATA oDevInterfaceDetailedData = new SP_DEVICE_INTERFACE_DETAIL_DATA();
            //Create Buffer to save the path detailed.
            oDevInterfaceDetailedData.cbSize = 5; //=5

            ///With Sample 3:
            if (SetupDiGetDeviceInterfaceDetail(hDeviceInfo, ref devInterfaceData,ref oDevInterfaceDetailedData, nRequiredSize, ref nRequiredSize, IntPtr.Zero))
            {
                //FIXME: Problem 1: The CreateFile will return 123. its means The filename, directory name, or volume label syntax is incorrect.
                //https://msdn.microsoft.com/en-us/library/windows/desktop/ms681382(v=vs.85).aspx

                ///With Sample 3:
                Log.Text += ("Acutal Path = "+ oDevInterfaceDetailedData.DevicePath + "\n");
                return oDevInterfaceDetailedData.DevicePath;
            }
        }
        return null;
    }
</code>```

The question is here: oDevInterfaceDetailedData.DevicePath

The string variable will shows the message as below.

```<code>Acutal Path = 屜尿楨⍤楶彤㌰て瀦摩ㅟ㐰⌱☶㐱㡡㈶搷〦〦〰⌰㑻㕥戵ⴲㅦ昶ㄭ挱ⵦ㠸扣〭㄰ㄱ〱〰㌰細
</code>```

My declare of function/structure as below

```<code>    [DllImport("setupapi.dll", SetLastError = true)]
    protected static extern bool SetupDiGetDeviceInterfaceDetail(IntPtr lpDeviceInfoSet, ref SP_DEVICE_INTERFACE_DATA oInterfaceData, ref SP_DEVICE_INTERFACE_DETAIL_DATA lpDeviceInterfaceDetailData, uint nDeviceInterfaceDetailDataSize, ref uint nRequiredSize, IntPtr lpDeviceInfoData);

    [DllImport("setupapi.dll", SetLastError = true)]
    protected static extern bool SetupDiGetDeviceInterfaceDetail(IntPtr lpDeviceInfoSet, ref SP_DEVICE_INTERFACE_DATA oInterfaceData, IntPtr lpDeviceInterfaceDetailData, uint nDeviceInterfaceDetailDataSize, ref uint nRequiredSize, IntPtr lpDeviceInfoData);[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]

    public struct SP_DEVICE_INTERFACE_DETAIL_DATA
    {
        public uint cbSize;
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
        public string DevicePath;
    }
</code>```

My platform is 64 bits Windows OS.
I use the VS2017 IDE to build a WPF project in C#.

Does someone could help me to figure out the question is..... Thanks a lot

答:
You try with codes:

[DllImport(@"setupapi.dll", CharSet = CharSet.Auto, SetLastError = true)]

public static extern Boolean SetupDiGetDeviceInterfaceDetail(
    IntPtr hDevInfo,
    ref SP_DEVICE_INTERFACE_DATA deviceInterfaceData,
    IntPtr deviceInterfaceDetailData,
    UInt32 deviceInterfaceDetailDataSize,
    out UInt32 requiredSize,
    IntPtr deviceInfoData
    );

Reference for those interested.  here

And here

Body:
Recently, I want to use C# to get the HID device. But I meet some trouble.

When I use SetupDiGetDeviceInterfaceDetail() function, I will get the wrong path.

My code of get path function as below.

private string GetDevicePath(IntPtr hDeviceInfo, ref SP_DEVICE_INTERFACE_DATA devInterfaceData)
    {
        uint nRequiredSize = 0;
        //basically, the first device detailed will return the false... it the really thing.
        if (!SetupDiGetDeviceInterfaceDetail(hDeviceInfo, ref devInterfaceData, IntPtr.Zero, (uint)0, ref nRequiredSize, IntPtr.Zero))
        {

            ///Declare Sample 3:
            SP_DEVICE_INTERFACE_DETAIL_DATA oDevInterfaceDetailedData = new SP_DEVICE_INTERFACE_DETAIL_DATA();
            //Create Buffer to save the path detailed.
            oDevInterfaceDetailedData.cbSize = 5; //=5

            ///With Sample 3:
            if (SetupDiGetDeviceInterfaceDetail(hDeviceInfo, ref devInterfaceData,ref oDevInterfaceDetailedData, nRequiredSize, ref nRequiredSize, IntPtr.Zero))
            {
                //FIXME: Problem 1: The CreateFile will return 123. its means The filename, directory name, or volume label syntax is incorrect.
                //https://msdn.microsoft.com/en-us/library/windows/desktop/ms681382(v=vs.85).aspx

                ///With Sample 3:
                Log.Text += ("Acutal Path = "+ oDevInterfaceDetailedData.DevicePath + "\n");
                return oDevInterfaceDetailedData.DevicePath;
            }
        }
        return null;
    }

The question is here: oDevInterfaceDetailedData.DevicePath

The string variable will shows the message as below.

Acutal Path = 屜尿楨⍤楶彤㌰て瀦摩ㅟ㐰⌱☶㐱㡡㈶搷〦〦〰⌰㑻㕥戵ⴲㅦ昶ㄭ挱ⵦ㠸扣〭㄰ㄱ〱〰㌰細

My declare of function/structure as below

    [DllImport("setupapi.dll", SetLastError = true)]
    protected static extern bool SetupDiGetDeviceInterfaceDetail(IntPtr lpDeviceInfoSet, ref SP_DEVICE_INTERFACE_DATA oInterfaceData, ref SP_DEVICE_INTERFACE_DETAIL_DATA lpDeviceInterfaceDetailData, uint nDeviceInterfaceDetailDataSize, ref uint nRequiredSize, IntPtr lpDeviceInfoData);

    [DllImport("setupapi.dll", SetLastError = true)]
    protected static extern bool SetupDiGetDeviceInterfaceDetail(IntPtr lpDeviceInfoSet, ref SP_DEVICE_INTERFACE_DATA oInterfaceData, IntPtr lpDeviceInterfaceDetailData, uint nDeviceInterfaceDetailDataSize, ref uint nRequiredSize, IntPtr lpDeviceInfoData);[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]

    public struct SP_DEVICE_INTERFACE_DETAIL_DATA
    {
        public uint cbSize;
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
        public string DevicePath;
    }

My platform is 64 bits Windows OS.
I use the VS2017 IDE to build a WPF project in C#.

Does someone could help me to figure out the question is..... Thanks a lot


问:
How to have a dropdown searchbox that filters table results?
I am still new to programming and currently I encounter a problem. I have used a code from W3schools which allows me to filters the table when it matches the search result. However, I want to make it better for the users of the website. I want to allow them to be able to search through the searchbox and also give them the option to select a dropdown from the box which returns the same result.

Below is the code I have used for HTML:

```<code><input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names.."><table id="myTable">
<tr class="header">
    <th style="width:60%;">Fruit Name</th>
    <th style="width:40%;">Place of Origin</th>
</tr>
<tr>
    <td>Apple</td>
    <td>Asia</td>
</tr>
<tr>
    <td>Black Berry</td>
    <td>North America</td>
</tr>
<tr>
    <td>Durian</td>
    <td>SouthEast Asia</td>
</tr>
<tr>
    <td>Watermelon</td>
    <td>South Korea</td>
</tr></table>
</code>```

And the JavaScript used:

```<code><script>
    function myFunction() {
        var input, filter, table, tr, td, i;
        input = document.getElementById("myInput");
        filter = input.value.toUpperCase();
        table = document.getElementById("myTable");
        tr = table.getElementsByTagName("tr");
        // Loop through all table rows, and hide those who don't match the search query
        for (i = 0; i < tr.length; i++) {
            td = tr[i].getElementsByTagName("td")[0];
            if (td) {
                if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
                    tr[i].style.display = "";
                } else {
                    tr[i].style.display = "none";
                }
            }
        }
    }
</script>
</code>```

I'm sorry for this mess, in short, these were taken from the W3school site with some changes. Instead of having just a search box, I want to implement a drop down with the search box if it is possible. Any help would be greatly appreciated.

答:
Try this :

HTML

```<code>    <input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names..">
    <select id="selectItems">
        <option>NA</option>
    </select>
<table id="myTable">

    <tr class="header">
        <th style="width:60%;">Fruit Name</th>
        <th style="width:40%;">Place of Origin</th>
    </tr>
    <tr>
        <td>Apple</td>
        <td>Asia</td>
    </tr>
    <tr>
        <td>Black Berry</td>
        <td>North America</td>
    </tr>
    <tr>
        <td>Durian</td>
        <td>SouthEast Asia</td>
    </tr>
    <tr>
        <td>Watermelon</td>
        <td>South Korea</td>
    </tr></table>
</code>```

Javascript:

```<code>function init()
{
 //insert item in dropdown from table.

 var html_for_elect = '';
 var itm_dd = document.getElementById("selectItems");

 table1 = document.getElementById("myTable");
 trtbl = table1.getElementsByTagName("tr");

 for (i = 0; i < trtbl.length; i++) {
            td = trtbl[i].getElementsByTagName("td")[0];
            if (td) {
                html_for_elect = html_for_elect + "<option>"+td.innerHTML+"</option>";

            }
        }
itm_dd.innerHTML = html_for_elect;
}
init();
    function myFunction() {
        var input, filter, table, tr, td, i;
        input = document.getElementById("myInput");
        filter = input.value.toUpperCase();
        table = document.getElementById("myTable");
        tr = table.getElementsByTagName("tr");
        // Loop through all table rows, and hide those who don't match the search query
        for (i = 0; i < tr.length; i++) {
            td = tr[i].getElementsByTagName("td")[0];
            if (td) {
                if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
                    tr[i].style.display = "";
                } else {
                    tr[i].style.display = "none";
                }
            }
        }

    }
    function myFunction1() {
        var input, filter, table, tr, td, i;
        input = document.getElementById("selectItems");
        filter = input.value.toUpperCase();
        table = document.getElementById("myTable");
        tr = table.getElementsByTagName("tr");
        // Loop through all table rows, and hide those who don't match the search query
        for (i = 0; i < tr.length; i++) {
            td = tr[i].getElementsByTagName("td")[0];
            if (td) {
                if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
                    tr[i].style.display = "";
                } else {
                    tr[i].style.display = "none";
                }
            }
        }

        document.getElementById("myInput").value= input.value;

    }

// myFunction1 can be use as (only use one of these myFunction1 functions):

function myFunction1() {

        document.getElementById("myInput").value=
        document.getElementById("selectItems").value;
        myFunction();

    }
</code>```

Body:
I am still new to programming and currently I encounter a problem. I have used a code from W3schools which allows me to filters the table when it matches the search result. However, I want to make it better for the users of the website. I want to allow them to be able to search through the searchbox and also give them the option to select a dropdown from the box which returns the same result.

Below is the code I have used for HTML:

<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names..">

    Fruit Name
    Place of Origin

    Apple
    Asia

    Black Berry
    North America

    Durian
    SouthEast Asia

    Watermelon
    South Korea

And the JavaScript used:

I'm sorry for this mess, in short, these were taken from the W3school site with some changes. Instead of having just a search box, I want to implement a drop down with the search box if it is possible. Any help would be greatly appreciated.

Body:
Try this :

HTML

    <input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names..">
    <select id="selectItems">
        <option>NA</option>
    </select>
<table id="myTable">

    <tr class="header">
        <th style="width:60%;">Fruit Name</th>
        <th style="width:40%;">Place of Origin</th>
    </tr>
    <tr>
        <td>Apple</td>
        <td>Asia</td>
    </tr>
    <tr>
        <td>Black Berry</td>
        <td>North America</td>
    </tr>
    <tr>
        <td>Durian</td>
        <td>SouthEast Asia</td>
    </tr>
    <tr>
        <td>Watermelon</td>
        <td>South Korea</td>
    </tr></table>

Javascript:

function init()
{
 //insert item in dropdown from table.

 var html_for_elect = '';
 var itm_dd = document.getElementById("selectItems");

 table1 = document.getElementById("myTable");
 trtbl = table1.getElementsByTagName("tr");

 for (i = 0; i < trtbl.length; i++) {
            td = trtbl[i].getElementsByTagName("td")[0];
            if (td) {
                html_for_elect = html_for_elect + "<option>"+td.innerHTML+"</option>";

            }
        }
itm_dd.innerHTML = html_for_elect;
}
init();
    function myFunction() {
        var input, filter, table, tr, td, i;
        input = document.getElementById("myInput");
        filter = input.value.toUpperCase();
        table = document.getElementById("myTable");
        tr = table.getElementsByTagName("tr");
        // Loop through all table rows, and hide those who don't match the search query
        for (i = 0; i < tr.length; i++) {
            td = tr[i].getElementsByTagName("td")[0];
            if (td) {
                if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
                    tr[i].style.display = "";
                } else {
                    tr[i].style.display = "none";
                }
            }
        }

    }
    function myFunction1() {
        var input, filter, table, tr, td, i;
        input = document.getElementById("selectItems");
        filter = input.value.toUpperCase();
        table = document.getElementById("myTable");
        tr = table.getElementsByTagName("tr");
        // Loop through all table rows, and hide those who don't match the search query
        for (i = 0; i < tr.length; i++) {
            td = tr[i].getElementsByTagName("td")[0];
            if (td) {
                if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
                    tr[i].style.display = "";
                } else {
                    tr[i].style.display = "none";
                }
            }
        }

        document.getElementById("myInput").value= input.value;

    }

// myFunction1 can be use as (only use one of these myFunction1 functions):

function myFunction1() {

        document.getElementById("myInput").value=
        document.getElementById("selectItems").value;
        myFunction();

    }


问:
Reason for using reactive programming in simple cases
Please, can somebody explain me what are the advantages of using reactive style:

```<code>Observable<String> greeting = Observable.just("Hello");
Observable<String> yelling = greeting.map(s -> s.toUppercase());
</code>```

instead of simple imperative style:

```<code>String greeting = "Hello";
String yelling = greeting.toUppercase();
</code>```

I understand reactive programming like the same “API” for database access, UI, computation, network access and etc. But why we need to use reactive programming for simple toUppercase

答:
Apart of all no blocking features, another great feature to use Reactive programing, is the important use of backpressure. Normally is used in situations where your publisher emit more information than your consumer can process.

So having this mechanism you can control the flow of traffic between both and avoid the nasty out of memory problems.

You can see some practicle examples of Reactive programing here https://github.com/politrons/reactive

And about back pressure here https://github.com/politrons/Akka/blob/master/src/main/scala/stream/BackPressure.scala

By the way, the only disadvantage about reactive programing, is the curve of learning because you´re changing paradigm of programing. But nowadays all important companies respect and follow the reactive manifesto http://www.reactivemanifesto.org/

If you want to see some practical examples you can reference here https://github.com/politrons/reactive

Body:
Please, can somebody explain me what are the advantages of using reactive style:

Observable<String> greeting = Observable.just("Hello");
Observable<String> yelling = greeting.map(s -> s.toUppercase());

instead of simple imperative style:

String greeting = "Hello";
String yelling = greeting.toUppercase();

I understand reactive programming like the same “API” for database access, UI, computation, network access and etc. But why we need to use reactive programming for simple toUppercase


问:
JAVA gives me wrong Date Results on Several devices
I have a weird problem I used Java to get a current date but I am getting different results on several devices, on one correct & on another wrong.
Here is my code:

```<code> public String getCurrentDate() {
     /// get date
     DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH);
     dateFormat.setTimeZone(TimeZone.getTimeZone("Asia/Tehran"));
     Date date = new Date();
     System.out.println(dateFormat.format(date)); //2017-11-13 18:20:46 correct time is 11am
     return dateFormat.format(date);
}
</code>```

On the device that gives the wrong result I set automatic time zone use network-provided time zone & time of the device is correct.

答:
You can use this method to get current time from your device:

```<code>public String getCurrentDate() {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Calendar calendar = Calendar.getInstance();
    String date = sdf.format(calendar.getTime());
    return date;
  }
</code>```

This method will return current date as string.

Body:
I have a weird problem I used Java to get a current date but I am getting different results on several devices, on one correct & on another wrong.
Here is my code:

 public String getCurrentDate() {
     /// get date
     DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH);
     dateFormat.setTimeZone(TimeZone.getTimeZone("Asia/Tehran"));
     Date date = new Date();
     System.out.println(dateFormat.format(date)); //2017-11-13 18:20:46 correct time is 11am
     return dateFormat.format(date);
}

On the device that gives the wrong result I set automatic time zone use network-provided time zone & time of the device is correct.

Body:
You can use this method to get current time from your device:

public String getCurrentDate() {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Calendar calendar = Calendar.getInstance();
    String date = sdf.format(calendar.getTime());
    return date;
  }

This method will return current date as string.


问:
Associativity, Precedence and F# Pipe-forward
The F# pipe-forward can be expressed as:

```<code>let (|>) x f = f x
</code>```

For example:

```<code>let SimpleFunction (a : typeA) (b : typeB) (c : typeC)=
    printf "OK."

// No problem here.
SimpleFunction a b c

// Using pipe-forward
c |> SimpleFunction a b
// No problem here. Interpreted as the same as above.
</code>```

However, according to the documentation, the pipe-forward operator is left-associative.

https://learn.microsoft.com/en-us/dotnet/fsharp/language-reference/symbol-and-operator-reference/

So, I expected the pipe-forward statement:

```<code>// Original Expression
c |> SimpleFunction a b

// to be equivalent to:
(c |> SimpleFunction) a b

// Which is equivalent to:
SimpleFunction c a b
// Error!! SimpleFunction takes typeA, then typeB, then typeC.
</code>```

Why does the compiler not "interpret" the pipe-forward expression as the error expression? Do I have any confusion about the operator precedence/associativity?

Additional Sources:

http://theburningmonk.com/2011/09/fsharp-pipe-forward-and-pipe-backward/

What is associativity of operators and why is it important?

https://en.wikipedia.org/wiki/Operator_associativity

答:
The associativitity of a binary operator only matters when you have two or more occurrences of the same operator. When you have different operators (here: |> and juxtaposition), what matters is their relative precedence.

Juxtaposition has a higher precedence than |>, therefore

```<code>c |> SimpleFunction a b
</code>```

is parsed like

```<code>(c) |> (SimpleFunction a b)
</code>```

so, by the definition of |>, it's equivalent to

```<code>(SimpleFunction a b) (c)
</code>```

which would usually be written

```<code>SimpleFunction a b c
</code>```

That last equivalence is due to juxtaposition being left-associative.

The fact that |> is left-associative means that an expression like

```<code>x |> f |> g
</code>```

is parsed as

```<code>(x |> f) |> g
</code>```

which is equivalent to

```<code>g (f x)
</code>```

i.e. chains of |> express function composition — successive pipeline steps — and not passing more arguments to a function.

Body:
The F# pipe-forward can be expressed as:

let (|>) x f = f x

For example:

let SimpleFunction (a : typeA) (b : typeB) (c : typeC)=
    printf "OK."

// No problem here.
SimpleFunction a b c

// Using pipe-forward
c |> SimpleFunction a b
// No problem here. Interpreted as the same as above.

However, according to the documentation, the pipe-forward operator is left-associative.

https://learn.microsoft.com/en-us/dotnet/fsharp/language-reference/symbol-and-operator-reference/

So, I expected the pipe-forward statement:

// Original Expression
c |> SimpleFunction a b

// to be equivalent to:
(c |> SimpleFunction) a b

// Which is equivalent to:
SimpleFunction c a b
// Error!! SimpleFunction takes typeA, then typeB, then typeC.

Why does the compiler not "interpret" the pipe-forward expression as the error expression? Do I have any confusion about the operator precedence/associativity?

Additional Sources:

http://theburningmonk.com/2011/09/fsharp-pipe-forward-and-pipe-backward/

What is associativity of operators and why is it important?

https://en.wikipedia.org/wiki/Operator_associativity

Body:
The associativitity of a binary operator only matters when you have two or more occurrences of the same operator. When you have different operators (here: |> and juxtaposition), what matters is their relative precedence.

Juxtaposition has a higher precedence than |>, therefore

c |> SimpleFunction a b

is parsed like

(c) |> (SimpleFunction a b)

so, by the definition of |>, it's equivalent to

(SimpleFunction a b) (c)

which would usually be written

SimpleFunction a b c

That last equivalence is due to juxtaposition being left-associative.

The fact that |> is left-associative means that an expression like

x |> f |> g

is parsed as

(x |> f) |> g

which is equivalent to

g (f x)

i.e. chains of |> express function composition — successive pipeline steps — and not passing more arguments to a function.


问:
rectangle not showing up in opencv
Why is rectangle not showing up in my code?</p>

```<code>import cv2

im = cv2.imread('players.bmp')

#im.shape >>returns (765,1365,3)

cv2.rectangle(im, (64,1248), (191,1311), (0,255,0), 2)
cv2.namedWindow("image", cv2.WINDOW_NORMAL)
cv2.imshow('image', im)
cv2.waitKey(0)
cv2.destroyAllWindows()
</code>```

答:
It does not show the rectangle, because you are drawing it outside the image.

Why? you may be asking. It is simple. You have this:

```<code>#im.shape >>returns (765,1365,3)
</code>```

This means

```<code>rows/height = 765
cols/width = 1365
channels = 3
</code>```

Then you do

```<code>cv2.rectangle(im, (64,1248), (191,1311), (0,255,0), 2)
</code>```

Here you use 2 points which are tuples (x,y), but you are writing them as if they where tuples (y,x). I know that OpenCV uses in a lot of functions the order (y,x), but this is due that they see the image as a matrix, which commonly is accessed with (row, column) which translates to (y,x). In the case of this rectangle they require Points which are expressed in the typical Cartesian way (x,y).

In conclusion, just change it to:

```<code>cv2.rectangle(im, (1248, 64), (1311, 191), (0,255,0), 2)
</code>```

And it should work.

Title: rectangle not showing up in opencv

Body:
Why is rectangle not showing up in my code?

import cv2

im = cv2.imread('players.bmp')

#im.shape >>returns (765,1365,3)

cv2.rectangle(im, (64,1248), (191,1311), (0,255,0), 2)
cv2.namedWindow("image", cv2.WINDOW_NORMAL)
cv2.imshow('image', im)
cv2.waitKey(0)
cv2.destroyAllWindows()

Body:
It does not show the rectangle, because you are drawing it outside the image.

Why? you may be asking. It is simple. You have this:

#im.shape >>returns (765,1365,3)

This means

rows/height = 765
cols/width = 1365
channels = 3

Then you do

cv2.rectangle(im, (64,1248), (191,1311), (0,255,0), 2)

Here you use 2 points which are tuples (x,y), but you are writing them as if they where tuples (y,x). I know that OpenCV uses in a lot of functions the order (y,x), but this is due that they see the image as a matrix, which commonly is accessed with (row, column) which translates to (y,x). In the case of this rectangle they require Points which are expressed in the typical Cartesian way (x,y).

In conclusion, just change it to:

cv2.rectangle(im, (1248, 64), (1311, 191), (0,255,0), 2)

And it should work.


问:
When appending items dynamically, masonry does not layout them out
I am using a Masonry JavaScript grid layout library https://masonry.desandro.com/. I have an issue when appending new items to the grid directly from the DOM using Angular *ngfor which iterate through an a array as follows:

```<code><div class="grid">
  <div class="grid-item grid-item--height{{i}}" *ngFor="let i of array">
   {{i}}
  </div>
</div>
</code>```

Because I am not appending them using the "appended masonry method", masonry does not layout them out. The array is getting new elements every time a user scroll down. So a JavaScript method is called:

```<code>onScrollDown() {
 // add another 20 items
 this.sum += 20;
 for (let i = start; i < this.sum; ++i) {
     this.array.push(i);  }
 }
</code>```

When the array get more elements, it automatically creates new html items. So i need to find the way masonry layout them out again after the new items are being created. I tried  calling $grid.masonry('layout') after the elements have being added to the array in the OnScrollMethod but it did not work.
I am trying $('.grid').masonry('reloadItems') as well, but calling this method the new items are overlapping the previous ones.

I would appreciate any help.

Update:

I am initializing masonry using my angular initialize component method as follows:

```<code>  ngOnInit() {
  this.$grid = jQuery('.grid').masonry({
    // options
    itemSelector: '.grid-item',
    columnWidth: 384,
    gutter: 24
  });
</code>```

答:
UPDATED

You might try reloadItems. If your loading images, use imagesLoaded.js to avoid overlaps:

```<code>ngOnInit() {
this.$grid = jQuery('.grid').imagesLoaded( function() {
jQuery('.grid').masonry({
// options
itemSelector: '.grid-item',
columnWidth: 384,
gutter: 24
});
});

onScrollDown() {
// add another 20 items
this.sum += 20;
for (let i = start; i < this.sum; ++i) {
 this.array.push(i);  }
jQuery('.grid').imagesLoaded( function() {
jQuery('.grid').masonry('reloadItems');
});
 }
</code>```

Body:
I am using a Masonry JavaScript grid layout library https://masonry.desandro.com/. I have an issue when appending new items to the grid directly from the DOM using Angular *ngfor which iterate through an a array as follows:

   {{i}}

Because I am not appending them using the "appended masonry method", masonry does not layout them out. The array is getting new elements every time a user scroll down. So a JavaScript method is called:

onScrollDown() {
 // add another 20 items
 this.sum += 20;
 for (let i = start; i < this.sum; ++i) {
     this.array.push(i);  }
 }

When the array get more elements, it automatically creates new html items. So i need to find the way masonry layout them out again after the new items are being created. I tried  calling $grid.masonry('layout') after the elements have being added to the array in the OnScrollMethod but it did not work.
I am trying $('.grid').masonry('reloadItems') as well, but calling this method the new items are overlapping the previous ones.

I would appreciate any help.

Update:

I am initializing masonry using my angular initialize component method as follows:

  ngOnInit() {
  this.$grid = jQuery('.grid').masonry({
    // options
    itemSelector: '.grid-item',
    columnWidth: 384,
    gutter: 24
  });

Body:
UPDATED

You might try reloadItems. If your loading images, use imagesLoaded.js to avoid overlaps:

ngOnInit() {
this.$grid = jQuery('.grid').imagesLoaded( function() {
jQuery('.grid').masonry({
// options
itemSelector: '.grid-item',
columnWidth: 384,
gutter: 24
});
});

onScrollDown() {
// add another 20 items
this.sum += 20;
for (let i = start; i < this.sum; ++i) {
 this.array.push(i);  }
jQuery('.grid').imagesLoaded( function() {
jQuery('.grid').masonry('reloadItems');
});
 }


问:
How to pass gradle parameter on IntelliJ sync

EDIT:

Turns out it was not a bug but misconfiguration on my part.

Original question

Due to this bug in IntelilJ I have to add

```<code>configurations {
    all {
        exclude(group = "ch.qos.logback", module = "logback-classic")
    }
}
</code>```

during IntelliJ gradle sync and then not forget to remove it.

Is there a way to pass a param to gradle on IntelliJ sync? I'd be able to have something like this:

```<code>if (project.hasProperty("intellijHack"))
    configurations {
        all {
            exclude(group = "ch.qos.logback", module = "logback-classic")
        }
    }
</code>```

答:
Passing command line options to IDE gradle importer process directly in IDE is not yet supported (only possible to a Gradle task Run Configuration with the 'Script parameters' field). Please vote and follow this request.

It should work with the gradle.properties file, though this property will also be honored by Gradle, launched from the command line.

Update(as of April 2023) : The above issue has been declined. A related issue exists at Ability to control Gradle build environment (using command line or environment variables) . Please vote and follow the request.

Body:
EDIT:

Turns out it was not a bug but misconfiguration on my part.

Original question

Due to this bug in IntelilJ I have to add

configurations {
    all {
        exclude(group = "ch.qos.logback", module = "logback-classic")
    }
}

during IntelliJ gradle sync and then not forget to remove it.

Is there a way to pass a param to gradle on IntelliJ sync? I'd be able to have something like this:

if (project.hasProperty("intellijHack"))
    configurations {
        all {
            exclude(group = "ch.qos.logback", module = "logback-classic")
        }
    }

ContentLicense: CC BY-SA 4.0


问:
Getting Access-Control-Allow-Headers in preflight error
I have created angular js app in which I have integrate twitch api , the api is

```<code> return $http({
        url: "https://api.twitch.tv/kraken/streams",
        method: "GET",
        params: { channel: channel, limit: 1 },
        headers: { "Client-Id": "XXXXXXXXXXXXXXX" }
    })
</code>```

the problem is when I reload the page the api is working but when my state changes without page reload I am getting cross origin error from this api.
the error is

Failed to load https://api.twitch.tv/kraken/streams?channel=eliazOne&limit=1: Request header field RefreshToken is not allowed by Access-Control-Allow-Headers in preflight response.

anyone has idea how to resolve cross error

答:
When you make a request to a different domain this is called a cross domain request. Also known as a CORS request.

When you POST / PUT data to a different domain it will make an OPTIONS request first. This is to ensure that the server has Access-Control-Allow-Headers in place on the response. These headers should permit access to the domain you are making the request from. If these headers are not present then when the OPTIONS request is made it will fail and the POST / PUT will never be made.

See here for more info https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#Preflighted_requests

The simple answer is to just add these headers to your server.

Body:
I have created angular js app in which I have integrate twitch api , the api is

 return $http({
        url: "https://api.twitch.tv/kraken/streams",
        method: "GET",
        params: { channel: channel, limit: 1 },
        headers: { "Client-Id": "XXXXXXXXXXXXXXX" }
    })

the problem is when I reload the page the api is working but when my state changes without page reload I am getting cross origin error from this api.
the error is

Failed to load https://api.twitch.tv/kraken/streams?channel=eliazOne&limit=1: Request header field RefreshToken is not allowed by Access-Control-Allow-Headers in preflight response.

anyone has idea how to resolve cross error


问:
APi Refresh token error
I don't understand... We have no problem for refresh token with this code with OneDrive classical account:

```<code>Curl url: https://login.live.com/oauth20_token.srf
Curl post: 1
Curl postfields: client_id, refresh_token, grant_type, redirect_uri, client_secret
</code>```

But with OneDrive Enterprise account, it doesn't work. We have this error:

```<code>*object(stdClass)#1 (2) {
  ["error"]=>
  string(13) "invalid_grant"
  ["error_description"]=>
  string(87) "The provided value for the input parameter 'refresh_token' or 'assertion' is not valid."
}*
</code>```

Is the call different with One Drive Enterprise?

答:
Finaly, question is:

What's the call to use for a refresh token with a OneDrive Business account?

With this call, it works with a OneDrive account but not with a Business OneDrive account:

```<code>curl_setopt_array($curl, array(
        CURLOPT_HTTPHEADER => $header,
        CURLOPT_RETURNTRANSFER => 1,
        CURLOPT_URL => 'https://login.live.com/oauth20_token.srf',
        CURLOPT_USERAGENT => 'Codular Sample cURL Request',
        CURLOPT_POST => 1,
        CURLOPT_POSTFIELDS => "client_id=".**CLIENT_ID**."&refresh_token=".**USER_TOKEN**."&grant_type=refresh_token&redirect_uri=https://example.com/oauth.php&client_secret=**CLIENT_SECRET**
    ));
</code>```

With Business account, we have:

```<code>object(stdClass)#1 (2) {
  ["error"]=>
  string(13) "invalid_grant"
  ["error_description"]=>
  string(87) "The provided value for the input parameter 'refresh_token' or 'assertion' is not valid."
}
</code>```

Title: APi Refresh token error

Body:
I don't understand... We have no problem for refresh token with this code with OneDrive classical account:

Curl url: https://login.live.com/oauth20_token.srf
Curl post: 1
Curl postfields: client_id, refresh_token, grant_type, redirect_uri, client_secret

But with OneDrive Enterprise account, it doesn't work. We have this error:

*object(stdClass)#1 (2) {
  ["error"]=>
  string(13) "invalid_grant"
  ["error_description"]=>
  string(87) "The provided value for the input parameter 'refresh_token' or 'assertion' is not valid."
}*

Is the call different with One Drive Enterprise?

Body:
Finaly, question is:

What's the call to use for a refresh token with a OneDrive Business account?

With this call, it works with a OneDrive account but not with a Business OneDrive account:

curl_setopt_array($curl, array(
        CURLOPT_HTTPHEADER => $header,
        CURLOPT_RETURNTRANSFER => 1,
        CURLOPT_URL => 'https://login.live.com/oauth20_token.srf',
        CURLOPT_USERAGENT => 'Codular Sample cURL Request',
        CURLOPT_POST => 1,
        CURLOPT_POSTFIELDS => "client_id=".**CLIENT_ID**."&refresh_token=".**USER_TOKEN**."&grant_type=refresh_token&redirect_uri=https://example.com/oauth.php&client_secret=**CLIENT_SECRET**
    ));

With Business account, we have:

object(stdClass)#1 (2) {
  ["error"]=>
  string(13) "invalid_grant"
  ["error_description"]=>
  string(87) "The provided value for the input parameter 'refresh_token' or 'assertion' is not valid."
}


问:
What's the syntax for mod in java
As an example in pseudocode:</p>

```<code>if ((a mod 2) == 0)
{
    isEven = true;
}
else
{
    isEven = false;
}
</code>```

答:
you should examine the specification before using 'remainder' operator % :

http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.17.3

```<code>// bad enough implementation of isEven method, for fun. so any worse?
boolean isEven(int num)
{
    num %= 10;
    if(num == 1)
       return false;
    else if(num == 0)
       return true;
    else
       return isEven(num + 2);
}
isEven = isEven(a);
</code>```

Title: What's the syntax for mod in java

Body:
As an example in pseudocode:

if ((a mod 2) == 0)
{
    isEven = true;
}
else
{
    isEven = false;
}

LastEditorDisplayName: Chris Jester-Young

Body:
you should examine the specification before using 'remainder' operator % :

http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.17.3

// bad enough implementation of isEven method, for fun. so any worse?
boolean isEven(int num)
{
    num %= 10;
    if(num == 1)
       return false;
    else if(num == 0)
       return true;
    else
       return isEven(num + 2);
}
isEven = isEven(a);


问:
Personal Portfolio Page - Stuck with Bootstrap Grid Layout
https://codepen.io/shaan046/pen/vWmVNY

HTML code:

```<code><body>
  <div id="header" class="row">
    <div class="col-md-1 col-lg-1"><h3 id="myText">Shantanu Tomar</h3</div>
        <div class="col-md-offset-5 col-md-2 col-lg-offset-5 col-lg-2"><button class="btn btn-primary">Button1</button></div>
        <div class="col-md-2 col-lg-2"><button class="btn">Button2</button></div>
        <div class="col-md-2 col-lg-2"><button class="btn">Button3</button></div>
        </div>
  </body>
</html>
</code>```

CSS Code

```<code>#header{
  background-color:red;
}
</code>```

JS code:

```<code>$(document).ready(function() {
  $("body").addClass("container-fluid");

});
</code>```

What I want is that the text “Shantanu Tomar” and 3 buttons on screen should come in div #header in a single row. I am using Bootstrap3. Not sure how I can provide col-- tags so that the webpage is visible on Phone, tablet, Laptop in right manner? I tried using lg and md classes but the buttons are not lining up with text “Shantanu Tomar”.

Thanks for the help!!

答:
Try like this. and learn bootstrap from W3schools https://www.w3schools.com/bootstrap/

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

Shantanu Tomar

<button class="btn btn-primary">Button1</button>

<button class="btn">Button2</button>

<button class="btn">Button3</button>

```

Body:
https://codepen.io/shaan046/pen/vWmVNY

HTML code:

Shantanu Tomar</h3

<button class="btn btn-primary">Button1</button>

<button class="btn">Button2</button>

<button class="btn">Button3</button>

CSS Code

#header{
  background-color:red;
}

JS code:

$(document).ready(function() {
  $("body").addClass("container-fluid");

});

What I want is that the text “Shantanu Tomar” and 3 buttons on screen should come in div #header in a single row. I am using Bootstrap3. Not sure how I can provide col-- tags so that the webpage is visible on Phone, tablet, Laptop in right manner? I tried using lg and md classes but the buttons are not lining up with text “Shantanu Tomar”.

Thanks for the help!!

Body:
Try like this. and learn bootstrap from W3schools https://www.w3schools.com/bootstrap/

<html>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<body>
  <div id="header" class="row">
    <div class="col-md-12 col-lg-12">
      <div class="col-md-3 col-lg-3">
        <h3 id="myText">Shantanu Tomar</h3></div>
        <div class=" col-md-2 col-lg-2"><button class="btn btn-primary">Button1</button></div>
        <div class="col-md-2 col-lg-2"><button class="btn">Button2</button></div>
        <div class="col-md-2 col-lg-2"><button class="btn">Button3</button></div>
        </div>
  </body>
</html>


问:
Vertically center parent div on page
I know vertical alignment is tricky and there are plenty of questions about it on stackoverflow... I have been trying to figure this out for a few hours, with no success, so decided to ask it (apologies if it is a duplicate)

I have created a login page for my website.

There are 2 main divs in the body, one for logo and one for login content. The login content, has 2 sections, one for email and password and one for social media login.

```<code><body>
 <div>
 My Logo goes here
 <div>
 <div>
  <section id="loginForm"></section>
  <section id="SocialLoginForm"></section>
 </div>
</body>
</code>```

Is there a way to always vertically center the login div? I want the logo to stay on the top, but the login div be vertically centered. I know I can assign a height to the div and center it's content, but I don't know how to determine the height as the screen size will change...

this is how it looks like, as you see there is a big gap at the bottom.

答:
If you dont mind using preprocessor such as Sass. I would recommend using a mixin like that:</p>

```<code>@mixin center($axis: "both") {
  position: absolute;
  @if $axis == "y" {
  -moz-transform: translateY(-50%);
  -ms-transform: translateY(-50%);
  -o-transform: translateY(-50%);
  -webkit-transform: translateY(-50%);
  top: 50%;
  transform: translateY(-50%);
 }
 @if $axis == "x" {
   -moz-transform: translateX(-50%);
   -ms-transform: translateX(-50%);
   -o-transform: translateX(-50%);
   -webkit-transform: translateX(-50%);
   left: 50%;
   transform: translateX(-50%);
 }
 @if $axis == "both" {
   -moz-transform: translate(-50%, -50%);
   -ms-transform: translate(-50%, -50%);
   -o-transform: translate(-50%, -50%);
   -webkit-transform: translate(-50%, -50%);
   left: 50%;
   top: 50%;
   transform: translate(-50%, -50%);
   }
  }

body {
  position: relative;
  .inner-div {
    @include center(); //both horizontaly and vertically pass 'x' or 'y' to center veritcally or horizontal
  }
}
</code>```

Title: Vertically center parent div on page

Body:
I know vertical alignment is tricky and there are plenty of questions about it on stackoverflow... I have been trying to figure this out for a few hours, with no success, so decided to ask it (apologies if it is a duplicate)

I have created a login page for my website.

There are 2 main divs in the body, one for logo and one for login content. The login content, has 2 sections, one for email and password and one for social media login.

 My Logo goes here

Is there a way to always vertically center the login div? I want the logo to stay on the top, but the login div be vertically centered. I know I can assign a height to the div and center it's content, but I don't know how to determine the height as the screen size will change...

this is how it looks like, as you see there is a big gap at the bottom.

Body:
If you dont mind using preprocessor such as Sass. I would recommend using a mixin like that:

@mixin center($axis: "both") {
  position: absolute;
  @if $axis == "y" {
  -moz-transform: translateY(-50%);
  -ms-transform: translateY(-50%);
  -o-transform: translateY(-50%);
  -webkit-transform: translateY(-50%);
  top: 50%;
  transform: translateY(-50%);
 }
 @if $axis == "x" {
   -moz-transform: translateX(-50%);
   -ms-transform: translateX(-50%);
   -o-transform: translateX(-50%);
   -webkit-transform: translateX(-50%);
   left: 50%;
   transform: translateX(-50%);
 }
 @if $axis == "both" {
   -moz-transform: translate(-50%, -50%);
   -ms-transform: translate(-50%, -50%);
   -o-transform: translate(-50%, -50%);
   -webkit-transform: translate(-50%, -50%);
   left: 50%;
   top: 50%;
   transform: translate(-50%, -50%);
   }
  }

body {
  position: relative;
  .inner-div {
    @include center(); //both horizontaly and vertically pass 'x' or 'y' to center veritcally or horizontal
  }
}


答:
Based on your comments, below is the updated code with search box as well as dropdown that will filter rows:

function myFunction(searchTerm) {
  var input, filter, table, tr, td, i;
  filter = searchTerm.toUpperCase();
  table = document.getElementById("myTable");
  tr = table.getElementsByTagName("tr");
  // Loop through all table rows, and hide those who don't match the search query
  for (i = 0; i
 -1) {
        tr[i].style.display = "";
      } else {
        tr[i].style.display = "none";
      }
    }
  }
}

var options = $("#fruitOptions");
$("#myTable tr:not(.header)").each(function() {
  options.append($("<option />").val($(this).find("td:first-child").text()).text($(this).find("td:first-child").text()));
});

$("#myInput").on('input', function() {
  myFunction($(this).val());
});

$("#fruitOptions").on('change', function() {
  myFunction($(this).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="myInput" placeholder="Search for names..">
<select id="fruitOptions">
<option value=''>- Please select -</option></select>
<table id="myTable">
  <tr class="header">
    <th style="width:60%;">Fruit Name</th>
    <th style="width:40%;">Place of Origin</th>
  </tr>
  <tr>
    <td>Apple</td>
    <td>Asia</td>
  </tr>
  <tr>
    <td>Black Berry</td>
    <td>North America</td>
  </tr>
  <tr>
    <td>Durian</td>
    <td>SouthEast Asia</td>
  </tr>
  <tr>
    <td>Watermelon</td>
    <td>South Korea</td>
  </tr>
</table></code>```

Title: How to have a dropdown searchbox that filters table results?

Body:
I am still new to programming and currently I encounter a problem. I have used a code from W3schools which allows me to filters the table when it matches the search result. However, I want to make it better for the users of the website. I want to allow them to be able to search through the searchbox and also give them the option to select a dropdown from the box which returns the same result.

Below is the code I have used for HTML:

<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names..">

    Fruit Name
    Place of Origin

    Apple
    Asia

    Black Berry
    North America

    Durian
    SouthEast Asia

    Watermelon
    South Korea

And the JavaScript used:

I'm sorry for this mess, in short, these were taken from the W3school site with some changes. Instead of having just a search box, I want to implement a drop down with the search box if it is possible. Any help would be greatly appreciated.

Body:
Based on your comments, below is the updated code with search box as well as dropdown that will filter rows:

function myFunction(searchTerm) {
  var input, filter, table, tr, td, i;
  filter = searchTerm.toUpperCase();
  table = document.getElementById("myTable");
  tr = table.getElementsByTagName("tr");
  // Loop through all table rows, and hide those who don't match the search query
  for (i = 0; i < tr.length; i++) {
    td = tr[i].getElementsByTagName("td")[0];
    if (td) {
      if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
        tr[i].style.display = "";
      } else {
        tr[i].style.display = "none";
      }
    }
  }
}

var options = $("#fruitOptions");
$("#myTable tr:not(.header)").each(function() {
  options.append($("<option />").val($(this).find("td:first-child").text()).text($(this).find("td:first-child").text()));
});

$("#myInput").on('input', function() {
  myFunction($(this).val());
});

$("#fruitOptions").on('change', function() {
  myFunction($(this).val());
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="myInput" placeholder="Search for names..">
<select id="fruitOptions">
<option value=''>- Please select -</option></select>
<table id="myTable">
  <tr class="header">
    <th style="width:60%;">Fruit Name</th>
    <th style="width:40%;">Place of Origin</th>
  </tr>
  <tr>
    <td>Apple</td>
    <td>Asia</td>
  </tr>
  <tr>
    <td>Black Berry</td>
    <td>North America</td>
  </tr>
  <tr>
    <td>Durian</td>
    <td>SouthEast Asia</td>
  </tr>
  <tr>
    <td>Watermelon</td>
    <td>South Korea</td>
  </tr>
</table>


问:
Need help understanding how to pop stack with add esp, 12
I have a question about this assembly program:

```<code>extern printf                ; the C function, to be called

SECTION .data                ; Data section, initialized variables
a: dd 5                      ; int a=5;
fmt: db "a=%d, eax=%d",10,0  ; The printf format, '\n','0'

SECTION .text                ; Code section.

global main                  ; the standard gcc entry point
main:                        ; the program label for the entry point

push ebp                  ; calling convention
mov ebp, esp

mov eax, [a]              ; put a from store into register
add eax, 2                ; a+2
push eax                  ; value of a+2
push dword [a]            ; value of variable a
push dword fmt            ; address of ctrl string
call printf               ; Call C function
add  esp, 12              ; pop stack 3 times = 4 bytes

mov esp, ebp              ; returning convention
pop ebp                   ; same as "leave" op

mov eax,0                 ; normal (no error) return value
ret                       ; return
</code>```

I see that near the end it pops the stack 3 times which is equal to 4 bytes. However, I do not understand why the stack needs to be popped at the end, and how 12 is equivalent to "3 times = 4 bytes" Also, is it necessary that the stacked be popped at the end?

答:
when you call a (sub)function, the CPU needs to save the value where to jump back; it uses the stack for this

so when you enter the function, the topmost value on the stack is the return address

this code adds another 12 bytes to the stack

```<code>push eax                  ; value of a+2
push dword [a]            ; value of variable a
push dword fmt            ; address of ctrl string
</code>```

each of these push writes 4 bytes to [ESP], and subtracts 4 byes of ESP (subtraction because the stack is growing downwards). Before you can ret back to your callee, you have to get rid of these 12 bytes on the stack. the easies way is, what he did in his code:

```<code>add  esp, 12              ; pop stack 3 times = 4 bytes
</code>```

on the other hand, the function saves the current ESP in EBP right on top of the function (this creates a new 'stack frame')

```<code>push ebp                  ; calling convention
mov ebp, esp
</code>```

this is done to be able to adress the callee's function parameters and local variables you may have reserved place for [EBP +/- offset], AND it's making you able to restore the whole stack by just loading the former value again:

```<code>mov esp, ebp              ; returning convention
pop ebp                   ; same as "leave" op
</code>```

Note: in this code, the stack is cleaned up twice. ( add 12 to ESP (which cleans the stack from the values the syscall got as parameters), and again by loading previous value from EBP. In this case one of either is not needed

Body:
I have a question about this assembly program:

extern printf                ; the C function, to be called

SECTION .data                ; Data section, initialized variables
a: dd 5                      ; int a=5;
fmt: db "a=%d, eax=%d",10,0  ; The printf format, '\n','0'

SECTION .text                ; Code section.

global main                  ; the standard gcc entry point
main:                        ; the program label for the entry point

push ebp                  ; calling convention
mov ebp, esp

mov eax, [a]              ; put a from store into register
add eax, 2                ; a+2
push eax                  ; value of a+2
push dword [a]            ; value of variable a
push dword fmt            ; address of ctrl string
call printf               ; Call C function
add  esp, 12              ; pop stack 3 times = 4 bytes

mov esp, ebp              ; returning convention
pop ebp                   ; same as "leave" op

mov eax,0                 ; normal (no error) return value
ret                       ; return

I see that near the end it pops the stack 3 times which is equal to 4 bytes. However, I do not understand why the stack needs to be popped at the end, and how 12 is equivalent to "3 times = 4 bytes" Also, is it necessary that the stacked be popped at the end?

Body:
when you call a (sub)function, the CPU needs to save the value where to jump back; it uses the stack for this

so when you enter the function, the topmost value on the stack is the return address

this code adds another 12 bytes to the stack

push eax                  ; value of a+2
push dword [a]            ; value of variable a
push dword fmt            ; address of ctrl string

each of these push writes 4 bytes to [ESP], and subtracts 4 byes of ESP (subtraction because the stack is growing downwards). Before you can ret back to your callee, you have to get rid of these 12 bytes on the stack. the easies way is, what he did in his code:

add  esp, 12              ; pop stack 3 times = 4 bytes

on the other hand, the function saves the current ESP in EBP right on top of the function (this creates a new 'stack frame')

push ebp                  ; calling convention
mov ebp, esp

this is done to be able to adress the callee's function parameters and local variables you may have reserved place for [EBP +/- offset], AND it's making you able to restore the whole stack by just loading the former value again:

mov esp, ebp              ; returning convention
pop ebp                   ; same as "leave" op

Note: in this code, the stack is cleaned up twice. ( add 12 to ESP (which cleans the stack from the values the syscall got as parameters), and again by loading previous value from EBP. In this case one of either is not needed


问:
'ValueError: Initial condition y0 must be one-dimensional.' How do I rectify this error?
I have attached my code below, it is a  model of the two body problem.I have tried to use 1D vectors as my argument for the odeint function but I still face the error. Suggestions are much appreciated.</p>

```<code>tspan = np.linspace(0,p,(p/60.0)+1.0)
x0 = np.empty((6,1))
x0[0]=r[0]
x0[1]=r[1]
x0[2]=r[2]
x0[3]=v[0]
x0[4]=v[1]
x0[5]=v[2]
tspan = np.linspace(0,p,(p/60.0)+1.0)
x = odeint(ot.odetwobody,x0,tspan)
def odetwobody(x,t):
    mu = 398600.0
    r = np.sqrt(x[1]**2+x[2]**2+x[3]**2)
    xddot = np.empty((6,1))
    xddot[0] = x[3]
    xddot[1]=x[4]
    xddot[2]=x[5]
    xddot[3]=(-mu*x[0])/r**3
    xddot[4]=(-mu*x[1])/r**3
    xddot[5]=(-mu*x[2])/r**3
    return xddot
</code>```

答: Your initial condition is x0. You just need to change it from the forced 2D-but-not-really x0 = np.empty((6,1)) to the fully 1d x0 = np.empty(6).

Body:
I have attached my code below, it is a  model of the two body problem.I have tried to use 1D vectors as my argument for the odeint function but I still face the error. Suggestions are much appreciated.

tspan = np.linspace(0,p,(p/60.0)+1.0)
x0 = np.empty((6,1))
x0[0]=r[0]
x0[1]=r[1]
x0[2]=r[2]
x0[3]=v[0]
x0[4]=v[1]
x0[5]=v[2]
tspan = np.linspace(0,p,(p/60.0)+1.0)
x = odeint(ot.odetwobody,x0,tspan)
def odetwobody(x,t):
    mu = 398600.0
    r = np.sqrt(x[1]**2+x[2]**2+x[3]**2)
    xddot = np.empty((6,1))
    xddot[0] = x[3]
    xddot[1]=x[4]
    xddot[2]=x[5]
    xddot[3]=(-mu*x[0])/r**3
    xddot[4]=(-mu*x[1])/r**3
    xddot[5]=(-mu*x[2])/r**3
    return xddot


问:
Magnolia 5.5.6 Stories App Custom CKEditor Panel
The Magnolia-Team wrote (DevelopingCustomBlocks) that the RichTextFieldDefinition is not available for Blocks.

I would love to use content-editor in the future instead of pages. Is it possible to extent the editor panel

with (custom) plugins for the ckeditor (that I created to use with the RichTextField)? If yes could you give me a hint on how to accomplish that?

答:
It is possible, and you can even use the standard RichTextField.
However before you start extending it, please make sure you understand idea behind new editor, it's working, structure of data it stores and how is that data manipulated later in order to not dig for yourself hole that would be hard to escape with custom extensions.

Whole editor is meant to be fluent for editing and very simple to manipulate offering maximum of freedom. Editor works with concept of blocks. Each hit of enter produces new block of type text. There's other types of blocks offered OOTB by Magnolia. Each different type of block is stored separately and it's rendering can be controlled by template. E.g. each text block becomes paragraph or div in html, depending on your choice. For other blocks, they might produce other types of elements. And this is where you need to become careful. If you extend CK editor, or start using default/old RichTextField, you will suddenly end up with block that already contains html, thus making it unpredictable what the output might look like after such block is processed by your template and whether resulting html is valid or well formatted. The less of html you get "baked in" in each block, the easier templating becomes later.

As for adding extra plugins to the text block, you can modify config.js of the editor, as for adding RichTextField you can just create block that will provide this field. However, keep in mind that with first you run into risk of introducing potentially dangerous html and with the second it's same risk of baking in dangerous html and on top breaking editor experience as RTF will not support same keyboard shortcuts available for other blocks.


问:
Built-in libraries to persist a BTree, equivalent to Java's `FileChannel` and `ByteBuffer`
So, I wrote this persistent BTree in Java, following the CLRS algorithms.
I used FileChannel and ByteBuffer to store the tree in a file, reading and writing the nodes when needed.

I tried looking how I could store such a BTree in Go, and discovered os.File, which I think could be used the same way as Java's FileChannel.
However, I could not find an equivalent for ByteBuffer. I looked at bytes.Buffer, and I see how this could work, however it does not have the ByteBuffer's handy putInt, putDouble, etc...

Would I have to implement myself those function to transform ints and doubles to byte arrays? I also looked at encoding.binary, but this looks very cumbersome. I understand that I would have to encode my variables to a byte array every time, then copy that byte array to the buffer.

What structures would be recommended in this case?

答:
Using the encoding/gob package

Using the encoding/gob package you can serialize entire trees into a series of bytes and deserialize them with a single method call.

See this example:

```<code>type Node struct {
    Data     int
    Children []*Node
}

func (n *Node) String() string {
    buf := &bytes.Buffer{}
    buf.WriteString(fmt.Sprintf("Node[Data: %d, Children: [", n.Data))
    for i, v := range n.Children {
        if i > 0 {
            buf.WriteString(", ")
        }
        buf.WriteString(v.String())
    }
    buf.WriteString("]")
    return buf.String()
}
</code>```

The Node.String() method is not required, I only created it to easily print / verify the tree.

Now using gob to serialize and deserialize a tree:

```<code>root := &Node{
    Data: 1,
    Children: []*Node{
        {Data: 2},
        {Data: 3},
    },
}
fmt.Println(root)

buf := &bytes.Buffer{}
if err := gob.NewEncoder(buf).Encode(root); err != nil {
    panic(err)
}

var root2 *Node
if err := gob.NewDecoder(buf).Decode(&root2); err != nil {
    panic(err)
}
fmt.Println(root2)
</code>```

Output (try it on the Go Playground):

```<code>Node[Data: 1, Children: [Node[Data: 2, Children: [], Node[Data: 3, Children: []]
Node[Data: 1, Children: [Node[Data: 2, Children: [], Node[Data: 3, Children: []]
</code>```

Here I used an in-memory buffer (bytes.Buffer), but if you want to save to / load from a file, you don't even need an in-memory buffer, you can directly pass an *os.File value to gob.NewEncoder() and gob.NewDecoder() (as *os.File implements both io.Reader and io.Writer).

Manual serialization / deserialization

Also note that if you don't want to (or can't) use encoding/gob to do the complete serialization in one step, you can also use binary.Write() and binary.Read() functions to directly write to / read from your file without using any in-memory buffers.

See this example encoding and decoding an int32 and a float64 value:

```<code>var i int32
var f float64

i, f = 1, 3.14

buf := &bytes.Buffer{}
if err := binary.Write(buf, binary.LittleEndian, i); err != nil {
    panic(err)
}
if err := binary.Write(buf, binary.LittleEndian, f); err != nil {
    panic(err)
}

var i2 int32
var f2 float64
if err := binary.Read(buf, binary.LittleEndian, &i2); err != nil {
    panic(err)
}
if err := binary.Read(buf, binary.LittleEndian, &f2); err != nil {
    panic(err)
}

fmt.Println(i2, f2)
</code>```

Output (try it on the Go Playground):

```<code>1 3.14
</code>```

Again, you can pass your file directly to binary.Read() and binary.Write() instead of *bytes.Buffer.

Non-binary serialization

You could also use other, non-binary serialization formats such as JSON.
 The encoding/json package will also be able to serialize / deserialize your entire tree with a single call. Using JSON would be less performant in terms of storage and speed though, but the serialized format would be more human-friendly (more readable / editable), and compatible with other applications / technologies.

Body:
Using the encoding/gob package

Using the encoding/gob package you can serialize entire trees into a series of bytes and deserialize them with a single method call.

See this example:

type Node struct {
    Data     int
    Children []*Node
}

func (n *Node) String() string {
    buf := &bytes.Buffer{}
    buf.WriteString(fmt.Sprintf("Node[Data: %d, Children: [", n.Data))
    for i, v := range n.Children {
        if i > 0 {
            buf.WriteString(", ")
        }
        buf.WriteString(v.String())
    }
    buf.WriteString("]")
    return buf.String()
}

The Node.String() method is not required, I only created it to easily print / verify the tree.

Now using gob to serialize and deserialize a tree:

root := &Node{
    Data: 1,
    Children: []*Node{
        {Data: 2},
        {Data: 3},
    },
}
fmt.Println(root)

buf := &bytes.Buffer{}
if err := gob.NewEncoder(buf).Encode(root); err != nil {
    panic(err)
}

var root2 *Node
if err := gob.NewDecoder(buf).Decode(&root2); err != nil {
    panic(err)
}
fmt.Println(root2)

Output (try it on the Go Playground):

Node[Data: 1, Children: [Node[Data: 2, Children: [], Node[Data: 3, Children: []]
Node[Data: 1, Children: [Node[Data: 2, Children: [], Node[Data: 3, Children: []]

Here I used an in-memory buffer (bytes.Buffer), but if you want to save to / load from a file, you don't even need an in-memory buffer, you can directly pass an *os.File value to gob.NewEncoder() and gob.NewDecoder() (as *os.File implements both io.Reader and io.Writer).

Manual serialization / deserialization

Also note that if you don't want to (or can't) use encoding/gob to do the complete serialization in one step, you can also use binary.Write() and binary.Read() functions to directly write to / read from your file without using any in-memory buffers.

See this example encoding and decoding an int32 and a float64 value:

var i int32
var f float64

i, f = 1, 3.14

buf := &bytes.Buffer{}
if err := binary.Write(buf, binary.LittleEndian, i); err != nil {
    panic(err)
}
if err := binary.Write(buf, binary.LittleEndian, f); err != nil {
    panic(err)
}

var i2 int32
var f2 float64
if err := binary.Read(buf, binary.LittleEndian, &i2); err != nil {
    panic(err)
}
if err := binary.Read(buf, binary.LittleEndian, &f2); err != nil {
    panic(err)
}

fmt.Println(i2, f2)

Output (try it on the Go Playground):

1 3.14

Again, you can pass your file directly to binary.Read() and binary.Write() instead of *bytes.Buffer.

Non-binary serialization

You could also use other, non-binary serialization formats such as JSON.
 The encoding/json package will also be able to serialize / deserialize your entire tree with a single call. Using JSON would be less performant in terms of storage and speed though, but the serialized format would be more human-friendly (more readable / editable), and compatible with other applications / technologies.


问:
AWS Lambda invoke exception "No LambdaFunction annotation for method invoke"
I am invoking a Lambda function from my Java code that is running inside Spark process.

The invocation is failing with following exception:

23:22:50,043 ERROR com.gravty.batch.process.BitProcessImpl -
  com.amazonaws.services.lambda.invoke.LambdaSerializationException: No
  LambdaFunction annotation for method invoke

Does anyone has any idea about this error?

答:
Resolved it by using interface with @LambdaFunction annotation.

my lambda interface:

```<code>public interface MyLambdaService {
    @LambdaFunction
    ApiGatewayProxyResponse execute(ApiGatewayRequest bit);
}
</code>```

this is how I created the lambda client:

```<code>MyLambdaService lambdaService = LambdaInvokerFactory.builder().lambdaClient(AWSLambdaClientBuilder.defaultClient())
                    .lambdaFunctionNameResolver((method, annotation, config) -> "ENV_SPECIFIC_FUNCTION_NAME").build(MyLambdaService.class);
</code>```

Body:
Resolved it by using interface with @LambdaFunction annotation.

my lambda interface:

public interface MyLambdaService {
    @LambdaFunction
    ApiGatewayProxyResponse execute(ApiGatewayRequest bit);
}

this is how I created the lambda client:

MyLambdaService lambdaService = LambdaInvokerFactory.builder().lambdaClient(AWSLambdaClientBuilder.defaultClient())
                    .lambdaFunctionNameResolver((method, annotation, config) -> "ENV_SPECIFIC_FUNCTION_NAME").build(MyLambdaService.class);


问:
declare variable inside or outside a loop, does it make big difference?
for example

```<code>int i, a, c, d; // these vars will only be used in while
while(bigNumber--) {
    i = doSomething();
    // **

}
</code>```

and

```<code>while(bigNumber--) {
   int i, a, b, c; // i'd like to put it here for readability
   i = doSomething();
   // **
}
</code>```

Does it make big difference in terms of performance?

答:
I think if you put it like this, it will constantly redeclare the variables, so no matter what you initialize, it will get lost after the variables redeclare themselves.</p>

```<code>while(bigNumber--) {
   int i, a, b, c;
   i = doSomething();
}
</code>```

Body:
for example

int i, a, c, d; // these vars will only be used in while
while(bigNumber--) {
    i = doSomething();
    // **

}

and

while(bigNumber--) {
   int i, a, b, c; // i'd like to put it here for readability
   i = doSomething();
   // **
}

Does it make big difference in terms of performance?

Body:
I think if you put it like this, it will constantly redeclare the variables, so no matter what you initialize, it will get lost after the variables redeclare themselves.

while(bigNumber--) {
   int i, a, b, c;
   i = doSomething();
}


问:
C# get variable name of an object in it's constructor
I'm creating a bunch of string variables, which are to be used to store the value of the variable name itself.
e.g

```<code>string name = "name";
string number="number;
</code>```

but as the list gets long, it becomes tedious to repetitively typing everything, so I made a class that just holds string data, and let the constructor to do the dirty work. e.g

```<code>class Data
{
public Data()
{
//pseudo code here:
name = NameOfTheVariable(this);
}
public string name {get;set;}
}
</code>```

So the ideal output would be something like this:

```<code>public static void Main()
{
//Declare an object here, the constructor will automatically assign the
//variable name to the property.
 Data number = new Data();
 Console.WriteLine(number.name);
}
</code>```

The output would be: "number", which is the variable name itself.

I did try to use MemberExpression mentioned in this post: get name of a variable or parameter

But the function doesn't take the keyword "this" as an valid argument.
so I cannot use the function provided in that post, eg:

```<code>class Data
{
public Data()
{
//This line will not work
name= MemberInfoGetting.GetMemberName(() => this);
}
public string name{get;set;}

}
</code>```

Anybody know how I could solve this problem?

答:
```<code>Data number = new Data();
Console.WriteLine(number.name);
</code>```

In C# 6.0 and above that would be:

```<code>SomeNumberClass number = new SomeNumberClass();
Console.WriteLine(nameof(number));
</code>```

The solution for Pre-C# 6 you linked would work accordingly, you just would not write nameof but use a static method instead:

```<code>SomeNumberClass number = new SomeNumberClass();
Console.WriteLine(MemberInfoGetting.GetMemberName(() => number));
</code>```

Body:
I'm creating a bunch of string variables, which are to be used to store the value of the variable name itself.
e.g

string name = "name";
string number="number;

but as the list gets long, it becomes tedious to repetitively typing everything, so I made a class that just holds string data, and let the constructor to do the dirty work. e.g

class Data
{
public Data()
{
//pseudo code here:
name = NameOfTheVariable(this);
}
public string name {get;set;}
}

So the ideal output would be something like this:

public static void Main()
{
//Declare an object here, the constructor will automatically assign the
//variable name to the property.
 Data number = new Data();
 Console.WriteLine(number.name);
}

The output would be: "number", which is the variable name itself.

I did try to use MemberExpression mentioned in this post: get name of a variable or parameter

But the function doesn't take the keyword "this" as an valid argument.
so I cannot use the function provided in that post, eg:

class Data
{
public Data()
{
//This line will not work
name= MemberInfoGetting.GetMemberName(() => this);
}
public string name{get;set;}

}

Anybody know how I could solve this problem?

Body:
Data number = new Data();
Console.WriteLine(number.name);

In C# 6.0 and above that would be:

SomeNumberClass number = new SomeNumberClass();
Console.WriteLine(nameof(number));

The solution for Pre-C# 6 you linked would work accordingly, you just would not write nameof but use a static method instead:

SomeNumberClass number = new SomeNumberClass();
Console.WriteLine(MemberInfoGetting.GetMemberName(() => number));


问:
How to ignore JSON fields when marshalling not unmarshalling
Assume I have a password field in a User struct.

```<code>type User struct{
   UserName string `json:"username"`
   Password string `json:"-"`
}
</code>```

My clients register their users by posting username and password together. So if I decode JSON to above struct, it ignores password. It's expected. But I wondered is there any way to ignore fields when only marshalling. I checked go official documentation page but couldn't find anything.

https://golang.org/pkg/encoding/json/

I can add an extra field into the struct but I need to know first is it possible to do that with JSON lib.

答:
One common approach is to use a temporary type or variable, with same structure, but different json tags or even different structure:

```<code>type User struct {
    UserName string `json:"username"`
    Password string `json:"password"`
}

func (usr User) MarshalJSON() ([]byte, error) {
    var tmp struct {
        UserName string `json:"username"`
    }
    tmp.UserName = usr.UserName
    return json.Marshal(&tmp)
}
</code>```

Body:
Assume I have a password field in a User struct.

type User struct{
   UserName string `json:"username"`
   Password string `json:"-"`
}

My clients register their users by posting username and password together. So if I decode JSON to above struct, it ignores password. It's expected. But I wondered is there any way to ignore fields when only marshalling. I checked go official documentation page but couldn't find anything.

https://golang.org/pkg/encoding/json/

I can add an extra field into the struct but I need to know first is it possible to do that with JSON lib.

Body:
One common approach is to use a temporary type or variable, with same structure, but different json tags or even different structure:

type User struct {
    UserName string `json:"username"`
    Password string `json:"password"`
}

func (usr User) MarshalJSON() ([]byte, error) {
    var tmp struct {
        UserName string `json:"username"`
    }
    tmp.UserName = usr.UserName
    return json.Marshal(&tmp)
}