问:
What is the minimum number of bits needed to correct all 2 bit errors?
I learned about hamming codes and how to use them to correct 1 bit errors and detect all 2 bit errors, but how extend this to correcting 2 bits, and maybe more?

What is the minimum number of bits needed to correct all 2 bit errors?

答:
I think I figured it out.

N=number of data bits,
k=number error correcting bits(eg parity for hamming)

In any ECC scheme, you have 2^(N+k) possible bit strings.

For single bit error:

You must find k such that the total number of possible bit strings is larger than the possible number of strings with at most 1 bit error for a given string.

The total possible strings with at most 1 bit error is 2^N(n+k+1)

1 string with no error, N+k strings with 1 bit error

2^(N+k)>=(2^N)*(N+k+1)

You simply have to plugin values of k until you find the one that satisfies the above(or however you wish to solve it)

Similarly for 2 bit error, it is

1 string with no error, N+k strings with 1 bit error, N+k choose 2 strings with 2 bit error.

2^(N+k)>=(2^N)*(N+k+1 + (N+k choose 2))


来源: stackexchange

问:
comapare files that are on remote directory and local directory using python
I got a code on this site to download files from remote directory from the server. Now I want modify this code so it compares the files and lists that are on remote directory and not on local directory. It lists the uncommon files between remote directory and local directory .
Is this possible?
Please help.  Thanks in Advance

```<code>import os
import pysftp
import socket
from stat import S_IMODE, S_ISDIR, S_ISREG

cnopts = pysftp.CnOpts()
cnopts.hostkeys = None

IP = "192.168.X.X"
myUsername = "user"
port = 22
myPassword = "password"

try:
    with pysftp.Connection(host=IP, username=myUsername, password=myPassword, cnopts=cnopts) as sftp:
        try:
            r=str(socket.gethostbyaddr(IP))
            print("connection successful with "+r)

            def get_r_portable(sftp, remotedir, localdir, preserve_mtime=False):
                for entry in sftp.listdir(remotedir):
                    remotepath = remotedir + "/" + entry
                    localpath = os.path.join(localdir, entry)
                    mode = sftp.stat(remotepath).st_mode
                    if S_ISDIR(mode):
                        try:
                            os.mkdir(localpath, mode=777)
                        except OSError:
                            pass
                        get_r_portable(sftp, remotepath, localpath, preserve_mtime)
                    elif S_ISREG(mode):
                        sftp.get(remotepath, localpath, preserve_mtime=preserve_mtime)

            remote_path = input("enter the remote_path: ")
            local_path = input("enter the local_path: ")

            get_r_portable(sftp, remote_path, local_path, preserve_mtime=False)
        except socket.herror:
            print("Unknown host")
except:
    print("connection failed")
</code>```

Outcome should be the uncommon files that are present in remote directory and not in local directory.

答:
If you want to download new files and those which are not on your local system, use rsync. you can sync your local directory with the remote one like below:

```<code>rsync -a ~/dir1 username@remote_host:destination_directory
</code>```

How use it in python:

```<code>import subprocess

args = ["rsync", "-av", "-e", "ssh", "user@server:/tmp/", "/home/local/Desktop/"]
subprocess.call(args)
</code>```

you can pass --password-file switch and it must point to a file contains ssh passwords, or you can use ssh key.

ContentLicense: CC BY-SA 4.0

Body:
I got a code on this site to download files from remote directory from the server. Now I want modify this code so it compares the files and lists that are on remote directory and not on local directory. It lists the uncommon files between remote directory and local directory .
Is this possible?
Please help.  Thanks in Advance

import os
import pysftp
import socket
from stat import S_IMODE, S_ISDIR, S_ISREG

cnopts = pysftp.CnOpts()
cnopts.hostkeys = None

IP = "192.168.X.X"
myUsername = "user"
port = 22
myPassword = "password"

try:
    with pysftp.Connection(host=IP, username=myUsername, password=myPassword, cnopts=cnopts) as sftp:
        try:
            r=str(socket.gethostbyaddr(IP))
            print("connection successful with "+r)

            def get_r_portable(sftp, remotedir, localdir, preserve_mtime=False):
                for entry in sftp.listdir(remotedir):
                    remotepath = remotedir + "/" + entry
                    localpath = os.path.join(localdir, entry)
                    mode = sftp.stat(remotepath).st_mode
                    if S_ISDIR(mode):
                        try:
                            os.mkdir(localpath, mode=777)
                        except OSError:
                            pass
                        get_r_portable(sftp, remotepath, localpath, preserve_mtime)
                    elif S_ISREG(mode):
                        sftp.get(remotepath, localpath, preserve_mtime=preserve_mtime)

            remote_path = input("enter the remote_path: ")
            local_path = input("enter the local_path: ")

            get_r_portable(sftp, remote_path, local_path, preserve_mtime=False)
        except socket.herror:
            print("Unknown host")
except:
    print("connection failed")

Outcome should be the uncommon files that are present in remote directory and not in local directory.

Body:
If you want to download new files and those which are not on your local system, use rsync. you can sync your local directory with the remote one like below:

rsync -a ~/dir1 username@remote_host:destination_directory

How use it in python:

import subprocess

args = ["rsync", "-av", "-e", "ssh", "user@server:/tmp/", "/home/local/Desktop/"]
subprocess.call(args)

you can pass --password-file switch and it must point to a file contains ssh passwords, or you can use ssh key.


问:
Getting Absolute Path Of a File From Browser
say that you have a NodeJS server and a ReactJS frontend that both runs in your local machine only. ReactJS and NodeJS communicates through socketio module. In React side you have a file selecting field looks like following.

```<code>  <div>
    Select a file: <input id="fileSelector" type="file" name="myFile"><br><br>
    <input type="submit">
  </div>
</code>```

You want to select a file from the browser and after that NodeJS will process some operations on that file. But in the given code block, input field only stores the name of the file and not the absolute path to it, because browser do not have access to file system. Because of that I can  not tell the NodeJS where the file is so that it can operate on it. What is the best of the bests approach in order to solve this. I do not want to do a trick but make it in the most suitable way. Thanks

答:
The only way you can do this in a browser is for the client to submit the file. Your node server will then perform whatever processing you plan to do with the uploaded file, then you can provide a link for the user to download the new file from your server. This is how most sites handle this.

In node you can use the formidable module to handle files uploaded to your server.

Another option is to build a desktop application. You can use electron to build a client side app in node with access to the file system and you can still use your client code using React.

Body:
say that you have a NodeJS server and a ReactJS frontend that both runs in your local machine only. ReactJS and NodeJS communicates through socketio module. In React side you have a file selecting field looks like following.

    Select a file: <input id="fileSelector" type="file" name="myFile">

    <input type="submit">

You want to select a file from the browser and after that NodeJS will process some operations on that file. But in the given code block, input field only stores the name of the file and not the absolute path to it, because browser do not have access to file system. Because of that I can  not tell the NodeJS where the file is so that it can operate on it. What is the best of the bests approach in order to solve this. I do not want to do a trick but make it in the most suitable way. Thanks


问:
How can I link a static library to a source used as an native library in NDK Android Build
I want to include a static library built for the C++ code provided, I tried linking the static library, but build cannot link the library. I am getting the following error:

undefined reference to 'Test_C_Interface'

I am new to Java NDK/cmake. Please help me with this

This is the cpp code used(native-lib.cpp)

    extern int Test_C_Interface();

    extern "C" JNIEXPORT jstring JNICALL

    Java_com_example_tvgui_MainActivity_stringFromJNI(JNIEnv *env, jobject /* this */) {
        std::string hello = "From C++";

        int ret_val;

        ret_val = Test_C_Interface();

        if(ret_val == 100){
            hello = "From C";
        }
       return env->NewStringUTF(hello.c_str());
    }
```

<p>This is the c code used to make the static library(sample.c/libsample.a)[Library built using NDK ARM-v7a ToolChain]</p>

<pre class="lang-c prettyprint-override"><code>    #include<stdio.h>

    int Test_C_Interface(void)
    {
        printf("Inside C Library\n");

        return 100;
    }
</code>```

This is the cmake file

```<code>    cmake_minimum_required(VERSION 3.4.1)

    add_library(
            native-lib
            SHARED
            native-lib.cpp)

    find_library(
            log-lib
            log)

    target_link_libraries(
            native-lib
            ${log-lib}
            ${CMAKE_CURRENT_SOURCE_DIR}/../../../libs/libsample.a)
</code>```

I need to build a application from like :

```<code>libsample.a
             \
              \
                ====libnative-lib.so + Java = .apk
              /
             /
native-lib.cpp
</code>```

UPDATE
The problem was solved by modifying the code as below :

```<code>extern "C"{
     int Test_C_Interface();
}
</code>```

答:
You can use android-ndk samples as an example (examples below). Here is the link to android dev manuals - explanation of Native libraries. And here is a same question on stack - link.

On ubuntu the path to static/shared libraries are here (it's android-ndk example):

hello-jni/app/src/main/jniLibs/ [processor] / [your library]

[ Including a library, java file ]

```<code>static {
        System.loadLibrary("hello-jni");
}
</code>```

[ Cmake file ]

```<code>cmake_minimum_required(VERSION 3.4.1)

add_library(hello-jni SHARED
            hello-jni.c)

#Include libraries needed for hello-jni lib
target_link_libraries(hello-jni
                      android
                      log)
</code>```

Body:
I want to include a static library built for the C++ code provided, I tried linking the static library, but build cannot link the library. I am getting the following error:

undefined reference to 'Test_C_Interface'

I am new to Java NDK/cmake. Please help me with this

This is the cpp code used(native-lib.cpp)

    extern int Test_C_Interface();

    extern "C" JNIEXPORT jstring JNICALL

    Java_com_example_tvgui_MainActivity_stringFromJNI(JNIEnv *env, jobject /* this */) {
        std::string hello = "From C++";

        int ret_val;

        ret_val = Test_C_Interface();

        if(ret_val == 100){
            hello = "From C";
        }
       return env->NewStringUTF(hello.c_str());
    }

This is the c code used to make the static library(sample.c/libsample.a)[Library built using NDK ARM-v7a ToolChain]

    #include<stdio.h>

    int Test_C_Interface(void)
    {
        printf("Inside C Library\n");

        return 100;
    }

This is the cmake file

    cmake_minimum_required(VERSION 3.4.1)

    add_library(
            native-lib
            SHARED
            native-lib.cpp)

    find_library(
            log-lib
            log)

    target_link_libraries(
            native-lib
            ${log-lib}
            ${CMAKE_CURRENT_SOURCE_DIR}/../../../libs/libsample.a)

I need to build a application from like :

libsample.a
             \
              \
                ====libnative-lib.so + Java = .apk
              /
             /
native-lib.cpp

UPDATE
The problem was solved by modifying the code as below :

extern "C"{
     int Test_C_Interface();
}

Body:
You can use android-ndk samples as an example (examples below). Here is the link to android dev manuals - explanation of Native libraries. And here is a same question on stack - link.

On ubuntu the path to static/shared libraries are here (it's android-ndk example):

hello-jni/app/src/main/jniLibs/ [processor] / [your library]

[ Including a library, java file ]

static {
        System.loadLibrary("hello-jni");
}

[ Cmake file ]

cmake_minimum_required(VERSION 3.4.1)

add_library(hello-jni SHARED
            hello-jni.c)

#Include libraries needed for hello-jni lib
target_link_libraries(hello-jni
                      android
                      log)


问:
Procedure too large error when applying Macro. How can I make it smaller?
So, I want certain columns to show color patterns for their values. From columns A to CD, however I can't select them all, otherwise my sheet will be messed up because the average will be taken from values from all columns and I need it to be calculated individually. My solution? To copy the code from one column and just paste it again and replace for the next column such as code below:

```<code>Sub Macro2()
'
' Macro2 Macro
'

'
    Selection.FormatConditions.AddColorScale ColorScaleType:=3
    Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
    Selection.FormatConditions(1).ColorScaleCriteria(1).Type = _
        xlConditionValueLowestValue
    With Selection.FormatConditions(1).ColorScaleCriteria(1).FormatColor
        .Color = 255
        .TintAndShade = 0
    End With
    Selection.FormatConditions(1).ColorScaleCriteria(2).Type = _
        xlConditionValuePercentile
    Selection.FormatConditions(1).ColorScaleCriteria(2).Value = 50
    With Selection.FormatConditions(1).ColorScaleCriteria(2).FormatColor
        .Color = 5287936
        .TintAndShade = 0
    End With
    Selection.FormatConditions(1).ColorScaleCriteria(3).Type = _
        xlConditionValueHighestValue
    With Selection.FormatConditions(1).ColorScaleCriteria(3).FormatColor
        .Color = 255
        .TintAndShade = 0
    End With
End Sub
Sub Macro3()
'
' Macro3 Macro
'

'
    Columns("B:B").Select
    Selection.FormatConditions.AddColorScale ColorScaleType:=3
    Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
    Selection.FormatConditions(1).ColorScaleCriteria(1).Type = _
        xlConditionValueLowestValue
    With Selection.FormatConditions(1).ColorScaleCriteria(1).FormatColor
        .Color = 255
        .TintAndShade = 0
    End With
    Selection.FormatConditions(1).ColorScaleCriteria(2).Type = _
        xlConditionValuePercentile
    Selection.FormatConditions(1).ColorScaleCriteria(2).Value = 50
    With Selection.FormatConditions(1).ColorScaleCriteria(2).FormatColor
        .Color = 5287936
        .TintAndShade = 0
    End With
    Selection.FormatConditions(1).ColorScaleCriteria(3).Type = _
        xlConditionValueHighestValue
    With Selection.FormatConditions(1).ColorScaleCriteria(3).FormatColor
        .Color = 255
        .TintAndShade = 0
    End With
    Columns("C:C").Select
    Selection.FormatConditions.AddColorScale ColorScaleType:=3
    Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
    Selection.FormatConditions(1).ColorScaleCriteria(1).Type = _
        xlConditionValueLowestValue
    With Selection.FormatConditions(1).ColorScaleCriteria(1).FormatColor
        .Color = 255
        .TintAndShade = 0
    End With
    Selection.FormatConditions(1).ColorScaleCriteria(2).Type = _
        xlConditionValuePercentile
    Selection.FormatConditions(1).ColorScaleCriteria(2).Value = 50
    With Selection.FormatConditions(1).ColorScaleCriteria(2).FormatColor
        .Color = 5287936
        .TintAndShade = 0
    End With
    Selection.FormatConditions(1).ColorScaleCriteria(3).Type = _
        xlConditionValueHighestValue
    With Selection.FormatConditions(1).ColorScaleCriteria(3).FormatColor
        .Color = 255
        .TintAndShade = 0
    End With
...
</code>```

And it goes on and on....

When I tried to run it, I get an error saying "Procedure too large". How can I simplify it?

答:
Use a loop:</p>

```<code>Dim c as Range, fc As ColorScale

For Each c in Range("A1:CD1").Cells

    Set fc = c.EntireColumn.FormatConditions.AddColorScale( _
                                               ColorScaleType:=3)
    fc.SetFirstPriority
    fc.ColorScaleCriteria(1).Type = xlConditionValueLowestValue
    With fc.ColorScaleCriteria(1).FormatColor
        .Color = 255
        .TintAndShade = 0
    End With
    fc.ColorScaleCriteria(2).Type = xlConditionValuePercentile
    fc.ColorScaleCriteria(2).Value = 50
    With fc.ColorScaleCriteria(2).FormatColor
        .Color = 5287936
        .TintAndShade = 0
    End With
    fc.ColorScaleCriteria(3).Type = xlConditionValueHighestValue
    With fc.ColorScaleCriteria(3).FormatColor
        .Color = 255
        .TintAndShade = 0
    End With

Next c
</code>```

Body:
So, I want certain columns to show color patterns for their values. From columns A to CD, however I can't select them all, otherwise my sheet will be messed up because the average will be taken from values from all columns and I need it to be calculated individually. My solution? To copy the code from one column and just paste it again and replace for the next column such as code below:

Sub Macro2()
'
' Macro2 Macro
'

'
    Selection.FormatConditions.AddColorScale ColorScaleType:=3
    Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
    Selection.FormatConditions(1).ColorScaleCriteria(1).Type = _
        xlConditionValueLowestValue
    With Selection.FormatConditions(1).ColorScaleCriteria(1).FormatColor
        .Color = 255
        .TintAndShade = 0
    End With
    Selection.FormatConditions(1).ColorScaleCriteria(2).Type = _
        xlConditionValuePercentile
    Selection.FormatConditions(1).ColorScaleCriteria(2).Value = 50
    With Selection.FormatConditions(1).ColorScaleCriteria(2).FormatColor
        .Color = 5287936
        .TintAndShade = 0
    End With
    Selection.FormatConditions(1).ColorScaleCriteria(3).Type = _
        xlConditionValueHighestValue
    With Selection.FormatConditions(1).ColorScaleCriteria(3).FormatColor
        .Color = 255
        .TintAndShade = 0
    End With
End Sub
Sub Macro3()
'
' Macro3 Macro
'

'
    Columns("B:B").Select
    Selection.FormatConditions.AddColorScale ColorScaleType:=3
    Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
    Selection.FormatConditions(1).ColorScaleCriteria(1).Type = _
        xlConditionValueLowestValue
    With Selection.FormatConditions(1).ColorScaleCriteria(1).FormatColor
        .Color = 255
        .TintAndShade = 0
    End With
    Selection.FormatConditions(1).ColorScaleCriteria(2).Type = _
        xlConditionValuePercentile
    Selection.FormatConditions(1).ColorScaleCriteria(2).Value = 50
    With Selection.FormatConditions(1).ColorScaleCriteria(2).FormatColor
        .Color = 5287936
        .TintAndShade = 0
    End With
    Selection.FormatConditions(1).ColorScaleCriteria(3).Type = _
        xlConditionValueHighestValue
    With Selection.FormatConditions(1).ColorScaleCriteria(3).FormatColor
        .Color = 255
        .TintAndShade = 0
    End With
    Columns("C:C").Select
    Selection.FormatConditions.AddColorScale ColorScaleType:=3
    Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
    Selection.FormatConditions(1).ColorScaleCriteria(1).Type = _
        xlConditionValueLowestValue
    With Selection.FormatConditions(1).ColorScaleCriteria(1).FormatColor
        .Color = 255
        .TintAndShade = 0
    End With
    Selection.FormatConditions(1).ColorScaleCriteria(2).Type = _
        xlConditionValuePercentile
    Selection.FormatConditions(1).ColorScaleCriteria(2).Value = 50
    With Selection.FormatConditions(1).ColorScaleCriteria(2).FormatColor
        .Color = 5287936
        .TintAndShade = 0
    End With
    Selection.FormatConditions(1).ColorScaleCriteria(3).Type = _
        xlConditionValueHighestValue
    With Selection.FormatConditions(1).ColorScaleCriteria(3).FormatColor
        .Color = 255
        .TintAndShade = 0
    End With
...

And it goes on and on....

When I tried to run it, I get an error saying "Procedure too large". How can I simplify it?

Body:
Use a loop:

Dim c as Range, fc As ColorScale

For Each c in Range("A1:CD1").Cells

    Set fc = c.EntireColumn.FormatConditions.AddColorScale( _
                                               ColorScaleType:=3)
    fc.SetFirstPriority
    fc.ColorScaleCriteria(1).Type = xlConditionValueLowestValue
    With fc.ColorScaleCriteria(1).FormatColor
        .Color = 255
        .TintAndShade = 0
    End With
    fc.ColorScaleCriteria(2).Type = xlConditionValuePercentile
    fc.ColorScaleCriteria(2).Value = 50
    With fc.ColorScaleCriteria(2).FormatColor
        .Color = 5287936
        .TintAndShade = 0
    End With
    fc.ColorScaleCriteria(3).Type = xlConditionValueHighestValue
    With fc.ColorScaleCriteria(3).FormatColor
        .Color = 255
        .TintAndShade = 0
    End With

Next c


问:
ElasticSearch Multiword synonyms
I have analyzer with synonyms

```<code>{
  "settings": {
    "analysis": {
      "filter": {
        "synonyms": {
          "type": "synonym",
      "synonyms": [
        "st,str,street",
        "district of columbia,dc"
      ]
    }
      },
      "analyzer": {
        "synonyms": {
          "tokenizer": "standard",
          "filter": [
            "lowercase",
            "synonyms"
          ]
        }
      }
    }
  }
}
</code>```

If I run analysis on "street", it gives me that "st" and "str" are synonyms.

But if I run on "DC", it gives me that "district", "of" and "columbia" are synonyms.

How to make "DC" and "District of Columbia" synonyms ?

答:
You can change your analyzer.tokenizer to "keyword",

```<code>"analyzer": {
    "synonyms": {
      "tokenizer": "keyword",
      "filter": [
        "lowercase",
        "synonyms"
      ]
    }
  }
</code>```

This treats "district of columbia" as a single entity and maps to "DC"

ContentLicense: CC BY-SA 3.0

Title: ElasticSearch Multiword synonyms

Body:
I have analyzer with synonyms

{
  "settings": {
    "analysis": {
      "filter": {
        "synonyms": {
          "type": "synonym",
      "synonyms": [
        "st,str,street",
        "district of columbia,dc"
      ]
    }
      },
      "analyzer": {
        "synonyms": {
          "tokenizer": "standard",
          "filter": [
            "lowercase",
            "synonyms"
          ]
        }
      }
    }
  }
}

If I run analysis on "street", it gives me that "st" and "str" are synonyms.

But if I run on "DC", it gives me that "district", "of" and "columbia" are synonyms.

How to make "DC" and "District of Columbia" synonyms ?

Body:
You can change your analyzer.tokenizer to "keyword",

"analyzer": {
    "synonyms": {
      "tokenizer": "keyword",
      "filter": [
        "lowercase",
        "synonyms"
      ]
    }
  }

This treats "district of columbia" as a single entity and maps to "DC"


问:
Nested Panels / Toolbars in Sencha Touch
I'm trying to create a constant bottom toolbar, which controls a panel above it. Then the panel above it should have a toolbar of its own (at the top). I've attempted the below code, which almost works, but I can't see the html of the sub-page inner panels. I think it's because the panel isn't taking up the remaining height, but I don't know why.

Anyone have any ideas? Thanks!

```<code>Ext.setup({
    onReady: function() {

    // Sub-page sections
    var blah = {
        style: "background-color: #B22222; color:#FF0000;",
        title: "one",
        html: "Why can't I see this html",
        layout:"fit",
        flex: 1
    };
    var blah2 = {
        style: "background-color: #404040; color:#000000;",
        title: "one",
        html: "Why can't I see this html",
        layout:"fit",
        flex: 1
    };

    // Main portion of the page, which includes top toolbar and content
    var page1 = new Ext.TabPanel({
        dock: "bottom",
        layout: "card",
        items: [blah, blah2, blah],
        title: "one",
        flex: 1
    });

    // This is the outer panel with the bottom toolbar
    var wrapper = new Ext.Panel({
        fullscreen: true,
        items: page1,
        dockedItems: [
          {
            xtype: "toolbar",
            dock: "bottom",
            items: [
              {
                iconMask: true,
                iconCls: "download"
              },
              {
                iconMask: true,
                iconCls: "favorites"
              },
              {
                iconMask: true,
                iconCls: "search"
              },
              {
                iconMask: true,
                iconCls: "user"
              }
            ]
          }
        ]
      });
    }
});
</code>```

答:
It sounds like what you are trying to do can be done using a TabPanel, rather than a Toolbar. When you dock the tabBar to the bottom, each tabButton can accept an icon.

I may have misunderstood what you are trying to do, but this should help:

```<code>Ext.setup({
    onReady: function() {

        // Sub-page sections
        var blah = {
            style: "background-color: #B22222; color:#FF0000;",
            title: "one",
            html: "Why can't I see this html",
        };
        var blah2 = {
            style: "background-color: #404040; color:#000000;",
            title: "one",
            html: "Why can't I see this html",
        };

        // Main portion of the page, which includes top toolbar and content
        var page1 = new Ext.TabPanel({
            items: [blah, blah2, blah],
            title: "one",
            iconMask: true,
            iconCls: "download",
        });

        // This is the outer panel with the bottom toolbar
        var wrapper = new Ext.TabPanel({
            fullscreen: true,
            tabBar: {
                dock: 'bottom',
                layout: {
                    pack: 'center'
                }
            },
            items: [
                page1,
                {
                    iconMask: true,
                    iconCls: "favorites"
                },
                {
                    iconMask: true,
                    iconCls: "search"
                },
                {
                    iconMask: true,
                    iconCls: "user"
                }
            ]
        });
    }
});
</code>```

I made a screencast about building a user interface in sencha touch using tabs and toolbars. There's a live demo, and the code is on github, so feel free to use that as a reference.

Body:
I'm trying to create a constant bottom toolbar, which controls a panel above it. Then the panel above it should have a toolbar of its own (at the top). I've attempted the below code, which almost works, but I can't see the html of the sub-page inner panels. I think it's because the panel isn't taking up the remaining height, but I don't know why.

Anyone have any ideas? Thanks!

Ext.setup({
    onReady: function() {

    // Sub-page sections
    var blah = {
        style: "background-color: #B22222; color:#FF0000;",
        title: "one",
        html: "Why can't I see this html",
        layout:"fit",
        flex: 1
    };
    var blah2 = {
        style: "background-color: #404040; color:#000000;",
        title: "one",
        html: "Why can't I see this html",
        layout:"fit",
        flex: 1
    };

    // Main portion of the page, which includes top toolbar and content
    var page1 = new Ext.TabPanel({
        dock: "bottom",
        layout: "card",
        items: [blah, blah2, blah],
        title: "one",
        flex: 1
    });

    // This is the outer panel with the bottom toolbar
    var wrapper = new Ext.Panel({
        fullscreen: true,
        items: page1,
        dockedItems: [
          {
            xtype: "toolbar",
            dock: "bottom",
            items: [
              {
                iconMask: true,
                iconCls: "download"
              },
              {
                iconMask: true,
                iconCls: "favorites"
              },
              {
                iconMask: true,
                iconCls: "search"
              },
              {
                iconMask: true,
                iconCls: "user"
              }
            ]
          }
        ]
      });
    }
});

Body:
It sounds like what you are trying to do can be done using a TabPanel, rather than a Toolbar. When you dock the tabBar to the bottom, each tabButton can accept an icon.

I may have misunderstood what you are trying to do, but this should help:

Ext.setup({
    onReady: function() {

        // Sub-page sections
        var blah = {
            style: "background-color: #B22222; color:#FF0000;",
            title: "one",
            html: "Why can't I see this html",
        };
        var blah2 = {
            style: "background-color: #404040; color:#000000;",
            title: "one",
            html: "Why can't I see this html",
        };

        // Main portion of the page, which includes top toolbar and content
        var page1 = new Ext.TabPanel({
            items: [blah, blah2, blah],
            title: "one",
            iconMask: true,
            iconCls: "download",
        });

        // This is the outer panel with the bottom toolbar
        var wrapper = new Ext.TabPanel({
            fullscreen: true,
            tabBar: {
                dock: 'bottom',
                layout: {
                    pack: 'center'
                }
            },
            items: [
                page1,
                {
                    iconMask: true,
                    iconCls: "favorites"
                },
                {
                    iconMask: true,
                    iconCls: "search"
                },
                {
                    iconMask: true,
                    iconCls: "user"
                }
            ]
        });
    }
});

I made a screencast about building a user interface in sencha touch using tabs and toolbars. There's a live demo, and the code is on github, so feel free to use that as a reference.


问:
Fix Python Guessing Game to not count erroneous tries
Running Python code for guessing game - if guess number outside of range - do not want it to count against tries. Code works but counts erroneous numbers as tries.

My code:

```<code>import random

print("The number is between 1 and 10")
print("You have 5 tries!")

theNumber = random.randrange(1,10)
maxTries = 5
tries = 1
guess = int(input("Take a guess: "))

while ((tries < maxTries) & (guess != theNumber)):
    try:
        if guess > theNumber:
            print("Guess lower...")
        elif guess < theNumber:
            print("Guess higher...")
        if guess > 10:
                raise ValueError

    except ValueError:
            print("Please enter a numeric value between 1 and 10.")
            #continue

    guess = int(input("Guess again: "))
    tries = tries + 1

    if(guess == theNumber):
        print("You guessed it! The number was", theNumber)
        print("And it only took you", tries, "tries!\n")
    else:
        print("You failed to guess", theNumber, "!")
</code>```

It allows continued guessing up to 5 tries as long as guess is between 1 and 10. If outside of this range - it will not count as a try but tells the user to "Please enter a numeric value between 1 and 10"). Which the code does - it just counts those tries when I do not want it to work that way.

答:
Try this one:

import random

min_number = 1
max_number = 10
number = random.randrange(min_number, max_number + 1)
print(number) # To know the number you are guessing
maximum_tries = 5

print(f"The number is between {min_number} and {max_number}")
print(f"You have {maximum_tries} tries!")

guess = int(input("Take a guess: "))

j = 1

while True:

    if guess > max_number or guess < min_number:
        print("Please enter a numeric value between 1 and 10.")
        j = j - 1
    elif guess > number:
        print("Guess lower...")
        print("You failed to guess", j, "!")
    elif guess < number:
        print("Guess higher...")
        print("You failed to guess", j, "!")

    if guess == number:
        print("You guessed it! The number was", number)
        print("And it only took you", j, "tries!\n")
        break

    if j == maximum_tries:
        break

    guess = int(input("Guess again: "))
    j = j + 1
```

Body:
Running Python code for guessing game - if guess number outside of range - do not want it to count against tries. Code works but counts erroneous numbers as tries.

My code:

import random

print("The number is between 1 and 10")
print("You have 5 tries!")

theNumber = random.randrange(1,10)
maxTries = 5
tries = 1
guess = int(input("Take a guess: "))

while ((tries < maxTries) & (guess != theNumber)):
    try:
        if guess > theNumber:
            print("Guess lower...")
        elif guess < theNumber:
            print("Guess higher...")
        if guess > 10:
                raise ValueError

    except ValueError:
            print("Please enter a numeric value between 1 and 10.")
            #continue

    guess = int(input("Guess again: "))
    tries = tries + 1

    if(guess == theNumber):
        print("You guessed it! The number was", theNumber)
        print("And it only took you", tries, "tries!\n")
    else:
        print("You failed to guess", theNumber, "!")

It allows continued guessing up to 5 tries as long as guess is between 1 and 10. If outside of this range - it will not count as a try but tells the user to "Please enter a numeric value between 1 and 10"). Which the code does - it just counts those tries when I do not want it to work that way.


问:
Cannot find module 'wrappy'
while i tried to install gulp from package manager console in visual studio 2015.

npm install gulp

I got error Cannot find module 'wrappy'

答: Do npm update. It worked for me

Title: Cannot find module 'wrappy'

Body: Do npm update. It worked for me


问:
How to autowire a spring bean based on some session info
We are working on a multilingual Spring based web application (not Spring Boot).

Now we are searching for the "spring way" of doing the following.

user starts a http session with some parameters, e.g. a locale "de" and/or a country-code "DE" (the type of parameter isn't really important)

user works with application

at some point the user triggers an action that somewhere deep inside needs a "localized" functionality

Example (java pseudocode):

// service with functionality common for all users
@Service
class CommonService implements ICommonService
{
    // how to autowire a service based on some info in the actual HttpSession, eg. CustomServiceUK or CustomServiceDE
    @Autowired
    private ICustomService customServiceImpl;

    @Override
    public void doSomeAction(String param)
    {
        ... do some common stuff

        customResult = customServiceImpl.calculate(param);

        ... do some common stuff with custom result
    }
}

// custom service implementations
@Service("CustomServiceUK")
class CustomServiceUK implements ICustomService
{
    @Override
    public String calculate(String value)
    {
        ... execute logic on value for an "uk" user
    }
}

@Service("CustomServiceDE")
class CustomServiceDE implements ICustomService
{
    @Override
    public String calculate(String value)
    {
        ... execute logic on value for an "de" user
    }
}
```

How to inject a custom service based on some info in the actual HttpSession (e.g. CustomServiceUK or CustomServiceDE) into CommonService?
What are our options to solve this issue? Is there something like a dynamic @Qualifier or some @Autowired Spring-Factory thing?

(the service implementation to use must not necessarily depend on the locale of the user but on some other piece of session/request information)

答:
Thanks for your answers.

Actually we end up with the following solution which works for us.

We created an additional implementation of ICustomService with name CustomServiceProxy.
This service has @Primary annotation to tell Spring that this component should be injected when no explicit qualifier is supplied.
The service gets the sessionData and a Map with all Spring managed ICustomService-Components injected (Map-Key = Qualifier of the Component).
Now when some method on CustomServiceProxy gets called, it generates the Map-Key based on the actual sessionData (e.g. language), lookup the ICustomService in the Map and delegates the call to this specific service.

// service with functionality common for all users
@Service
class CommonService implements ICommonService
{
    // because of @Primary an instance of CustomServiceProxy will be injected
    @Autowired
    private ICustomService customServiceImpl;

    @Override
    public void doSomeAction(String param)
    {
        ... do some common stuff

        customResult = customServiceImpl.calculate(param);

        ... do some common stuff with custom result
    }
}

// custom service implementations
@Service
@Primary
class CustomServiceProxy implements ICustomService
{
    private CustomData sessionData;
    private Map<String, ICustomService> services;

    @Autowired
    public CustomServiceProxy(CustomData sessionData, Map<String, ICustomService> services)
    {
        this.sessionData = sessionData;
        this.services = services;
    }

    @Override
    public String calculate(String value)
    {
        String serviceName = "CustomService" + sessionData.getLanguage().toUpperCase();
        ICustomService customService = services.get(serviceName);
        // handle missing service: throw exception or maybe switch to a default implementation
        Objects.requireNonNull(customService, "missing CustomService with name " + serviceName);
        return customService.calculate(value);
    }
}

@Service("CustomServiceUK")
class CustomServiceUK implements ICustomService
{
    @Override
    public String calculate(String value)
    {
        ... execute logic on value for an "uk" user
    }
}

@Service("CustomServiceDE")
class CustomServiceDE implements ICustomService
{
    @Override
    public String calculate(String value)
    {
        ... execute logic on value for an "de" user
    }
}
```

Body:
We are working on a multilingual Spring based web application (not Spring Boot).

Now we are searching for the "spring way" of doing the following.

user starts a http session with some parameters, e.g. a locale "de" and/or a country-code "DE" (the type of parameter isn't really important)

user works with application

at some point the user triggers an action that somewhere deep inside needs a "localized" functionality

Example (java pseudocode):

// service with functionality common for all users
@Service
class CommonService implements ICommonService
{
    // how to autowire a service based on some info in the actual HttpSession, eg. CustomServiceUK or CustomServiceDE
    @Autowired
    private ICustomService customServiceImpl;

    @Override
    public void doSomeAction(String param)
    {
        ... do some common stuff

        customResult = customServiceImpl.calculate(param);

        ... do some common stuff with custom result
    }
}

// custom service implementations
@Service("CustomServiceUK")
class CustomServiceUK implements ICustomService
{
    @Override
    public String calculate(String value)
    {
        ... execute logic on value for an "uk" user
    }
}

@Service("CustomServiceDE")
class CustomServiceDE implements ICustomService
{
    @Override
    public String calculate(String value)
    {
        ... execute logic on value for an "de" user
    }
}

How to inject a custom service based on some info in the actual HttpSession (e.g. CustomServiceUK or CustomServiceDE) into CommonService?
What are our options to solve this issue? Is there something like a dynamic @Qualifier or some @Autowired Spring-Factory thing?

(the service implementation to use must not necessarily depend on the locale of the user but on some other piece of session/request information)


问:
change default font SSRS Visual Studio
I have been searching hi and lo, within and outside internet but it seems I cannot find a definitive answer:
Can I change the default layout-items in SSRS reports? If so, how?

So that a textbox does not have Arial 10 as default fontsize but has fontsize 8?

So that tablixes have default properties like 'show column-headers on each page' enabled?

and so on?

I am familiar with custom templates (.rdl) but they do not offer the possibility of changing layout-items like default font and colors and properties of report parts and such.

In VS 2005 there was the StyleTemplate to play with but that is only effective when using the wizard.
It seems it is the same way with VS 2010.

I prefer to hear that it can be done and instructions how to, I would be satisfied with tips how to circumvent the problem of manually changing those properties eacht time and I will be grateful for a definitive answer. Right now it is driving me crazy :)

I am working with VS2010 (latest updates and such) icm SQL 2008, 2008R2 and (local) 2012BI

Thanks for thinking with me!

答: The FontSize property must be in npt format. If this property takes the value from an SQL query that returns an integer, add the expression by adding "pt": (for example, = Fields! DimFont.Value & "pt").

Title: change default font SSRS Visual Studio


问:
Action Controller: Exception when refreshing page
I'm having a problem when refreshing the page to my custom controller action. Everytime I refresh the page after executing the action for the first time I get an ActiveRecord::RecordNotFound exception.

I wrote theses custom queries in actions in my controller, them I added the path to this actions in my routes.rb
This is the URL I'm accessing: http://localhost:3000/health_units/especialidades?specialty=ENFASE
It works fine when accessed from the index page, but if I try to refresh the page or even type it I get this error.

This is my controller:

class HealthUnitsController < ApplicationController
  before_action :set_health_unit, only: [:show, :edit, :update, :destroy]

  # GET /health_units
  # GET /health_units.json
  def index
    @health_units = HealthUnit.all
  end

  # GET /health_units/1
  # GET /health_units/1.json
  def show
  end

  # GET /health_units/new
  def new
    @health_unit = HealthUnit.new
  end

  # GET /health_units/1/edit
  def edit
  end

  # POST /health_units
  # POST /health_units.json
  def create
    @health_unit = HealthUnit.new(health_unit_params)

    respond_to do |format|
      if @health_unit.save
        format.html { redirect_to @health_unit, notice: 'Health unit was successfully created.' }
        format.json { render :show, status: :created, location: @health_unit }
      else
        format.html { render :new }
        format.json { render json: @health_unit.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /health_units/1
  # PATCH/PUT /health_units/1.json
  def update
    respond_to do |format|
      if @health_unit.update(health_unit_params)
        format.html { redirect_to @health_unit, notice: 'Health unit was successfully updated.' }
        format.json { render :show, status: :ok, location: @health_unit }
      else
        format.html { render :edit }
        format.json { render json: @health_unit.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /health_units/1
  # DELETE /health_units/1.json
  def destroy
    @health_unit.destroy
    respond_to do |format|
      format.html { redirect_to health_units_url, notice: 'Health unit was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  def basic_search
    if params[:keywords].empty?
      redirect_to health_units_path
    else
      @health_units = HealthUnit.where("specialties && :kw or
        treatments && :kw", kw: params[:keywords].split(' '))
      respond_to do |format|
        format.html { render template: "health_units/index.html.slim" }
        format.json { render template: "health_units/index.json.jbuilder"}
      end
    end
  end

  def list_by_specialties
    if params[:specialty].nil?
      redirect_to health_units_path
    else
      @specialty = params[:specialty]
      @health_units = HealthUnit.where("specialties && ARRAY[?]",
        @specialty)
      respond_to do |format|
        format.html { render template: "health_units/specialty.html.slim" }
        format.json { render template: "health_units/index.json.jbuilder"}
      end
    end
  end

  def list_by_treatments
    if params[:treatments].empty?
      redirect_to health_units_path
    else
      @health_unit = HealthUnit.where("treatments && ?",
        params[:treatments].split(' '))
      respond_to do |format|
        format.html { render template: "health_units/index.html.slim" }
        format.json { render template: "health_units/index.json.jbuilder"}
      end
    end
  end

  def search_by_neighborhood
    if params[:neighborhood].nil?
      redirect_to health_units_path
    else
      @health_units = HealthUnit.where(neighborhood: params[:neighborhood])
      respond_to do |format|
        format.html { render template: "health_units/index.html.slim" }
        format.json { render template: "health_units/index.json.jbuilder"}
      end
    end
  end

  def advanced_search
    @health_unit = HealthUnit.new
  end

  def advanced_search_results
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_health_unit
      @health_unit = HealthUnit.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def health_unit_params
      params.require(:health_unit).permit(:cnes, :name, :address, :neighborhood, :phone, :latitude, :longitude, :description)
    end

end

```

<p>This is my <code>routes.rb</code>:</p>

<pre class="lang-rb prettyprint-override"><code>  resources :health_units do
    collection do
      resources :comments, path: 'comentarios'
      post :basic_search, path: 'resultados'
      post :advanced_search, path: 'pesquisar'
      post :list_by_specialties, path: 'especialidades', as: :specialty
      post :list_by_treatments, path: 'atendimentos', as: :treatments
      post :search_by_neighborhood, path: 'bairro', as: :neighborhood
    end
</code>```

And this is the error I get in my console:

```<code>Started GET "/health_units/especialidades?specialty=ENFASE" for 127.0.0.1 at 2019-05-27 03:29:07 -0300
Processing by HealthUnitsController#show as HTML
  Parameters: {"specialty"=>"ENFASE", "id"=>"especialidades"}
  HealthUnit Load (0.5ms)  SELECT  "health_units".* FROM "health_units" WHERE "health_units"."id" = $1 LIMIT $2  [["id", 0], ["LIMIT", 1]]
  ↳ app/controllers/health_units_controller.rb:127
Completed 404 Not Found in 3ms (ActiveRecord: 0.5ms)

ActiveRecord::RecordNotFound (Couldn't find HealthUnit with 'id'=especialidades):

app/controllers/health_units_controller.rb:127:in `set_health_unit'
Started GET "/favicon.ico" for 127.0.0.1 at 2019-05-27 03:29:07 -0300

ActionController::RoutingError (No route matches [GET] "/favicon.ico"):

actionpack (5.2.3) lib/action_dispatch/middleware/debug_exceptions.rb:65:in `call'
actionpack (5.2.3) lib/action_dispatch/middleware/show_exceptions.rb:33:in `call'
railties (5.2.3) lib/rails/rack/logger.rb:38:in `call_app'
railties (5.2.3) lib/rails/rack/logger.rb:26:in `block in call'
activesupport (5.2.3) lib/active_support/tagged_logging.rb:71:in `block in tagged'
activesupport (5.2.3) lib/active_support/tagged_logging.rb:28:in `tagged'
activesupport (5.2.3) lib/active_support/tagged_logging.rb:71:in `tagged'
railties (5.2.3) lib/rails/rack/logger.rb:26:in `call'
actionpack (5.2.3) lib/action_dispatch/middleware/remote_ip.rb:81:in `call'
actionpack (5.2.3) lib/action_dispatch/middleware/request_id.rb:27:in `call'
rack (2.0.7) lib/rack/method_override.rb:22:in `call'
rack (2.0.7) lib/rack/runtime.rb:22:in `call'
activesupport (5.2.3) lib/active_support/cache/strategy/local_cache_middleware.rb:29:in `call'
actionpack (5.2.3) lib/action_dispatch/middleware/executor.rb:14:in `call'
actionpack (5.2.3) lib/action_dispatch/middleware/static.rb:127:in `call'
rack (2.0.7) lib/rack/sendfile.rb:111:in `call'
railties (5.2.3) lib/rails/engine.rb:524:in `call'
puma (3.12.1) lib/puma/configuration.rb:227:in `call'
puma (3.12.1) lib/puma/server.rb:660:in `handle_request'
puma (3.12.1) lib/puma/server.rb:474:in `process_client'
puma (3.12.1) lib/puma/server.rb:334:in `block in run'
puma (3.12.1) lib/puma/thread_pool.rb:135:in `block in spawn_thread'
</code>```

I would like to be able to refresh the page and get the same result as the first time I accessed it.

答:
The request is going as GET request.

```<code>Started GET "/health_units/especialidades?specialty=ENFASE" for 127.0.0.1 at 2019-05-27 03:29:07 -0300
Processing by HealthUnitsController#show as HTML
</code>```

rails is expecting it as a POST request as per the route defined

```<code>post :list_by_specialties, path: 'especialidades', as: :specialty
</code>```

So, instead of matching HealthUnitsController#list_by_specialties it's matching the route for HealthUnitsController#show

You ned to look why your request is going as GET and not POST. Once you fix that it will work properly

The reason you're getting the ActiveRecord::RecordNotFound error

```<code>ActiveRecord::RecordNotFound (Couldn't find HealthUnit with 'id'=especialidades):
</code>```

Because it's trying to find HealthUnit with id especialidades.to_i whic returns 0 and since there is no record with id = 0 you get the ActiveRecord::RecordNotFound error

Body:
I'm having a problem when refreshing the page to my custom controller action. Everytime I refresh the page after executing the action for the first time I get an ActiveRecord::RecordNotFound exception.

I wrote theses custom queries in actions in my controller, them I added the path to this actions in my routes.rb
This is the URL I'm accessing: http://localhost:3000/health_units/especialidades?specialty=ENFASE
It works fine when accessed from the index page, but if I try to refresh the page or even type it I get this error.

This is my controller:

class HealthUnitsController < ApplicationController
  before_action :set_health_unit, only: [:show, :edit, :update, :destroy]

  # GET /health_units
  # GET /health_units.json
  def index
    @health_units = HealthUnit.all
  end

  # GET /health_units/1
  # GET /health_units/1.json
  def show
  end

  # GET /health_units/new
  def new
    @health_unit = HealthUnit.new
  end

  # GET /health_units/1/edit
  def edit
  end

  # POST /health_units
  # POST /health_units.json
  def create
    @health_unit = HealthUnit.new(health_unit_params)

    respond_to do |format|
      if @health_unit.save
        format.html { redirect_to @health_unit, notice: 'Health unit was successfully created.' }
        format.json { render :show, status: :created, location: @health_unit }
      else
        format.html { render :new }
        format.json { render json: @health_unit.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /health_units/1
  # PATCH/PUT /health_units/1.json
  def update
    respond_to do |format|
      if @health_unit.update(health_unit_params)
        format.html { redirect_to @health_unit, notice: 'Health unit was successfully updated.' }
        format.json { render :show, status: :ok, location: @health_unit }
      else
        format.html { render :edit }
        format.json { render json: @health_unit.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /health_units/1
  # DELETE /health_units/1.json
  def destroy
    @health_unit.destroy
    respond_to do |format|
      format.html { redirect_to health_units_url, notice: 'Health unit was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  def basic_search
    if params[:keywords].empty?
      redirect_to health_units_path
    else
      @health_units = HealthUnit.where("specialties && :kw or
        treatments && :kw", kw: params[:keywords].split(' '))
      respond_to do |format|
        format.html { render template: "health_units/index.html.slim" }
        format.json { render template: "health_units/index.json.jbuilder"}
      end
    end
  end

  def list_by_specialties
    if params[:specialty].nil?
      redirect_to health_units_path
    else
      @specialty = params[:specialty]
      @health_units = HealthUnit.where("specialties && ARRAY[?]",
        @specialty)
      respond_to do |format|
        format.html { render template: "health_units/specialty.html.slim" }
        format.json { render template: "health_units/index.json.jbuilder"}
      end
    end
  end

  def list_by_treatments
    if params[:treatments].empty?
      redirect_to health_units_path
    else
      @health_unit = HealthUnit.where("treatments && ?",
        params[:treatments].split(' '))
      respond_to do |format|
        format.html { render template: "health_units/index.html.slim" }
        format.json { render template: "health_units/index.json.jbuilder"}
      end
    end
  end

  def search_by_neighborhood
    if params[:neighborhood].nil?
      redirect_to health_units_path
    else
      @health_units = HealthUnit.where(neighborhood: params[:neighborhood])
      respond_to do |format|
        format.html { render template: "health_units/index.html.slim" }
        format.json { render template: "health_units/index.json.jbuilder"}
      end
    end
  end

  def advanced_search
    @health_unit = HealthUnit.new
  end

  def advanced_search_results
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_health_unit
      @health_unit = HealthUnit.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def health_unit_params
      params.require(:health_unit).permit(:cnes, :name, :address, :neighborhood, :phone, :latitude, :longitude, :description)
    end

end

This is my routes.rb:

  resources :health_units do
    collection do
      resources :comments, path: 'comentarios'
      post :basic_search, path: 'resultados'
      post :advanced_search, path: 'pesquisar'
      post :list_by_specialties, path: 'especialidades', as: :specialty
      post :list_by_treatments, path: 'atendimentos', as: :treatments
      post :search_by_neighborhood, path: 'bairro', as: :neighborhood
    end

And this is the error I get in my console:

Started GET "/health_units/especialidades?specialty=ENFASE" for 127.0.0.1 at 2019-05-27 03:29:07 -0300
Processing by HealthUnitsController#show as HTML
  Parameters: {"specialty"=>"ENFASE", "id"=>"especialidades"}
  HealthUnit Load (0.5ms)  SELECT  "health_units".* FROM "health_units" WHERE "health_units"."id" = $1 LIMIT $2  [["id", 0], ["LIMIT", 1]]
  ↳ app/controllers/health_units_controller.rb:127
Completed 404 Not Found in 3ms (ActiveRecord: 0.5ms)

ActiveRecord::RecordNotFound (Couldn't find HealthUnit with 'id'=especialidades):

app/controllers/health_units_controller.rb:127:in `set_health_unit'
Started GET "/favicon.ico" for 127.0.0.1 at 2019-05-27 03:29:07 -0300

ActionController::RoutingError (No route matches [GET] "/favicon.ico"):

actionpack (5.2.3) lib/action_dispatch/middleware/debug_exceptions.rb:65:in `call'
actionpack (5.2.3) lib/action_dispatch/middleware/show_exceptions.rb:33:in `call'
railties (5.2.3) lib/rails/rack/logger.rb:38:in `call_app'
railties (5.2.3) lib/rails/rack/logger.rb:26:in `block in call'
activesupport (5.2.3) lib/active_support/tagged_logging.rb:71:in `block in tagged'
activesupport (5.2.3) lib/active_support/tagged_logging.rb:28:in `tagged'
activesupport (5.2.3) lib/active_support/tagged_logging.rb:71:in `tagged'
railties (5.2.3) lib/rails/rack/logger.rb:26:in `call'
actionpack (5.2.3) lib/action_dispatch/middleware/remote_ip.rb:81:in `call'
actionpack (5.2.3) lib/action_dispatch/middleware/request_id.rb:27:in `call'
rack (2.0.7) lib/rack/method_override.rb:22:in `call'
rack (2.0.7) lib/rack/runtime.rb:22:in `call'
activesupport (5.2.3) lib/active_support/cache/strategy/local_cache_middleware.rb:29:in `call'
actionpack (5.2.3) lib/action_dispatch/middleware/executor.rb:14:in `call'
actionpack (5.2.3) lib/action_dispatch/middleware/static.rb:127:in `call'
rack (2.0.7) lib/rack/sendfile.rb:111:in `call'
railties (5.2.3) lib/rails/engine.rb:524:in `call'
puma (3.12.1) lib/puma/configuration.rb:227:in `call'
puma (3.12.1) lib/puma/server.rb:660:in `handle_request'
puma (3.12.1) lib/puma/server.rb:474:in `process_client'
puma (3.12.1) lib/puma/server.rb:334:in `block in run'
puma (3.12.1) lib/puma/thread_pool.rb:135:in `block in spawn_thread'

I would like to be able to refresh the page and get the same result as the first time I accessed it.

Body:
The request is going as GET request.

Started GET "/health_units/especialidades?specialty=ENFASE" for 127.0.0.1 at 2019-05-27 03:29:07 -0300
Processing by HealthUnitsController#show as HTML

rails is expecting it as a POST request as per the route defined

post :list_by_specialties, path: 'especialidades', as: :specialty

So, instead of matching HealthUnitsController#list_by_specialties it's matching the route for HealthUnitsController#show

You ned to look why your request is going as GET and not POST. Once you fix that it will work properly

The reason you're getting the ActiveRecord::RecordNotFound error

ActiveRecord::RecordNotFound (Couldn't find HealthUnit with 'id'=especialidades):

Because it's trying to find HealthUnit with id especialidades.to_i whic returns 0 and since there is no record with id = 0 you get the ActiveRecord::RecordNotFound error


问:
How to implement an optional callback from scratch in Kotlin?
I have this function, which works wonderfully.

```<code>inline fun <reified T:Any>String.parse() : T {
    return GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create().fromJson<T>(this, T::class.java)
}

fun request (callback: (MyClass)->Unit) {
    val url = URL("someurl").readText()
    val myObject : MyClass = str.parse()
    callback(myObject)
}

net.request {
    it.myFunction()
    println (it.myString)
}
</code>```

myObject automatically filled with an object of type MyClass, and returned correctly to the callback.

Now I want to catch the error, and have the callback can return it as well.

```<code>fun request (callback: (MyClass?, Exception?)->Unit) {
    try {
        val url = URL("someurl").readText()
        val myObject : MyClass = str.parse()
        callback(myObject, null)
    }
    catch (e: Exception) {
        callback(null, e)
    }
}

net.request { response, error ->
    if (response != null ) { // do something }
    else { // report something }
}
</code>```

But this is ugly, because no matter what, I will have to force the callback to always have two parameters, but only one is present at a time. So I'm searching for optional callback methods. I want to be able to call the method like this:

```<code>net.request {
    onSuccess { response -> // do something }
    onError { error -> // report something }
}
</code>```

Or probably:

```<code>net.request
    .onSuccess { response -> // do something }
    .onError { error -> // report something }
</code>```

If I don't want to handle the error, I simply make a call like this:

```<code>net.request {
    onSuccess { // do something with 'it' }
}
</code>```

What I can found over the internet is overwriting the existing callback methods like this. This is not what I want. I want to write that callback from scratch. Looking at the source code sometimes doesn't help either because the code is in Java, and I don't understand Java. Not yet.

And I understand that major library in Kotlin like retrofit or JavaRx probably already implement something like this, but I just want to know the bare minimum code needed to do this, as this is how I learn. I just can't find the correct tutorial for this.

答:
You can try this library out. It helps model success/failure operations concisely. Your callback can then take in your MyClass object wrapped this way Result<MyClass, Exception> or just Result.

To pass a value to your callback, you then do Callback(Result.of(MyClass)) for a successful operation or a Callback(Result.of(Exception())) in case of a failure.

You can then consume the callback by using any of the functions below

```<code>//if successful
result.success {
}

//if failed
result.failure {
}

//fold is there, if you want to handle both success and failure
result.fold({ value ->
    //do something with value
}, { error ->
    //do something with error
})
</code>```

Hope this helps :)

Edit: As @user2340612 pointed out, Result has been added to the Kotlin stdlib. See here for more details

Body:
I have this function, which works wonderfully.

inline fun <reified T:Any>String.parse() : T {
    return GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create().fromJson<T>(this, T::class.java)
}

fun request (callback: (MyClass)->Unit) {
    val url = URL("someurl").readText()
    val myObject : MyClass = str.parse()
    callback(myObject)
}

net.request {
    it.myFunction()
    println (it.myString)
}

myObject automatically filled with an object of type MyClass, and returned correctly to the callback.

Now I want to catch the error, and have the callback can return it as well.

fun request (callback: (MyClass?, Exception?)->Unit) {
    try {
        val url = URL("someurl").readText()
        val myObject : MyClass = str.parse()
        callback(myObject, null)
    }
    catch (e: Exception) {
        callback(null, e)
    }
}

net.request { response, error ->
    if (response != null ) { // do something }
    else { // report something }
}

But this is ugly, because no matter what, I will have to force the callback to always have two parameters, but only one is present at a time. So I'm searching for optional callback methods. I want to be able to call the method like this:

net.request {
    onSuccess { response -> // do something }
    onError { error -> // report something }
}

Or probably:

net.request
    .onSuccess { response -> // do something }
    .onError { error -> // report something }

If I don't want to handle the error, I simply make a call like this:

net.request {
    onSuccess { // do something with 'it' }
}

What I can found over the internet is overwriting the existing callback methods like this. This is not what I want. I want to write that callback from scratch. Looking at the source code sometimes doesn't help either because the code is in Java, and I don't understand Java. Not yet.

And I understand that major library in Kotlin like retrofit or JavaRx probably already implement something like this, but I just want to know the bare minimum code needed to do this, as this is how I learn. I just can't find the correct tutorial for this.

Body:
You can try this library out. It helps model success/failure operations concisely. Your callback can then take in your MyClass object wrapped this way Result<MyClass, Exception> or just Result.

To pass a value to your callback, you then do Callback(Result.of(MyClass)) for a successful operation or a Callback(Result.of(Exception())) in case of a failure.

You can then consume the callback by using any of the functions below

//if successful
result.success {
}

//if failed
result.failure {
}

//fold is there, if you want to handle both success and failure
result.fold({ value ->
    //do something with value
}, { error ->
    //do something with error
})

Hope this helps :)

Edit: As @user2340612 pointed out, Result has been added to the Kotlin stdlib. See here for more details


问:
How to check if an array index exists or not in javascript?
I am working with Titanium, my code looks like this:

```<code>var currentData = new Array();
if(currentData[index]!==""||currentData[index]!==null||currentData[index]!=='null')
{
    Ti.API.info("is exists  " + currentData[index]);
    return true;
}
else
{
    return false;
}
</code>```

I am passing an index to the currentData array. I still can't detect a non-existing index using the above code.

答:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
if(fruits.indexOf("Banana") == -1){
    console.log('item not exist')
} else {
 console.log('item exist')
}```

Body:
I am working with Titanium, my code looks like this:

var currentData = new Array();
if(currentData[index]!==""||currentData[index]!==null||currentData[index]!=='null')
{
    Ti.API.info("is exists  " + currentData[index]);
    return true;
}
else
{
    return false;
}

I am passing an index to the currentData array. I still can't detect a non-existing index using the above code.


问:
Eclipse RCP retrieve compilation errors
I'm developing an eclipse rcp. When i run a project, it is first builded and then launched. If the builder failed to compile the project, then i have to notify the user about that.

Which is the better way to know if there were errors during compilation?

thanks

答:
The solution was contained in the api of IncrementalProjectBuilder in the build method:

Throws:
      CoreException - if this build fails.

I have to throw an exception when the builder failed.

Title: Eclipse RCP retrieve compilation errors


问:
I can't get my custom fonts to work with Xamarin.Forms
I created this resource:

```<code><?xml version="1.0" encoding="utf-8"?> <Application xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="CustomFrameApp.App">
    <Application.Resources>
        <ResourceDictionary>
            <OnPlatform x:TypeArguments="x:String" x:Key="NewFont">
                <On Platform="iOS" Value="Camber_Medium_Regular" />
            </OnPlatform>
        </ResourceDictionary>
    </Application.Resources> </Application>
</code>```

added to info.plist

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>UIAppFonts</key>
    <array>
        <string>Camber_Medium_Regular.otf</string>
    </array>
</dict>
</plist>
</code>```

and used in my XAML

```<code><Label FontSize="12px" Text="ABCD" TextColor="Black" VerticalOptions="Center" HorizontalOptions="Center" FontFamily="{StaticResource NewFont}" />
</code>```

But the fonts are still not being used

I added them as bundle resource as suggested and they are in the resource file of iOS

Does anyone have any idea what might be wrong?

答:
According to Fonts in Xamarin.Forms, please confirm three things:

If you have added font file tat called Camber_Medium_Regular.ttf in Resource file , and Build Action:BundleResource

2.Update the Info.plist, like this:

```<code>    <key>UIAppFonts</key>
<array>
    <string>Camber_Medium_Regular.ttf</string>
</array>
</code>```

3.Refer to it by name

```<code><OnPlatform x:TypeArguments="x:String">
                <On Platform="iOS" Value="Camber_Medium_Regular" />
                <On Platform="Android" Value="Lobster-Regular.ttf#Lobster-Regular" />
                <On Platform="UWP" Value="Assets/Fonts/Lobster-Regular.ttf#Lobster" />
            </OnPlatform>
</code>```

Body:
I created this resource:

<?xml version="1.0" encoding="utf-8"?> <Application xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="CustomFrameApp.App">
    <Application.Resources>
        <ResourceDictionary>
            <OnPlatform x:TypeArguments="x:String" x:Key="NewFont">
                <On Platform="iOS" Value="Camber_Medium_Regular" />
            </OnPlatform>
        </ResourceDictionary>
    </Application.Resources> </Application>

added to info.plist

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>UIAppFonts</key>
    <array>
        <string>Camber_Medium_Regular.otf</string>
    </array>
</dict>
</plist>

and used in my XAML

But the fonts are still not being used

I added them as bundle resource as suggested and they are in the resource file of iOS

Does anyone have any idea what might be wrong?

Body:
According to Fonts in Xamarin.Forms, please confirm three things:

If you have added font file tat called Camber_Medium_Regular.ttf in Resource file , and Build Action:BundleResource

2.Update the Info.plist, like this:

    <key>UIAppFonts</key>
<array>
    <string>Camber_Medium_Regular.ttf</string>
</array>

3.Refer to it by name

<OnPlatform x:TypeArguments="x:String">
                <On Platform="iOS" Value="Camber_Medium_Regular" />
                <On Platform="Android" Value="Lobster-Regular.ttf#Lobster-Regular" />
                <On Platform="UWP" Value="Assets/Fonts/Lobster-Regular.ttf#Lobster" />
            </OnPlatform>


问:
Jenkins Pipeline still executes following stages even though current stage failed
I'm implementing a try catch block on most of my stages inside my jenkins pipeline to skip all the following stages when the current stage fails however, one of my stages is returning an error but still continues to execute the next stages.

I've tried using sh 'exit 1', currentStage.result = 'FAILED', if else clause to check the stage result but to no avail.

pipeline {
 agent none
 stages {
  stage ('one') {
   steps {
    echo 'Next stage should be skipped if this stage fails'
    script {
     try {
      sh '''#!/bin/bash -l
      source ~/.nvm/nvm.sh
      nvm use node
      node somefile.js'''
     }
     catch (e) {
      currentBuild.result = 'FAILURE';
      throw e
     }
    }
   }
   }
  stage ('two') {
   steps {
    echo 'This stage should be skipped if prior stage throws an erorr'
   }
  }
 }
}```

I expect stage two to be skipped as my somefile.js is throwing an error.

答:
You can use the when-clause that Jenkins provides (Source).

```<code>    stage ('two') {
        // Skip this stage if pipeline has already failed
        when { not { equals expected: 'FAILURE', actual: currentBuild.result } }
        steps {
            echo 'This stage should be skipped if prior stage throws an erorr'
        }
    }
</code>```

Body:
I'm implementing a try catch block on most of my stages inside my jenkins pipeline to skip all the following stages when the current stage fails however, one of my stages is returning an error but still continues to execute the next stages.

I've tried using sh 'exit 1', currentStage.result = 'FAILED', if else clause to check the stage result but to no avail.

pipeline {
 agent none
 stages {
  stage ('one') {
   steps {
    echo 'Next stage should be skipped if this stage fails'
    script {
     try {
      sh '''#!/bin/bash -l
      source ~/.nvm/nvm.sh
      nvm use node
      node somefile.js'''
     }
     catch (e) {
      currentBuild.result = 'FAILURE';
      throw e
     }
    }
   }
   }
  stage ('two') {
   steps {
    echo 'This stage should be skipped if prior stage throws an erorr'
   }
  }
 }
}

I expect stage two to be skipped as my somefile.js is throwing an error.

Body:
You can use the when-clause that Jenkins provides (Source).

    stage ('two') {
        // Skip this stage if pipeline has already failed
        when { not { equals expected: 'FAILURE', actual: currentBuild.result } }
        steps {
            echo 'This stage should be skipped if prior stage throws an erorr'
        }
    }


问:
Return a new string where everth xth character (starting at 0) is now followed by *?
I wanna write a function that takes a string, s, and an int, x. It should return a new string where every xth character (starting from zero) is now followed by an '*'.

So far I've tried this code:

```<code>def string_chunks(string, x):
    """
    >>> string_chunks("Once upon a time, in a land far, far away", 5)
    'O*nce u*pon a* time*, in *a lan*d far*, far* away*'
    """
    for ch in string:
        return ch + "*"
</code>```

but I am very stuck and am unable to make it work.
I would appreciate any help. If you provide an answer, it would be nice if you could comment the code also.

答:
Currently you do this:

```<code>for ch in string:
        return ch + "*"
</code>```

This immediately exists the function. Instead, you want to create the whole string by doing something like this:

```<code>chunked_text = chunked_text + ch + "*"
</code>```

and only after iterating over the whole string you want to return it.

Body:
I wanna write a function that takes a string, s, and an int, x. It should return a new string where every xth character (starting from zero) is now followed by an '*'.

So far I've tried this code:

def string_chunks(string, x):
    """
    >>> string_chunks("Once upon a time, in a land far, far away", 5)
    'O*nce u*pon a* time*, in *a lan*d far*, far* away*'
    """
    for ch in string:
        return ch + "*"

but I am very stuck and am unable to make it work.
I would appreciate any help. If you provide an answer, it would be nice if you could comment the code also.

Body:
Currently you do this:

for ch in string:
        return ch + "*"

This immediately exists the function. Instead, you want to create the whole string by doing something like this:

chunked_text = chunked_text + ch + "*"

and only after iterating over the whole string you want to return it.


问:
Discrete Fourier Transform OpenCV not working on Android
i'm trying to convert and display an image made with Core.dft() on Android but it keeps crashing at the line I call Core.dft().

Here is my code:

```<code>private Mat getDFT(Mat singleChannel) {

    singleChannel.convertTo(singleChannel, CvType.CV_64FC1);

    int m = Core.getOptimalDFTSize(singleChannel.rows());
    int n = Core.getOptimalDFTSize(singleChannel.cols()); // on the border
    // add zero
    // values
    // Imgproc.copyMakeBorder(image1,
    // padded, 0, m -
    // image1.rows(), 0, n

    Mat padded = new Mat(new Size(n, m), CvType.CV_64FC1); // expand input
    // image to
    // optimal size

    Core.copyMakeBorder(singleChannel, padded, 0, m - singleChannel.rows(), 0,
            n - singleChannel.cols(), Core.BORDER_CONSTANT);

    List<Mat> planes = new ArrayList<Mat>();
    planes.add(padded);
    planes.add(Mat.zeros(padded.rows(), padded.cols(), CvType.CV_64FC1));

    Mat complexI = Mat.zeros(padded.rows(), padded.cols(), CvType.CV_64FC2);

    Mat complexI2 = Mat
            .zeros(padded.rows(), padded.cols(), CvType.CV_64FC2);

    Core.merge(planes, complexI); // Add to the expanded another plane with
    // zeros

    Core.dct(complexI, complexI2); // this way the result may fit in the
    // source matrix

    // compute the magnitude and switch to logarithmic scale
    // => log(1 + sqrt(Re(DFT(I))^2 + Im(DFT(I))^2))
    Core.split(complexI2, planes); // planes[0] = Re(DFT(I), planes[1] =
    // Im(DFT(I))

    Mat mag = new Mat(planes.get(0).size(), planes.get(0).type());

    Core.magnitude(planes.get(0), planes.get(1), mag);// planes[0]
    // =
    // magnitude

    Mat magI = mag;
    Mat magI2 = new Mat(magI.size(), magI.type());
    Mat magI3 = new Mat(magI.size(), magI.type());
    Mat magI4 = new Mat(magI.size(), magI.type());
    Mat magI5 = new Mat(magI.size(), magI.type());

    Core.add(magI, Mat.ones(padded.rows(), padded.cols(), CvType.CV_64FC1),
            magI2); // switch to logarithmic scale
    Core.log(magI2, magI3);

    Mat crop = new Mat(magI3, new Rect(0, 0, magI3.cols() & -2,
            magI3.rows() & -2));

    magI4 = crop.clone();

    // rearrange the quadrants of Fourier image so that the origin is at the
    // image center
    int cx = magI4.cols() / 2;
    int cy = magI4.rows() / 2;

    Rect q0Rect = new Rect(0, 0, cx, cy);
    Rect q1Rect = new Rect(cx, 0, cx, cy);
    Rect q2Rect = new Rect(0, cy, cx, cy);
    Rect q3Rect = new Rect(cx, cy, cx, cy);

    Mat q0 = new Mat(magI4, q0Rect); // Top-Left - Create a ROI per quadrant
    Mat q1 = new Mat(magI4, q1Rect); // Top-Right
    Mat q2 = new Mat(magI4, q2Rect); // Bottom-Left
    Mat q3 = new Mat(magI4, q3Rect); // Bottom-Right

    Mat tmp = new Mat(); // swap quadrants (Top-Left with Bottom-Right)
    q0.copyTo(tmp);
    q3.copyTo(q0);
    tmp.copyTo(q3);

    q1.copyTo(tmp); // swap quadrant (Top-Right with Bottom-Left)
    q2.copyTo(q1);
    tmp.copyTo(q2);

    Core.normalize(magI4, magI5, 0, 255, Core.NORM_MINMAX);

    Mat realResult = new Mat(magI5.size(), CvType.CV_8UC1);

    magI5.convertTo(realResult, CvType.CV_8UC1);

    return realResult;
}
</code>```

Which I took form here.

The error that throws Android Studio is:

Caused by: CvException [org.opencv.core.CvException: cv::Exception: OpenCV(3.4.1) /build/master_pack-android/opencv/modules/core/src/dxt.cpp:3335: error: (-215) type == (((5) & ((1 << 3) - 1)) + (((1)-1) << 3)) || type == (((5) & ((1 << 3) - 1)) + (((2)-1) << 3)) || type == (((6) & ((1 << 3) - 1)) + (((1)-1) << 3)) || type == (((6) & ((1 << 3) - 1)) + (((2)-1) << 3)) in function void cv::dft(cv::InputArray, cv::OutputArray, int, int)

I called getDFT(mat); from:

```<code>protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode,resultCode,data);
    if (resultCode == RESULT_OK){
        path = data.getData();
        foto.setImageURI(path);
        try {
            Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), path);
            Mat mat = new Mat();
            Bitmap bitmap1 = bitmap.copy(Bitmap.Config.ARGB_8888, true);
            Utils.bitmapToMat(bitmap1, mat);
            getDFT(mat);
            Utils.matToBitmap(mat, bitmap);
            fourier.setImageBitmap(bitmap);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
</code>```

And this is called from:

```<code>boton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            intent.setType("image/");
            startActivityForResult(intent.createChooser(intent,"Selecciona la aplicación"),10);
        }
    });
</code>```

I also tried some code from here

But nothing happen.

I'm using OpenCv 3.4.1 and Android Studio 3.2.1

Any advice?

答:
I used your code to implement a dft of the camera preview in real-time by changing the line

Core.dct(complexI, complexI2);
to
Core.dft(complexI, complexI2);

Body:
i'm trying to convert and display an image made with Core.dft() on Android but it keeps crashing at the line I call Core.dft().

Here is my code:

private Mat getDFT(Mat singleChannel) {

    singleChannel.convertTo(singleChannel, CvType.CV_64FC1);

    int m = Core.getOptimalDFTSize(singleChannel.rows());
    int n = Core.getOptimalDFTSize(singleChannel.cols()); // on the border
    // add zero
    // values
    // Imgproc.copyMakeBorder(image1,
    // padded, 0, m -
    // image1.rows(), 0, n

    Mat padded = new Mat(new Size(n, m), CvType.CV_64FC1); // expand input
    // image to
    // optimal size

    Core.copyMakeBorder(singleChannel, padded, 0, m - singleChannel.rows(), 0,
            n - singleChannel.cols(), Core.BORDER_CONSTANT);

    List<Mat> planes = new ArrayList<Mat>();
    planes.add(padded);
    planes.add(Mat.zeros(padded.rows(), padded.cols(), CvType.CV_64FC1));

    Mat complexI = Mat.zeros(padded.rows(), padded.cols(), CvType.CV_64FC2);

    Mat complexI2 = Mat
            .zeros(padded.rows(), padded.cols(), CvType.CV_64FC2);

    Core.merge(planes, complexI); // Add to the expanded another plane with
    // zeros

    Core.dct(complexI, complexI2); // this way the result may fit in the
    // source matrix

    // compute the magnitude and switch to logarithmic scale
    // => log(1 + sqrt(Re(DFT(I))^2 + Im(DFT(I))^2))
    Core.split(complexI2, planes); // planes[0] = Re(DFT(I), planes[1] =
    // Im(DFT(I))

    Mat mag = new Mat(planes.get(0).size(), planes.get(0).type());

    Core.magnitude(planes.get(0), planes.get(1), mag);// planes[0]
    // =
    // magnitude

    Mat magI = mag;
    Mat magI2 = new Mat(magI.size(), magI.type());
    Mat magI3 = new Mat(magI.size(), magI.type());
    Mat magI4 = new Mat(magI.size(), magI.type());
    Mat magI5 = new Mat(magI.size(), magI.type());

    Core.add(magI, Mat.ones(padded.rows(), padded.cols(), CvType.CV_64FC1),
            magI2); // switch to logarithmic scale
    Core.log(magI2, magI3);

    Mat crop = new Mat(magI3, new Rect(0, 0, magI3.cols() & -2,
            magI3.rows() & -2));

    magI4 = crop.clone();

    // rearrange the quadrants of Fourier image so that the origin is at the
    // image center
    int cx = magI4.cols() / 2;
    int cy = magI4.rows() / 2;

    Rect q0Rect = new Rect(0, 0, cx, cy);
    Rect q1Rect = new Rect(cx, 0, cx, cy);
    Rect q2Rect = new Rect(0, cy, cx, cy);
    Rect q3Rect = new Rect(cx, cy, cx, cy);

    Mat q0 = new Mat(magI4, q0Rect); // Top-Left - Create a ROI per quadrant
    Mat q1 = new Mat(magI4, q1Rect); // Top-Right
    Mat q2 = new Mat(magI4, q2Rect); // Bottom-Left
    Mat q3 = new Mat(magI4, q3Rect); // Bottom-Right

    Mat tmp = new Mat(); // swap quadrants (Top-Left with Bottom-Right)
    q0.copyTo(tmp);
    q3.copyTo(q0);
    tmp.copyTo(q3);

    q1.copyTo(tmp); // swap quadrant (Top-Right with Bottom-Left)
    q2.copyTo(q1);
    tmp.copyTo(q2);

    Core.normalize(magI4, magI5, 0, 255, Core.NORM_MINMAX);

    Mat realResult = new Mat(magI5.size(), CvType.CV_8UC1);

    magI5.convertTo(realResult, CvType.CV_8UC1);

    return realResult;
}

Which I took form here.

The error that throws Android Studio is:

Caused by: CvException [org.opencv.core.CvException: cv::Exception: OpenCV(3.4.1) /build/master_pack-android/opencv/modules/core/src/dxt.cpp:3335: error: (-215) type == (((5) & ((1 << 3) - 1)) + (((1)-1) << 3)) || type == (((5) & ((1 << 3) - 1)) + (((2)-1) << 3)) || type == (((6) & ((1 << 3) - 1)) + (((1)-1) << 3)) || type == (((6) & ((1 << 3) - 1)) + (((2)-1) << 3)) in function void cv::dft(cv::InputArray, cv::OutputArray, int, int)

I called getDFT(mat); from:

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode,resultCode,data);
    if (resultCode == RESULT_OK){
        path = data.getData();
        foto.setImageURI(path);
        try {
            Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), path);
            Mat mat = new Mat();
            Bitmap bitmap1 = bitmap.copy(Bitmap.Config.ARGB_8888, true);
            Utils.bitmapToMat(bitmap1, mat);
            getDFT(mat);
            Utils.matToBitmap(mat, bitmap);
            fourier.setImageBitmap(bitmap);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

And this is called from:

boton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            intent.setType("image/");
            startActivityForResult(intent.createChooser(intent,"Selecciona la aplicación"),10);
        }
    });

I also tried some code from here

But nothing happen.

I'm using OpenCv 3.4.1 and Android Studio 3.2.1

Any advice?


问:
Replacement for DirectPropertyAccessor?
I am upgrading a Spring 4.3.2 project to Spring 5.1.5.
One of my test cases started failing with the error.

ClassNotFoundException: org.hibernate.property.DirectPropertyAccessor

Which makes sense since it has been deprecated in Hibernate 5.x which is the lowest compatible Hibernate version for Spring 5.x. I am consuming it in my hbm.xml as below:

```<code><class name="Notification"
       table="T_NOTIFICATION"
       lazy="false">

    <id name="id"
        type="integer"
        column="ID"
        unsaved-value="null"
        access="property">
        <generator class="identity"/>
    </id>

    <!-- A versioned entity. -->
    <version name="version"
             column="VERSION"
             access="org.hibernate.property.DirectPropertyAccessor"/>
</code>```

What should I replace the access field with, to maintain the same behaviour?

答:
The issue is not with Spring version but with Hibernate version.

org.hibernate.property.DirectPropertyAccessor is deprecated in 5.x version of hibernate.

DirectPropertyAccessor should be replaced with either org.hibernate.property.access.internal.PropertyAccessFieldImpl or org.hibernate.property.access.internal.PropertyAccessMixedImplin higher hibernate versions.

Title: Replacement for DirectPropertyAccessor?

Body:
I am upgrading a Spring 4.3.2 project to Spring 5.1.5.
One of my test cases started failing with the error.

ClassNotFoundException: org.hibernate.property.DirectPropertyAccessor

Which makes sense since it has been deprecated in Hibernate 5.x which is the lowest compatible Hibernate version for Spring 5.x. I am consuming it in my hbm.xml as below:

<class name="Notification"
       table="T_NOTIFICATION"
       lazy="false">

    <id name="id"
        type="integer"
        column="ID"
        unsaved-value="null"
        access="property">
        <generator class="identity"/>
    </id>

    <version name="version"
             column="VERSION"
             access="org.hibernate.property.DirectPropertyAccessor"/>

What should I replace the access field with, to maintain the same behaviour?


问:
Chart.JS: How can I only display data labels when the doughnut size is big enough for the text?
I am using Chart.JS with the Chart.JS datalabel plugin. Is it possible to only show the data labels when the doughnut slice size is big enough for the text?

I have the following example:

https://jsfiddle.net/7vg5w4mq/

```<code>var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
        plugins: [ChartDataLabels],
    type: 'doughnut',
    options:{
      plugins: {
        datalabels: {
          color: '#000000',
          display: true,
          formatter: function (value, ctx) {
            return value + " kWh";
          }
        }
      },
      rotation: 1 * Math.PI,
      circumference: 1 * Math.PI
    },
    data: {
        labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange", "Red1", "Blue1", "Yellow1", "Green1", "Purple1", "Orange1", "Red2", "Blue2", "Yellow2", "Green2", "Purple2", "Orange2"],
        datasets: [{
            label: '# of Votes',
            data: [12, 19, 3, 5, 2, 3, 12, 19, 3, 5, 2, 3, 12, 19, 3, 5, 2, 3],
            backgroundColor: [
                'rgba(255, 99, 132, 0.2)',
                'rgba(54, 162, 235, 0.2)',
                'rgba(255, 206, 86, 0.2)',
                'rgba(75, 192, 192, 0.2)',
                'rgba(153, 102, 255, 0.2)',
                'rgba(255, 159, 64, 0.2)',
                'rgba(255, 99, 132, 0.2)',
                'rgba(54, 162, 235, 0.2)',
                'rgba(255, 206, 86, 0.2)',
                'rgba(75, 192, 192, 0.2)',
                'rgba(153, 102, 255, 0.2)',
                'rgba(255, 159, 64, 0.2)',
                'rgba(255, 99, 132, 0.2)',
                'rgba(54, 162, 235, 0.2)',
                'rgba(255, 206, 86, 0.2)',
                'rgba(75, 192, 192, 0.2)',
                'rgba(153, 102, 255, 0.2)',
                'rgba(255, 159, 64, 0.2)'
            ],
            borderColor: [
                'rgba(255,99,132,1)',
                'rgba(54, 162, 235, 1)',
                'rgba(255, 206, 86, 1)',
                'rgba(75, 192, 192, 1)',
                'rgba(153, 102, 255, 1)',
                'rgba(255, 159, 64, 1)',
                'rgba(255,99,132,1)',
                'rgba(54, 162, 235, 1)',
                'rgba(255, 206, 86, 1)',
                'rgba(75, 192, 192, 1)',
                'rgba(153, 102, 255, 1)',
                'rgba(255, 159, 64, 1)',
                'rgba(255,99,132,1)',
                'rgba(54, 162, 235, 1)',
                'rgba(255, 206, 86, 1)',
                'rgba(75, 192, 192, 1)',
                'rgba(153, 102, 255, 1)',
                'rgba(255, 159, 64, 1)'
            ],
            borderWidth: 1
        }]
    }
});
</code>```

I know, this example doesn't make any sense, but you can see the issue.

If there is a lot of data, the data labels overflow the doughnut slice size like this:

Is there an option to tell Chart.JS to only show these labels when the text fits into the doughnut? (Otherwise just show the tooltips).

The option to just check the percentage of the values does not work because the chart itself (Or the size of the browser window) can be resized to a very small size (And the percentages would no longer fit).

Note: This is not the same question as Chart.JS: How can I only display data labels when the bar width is big enough for the text? because there I'm asking for the same thing, but for a bar chart!

答:
I'm now using a combination of two ideas:

Show values only if a certain percentage threshold of the value is not underrun

Show values only if a certain graph width is not underrun

The example below shows the idea(s):

```<code>formatter: function(value) {
    let percentage = (value.toFixed(2) / sum) * 100;

    if (percentage > 100) {
        percentage = 100;
    }

    if (percentage < 10) {
        return "";
    }

    if (ctx.width <= 200) {
        return "";
    }

    return value + " kWh";
}
</code>```

Body:
I am using Chart.JS with the Chart.JS datalabel plugin. Is it possible to only show the data labels when the doughnut slice size is big enough for the text?

I have the following example:

https://jsfiddle.net/7vg5w4mq/

var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
        plugins: [ChartDataLabels],
    type: 'doughnut',
    options:{
      plugins: {
        datalabels: {
          color: '#000000',
          display: true,
          formatter: function (value, ctx) {
            return value + " kWh";
          }
        }
      },
      rotation: 1 * Math.PI,
      circumference: 1 * Math.PI
    },
    data: {
        labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange", "Red1", "Blue1", "Yellow1", "Green1", "Purple1", "Orange1", "Red2", "Blue2", "Yellow2", "Green2", "Purple2", "Orange2"],
        datasets: [{
            label: '# of Votes',
            data: [12, 19, 3, 5, 2, 3, 12, 19, 3, 5, 2, 3, 12, 19, 3, 5, 2, 3],
            backgroundColor: [
                'rgba(255, 99, 132, 0.2)',
                'rgba(54, 162, 235, 0.2)',
                'rgba(255, 206, 86, 0.2)',
                'rgba(75, 192, 192, 0.2)',
                'rgba(153, 102, 255, 0.2)',
                'rgba(255, 159, 64, 0.2)',
                'rgba(255, 99, 132, 0.2)',
                'rgba(54, 162, 235, 0.2)',
                'rgba(255, 206, 86, 0.2)',
                'rgba(75, 192, 192, 0.2)',
                'rgba(153, 102, 255, 0.2)',
                'rgba(255, 159, 64, 0.2)',
                'rgba(255, 99, 132, 0.2)',
                'rgba(54, 162, 235, 0.2)',
                'rgba(255, 206, 86, 0.2)',
                'rgba(75, 192, 192, 0.2)',
                'rgba(153, 102, 255, 0.2)',
                'rgba(255, 159, 64, 0.2)'
            ],
            borderColor: [
                'rgba(255,99,132,1)',
                'rgba(54, 162, 235, 1)',
                'rgba(255, 206, 86, 1)',
                'rgba(75, 192, 192, 1)',
                'rgba(153, 102, 255, 1)',
                'rgba(255, 159, 64, 1)',
                'rgba(255,99,132,1)',
                'rgba(54, 162, 235, 1)',
                'rgba(255, 206, 86, 1)',
                'rgba(75, 192, 192, 1)',
                'rgba(153, 102, 255, 1)',
                'rgba(255, 159, 64, 1)',
                'rgba(255,99,132,1)',
                'rgba(54, 162, 235, 1)',
                'rgba(255, 206, 86, 1)',
                'rgba(75, 192, 192, 1)',
                'rgba(153, 102, 255, 1)',
                'rgba(255, 159, 64, 1)'
            ],
            borderWidth: 1
        }]
    }
});

I know, this example doesn't make any sense, but you can see the issue.

If there is a lot of data, the data labels overflow the doughnut slice size like this:

Is there an option to tell Chart.JS to only show these labels when the text fits into the doughnut? (Otherwise just show the tooltips).

The option to just check the percentage of the values does not work because the chart itself (Or the size of the browser window) can be resized to a very small size (And the percentages would no longer fit).

Note: This is not the same question as Chart.JS: How can I only display data labels when the bar width is big enough for the text? because there I'm asking for the same thing, but for a bar chart!

Body:
I'm now using a combination of two ideas:

Show values only if a certain percentage threshold of the value is not underrun

Show values only if a certain graph width is not underrun

The example below shows the idea(s):

formatter: function(value) {
    let percentage = (value.toFixed(2) / sum) * 100;

    if (percentage > 100) {
        percentage = 100;
    }

    if (percentage < 10) {
        return "";
    }

    if (ctx.width <= 200) {
        return "";
    }

    return value + " kWh";
}


问:
Unpickling error with MARK: how to solve it?
I am trying to load a simple list from a file to another, but python raises _pickle.UnpicklingError: could not find MARK as soon as I run it. The code is really simple and follows what the course tells me, I really don't understand. It goes as follows: file "donnees.py" has the list, and "fonctions.py" has the rest.

donnees.py

```<code>listemots=["bonjour","pivers","cactus","france","taureau","espace"]
</code>```

fonctions.py

```<code>import pickle
import random

with open("donnees.py","rb") as donnees:

    unpickler1=pickle.Unpickler(donnees)

    listerecuperee=unpickler1.load()

print(listerecuperee)
</code>```

Error raises is:

```<code>Traceback (most recent call last):
  File "/Users/sebastienchabrol/Documents/Cours de python/pendu/fonctions.py", line 6, in <module>
    listerecuperee=unpickler1.load()
_pickle.UnpicklingError: could not find MARK
</code>```

Does someone have an idea about how to fix this ? Many thanks !!

答:
For this just use:

```<code>from donnees import listemotes
</code>```

Don’t use .py files to pickle variables. If you want to persist a list then use the csv module.

Body:
I am trying to load a simple list from a file to another, but python raises _pickle.UnpicklingError: could not find MARK as soon as I run it. The code is really simple and follows what the course tells me, I really don't understand. It goes as follows: file "donnees.py" has the list, and "fonctions.py" has the rest.

donnees.py

listemots=["bonjour","pivers","cactus","france","taureau","espace"]

fonctions.py

import pickle
import random

with open("donnees.py","rb") as donnees:

    unpickler1=pickle.Unpickler(donnees)

    listerecuperee=unpickler1.load()

print(listerecuperee)

Error raises is:

Traceback (most recent call last):
  File "/Users/sebastienchabrol/Documents/Cours de python/pendu/fonctions.py", line 6, in <module>
    listerecuperee=unpickler1.load()
_pickle.UnpicklingError: could not find MARK

Does someone have an idea about how to fix this ? Many thanks !!

Body:
For this just use:

from donnees import listemotes

Don’t use .py files to pickle variables. If you want to persist a list then use the csv module.