问:
How to keep child divs from expanding beyond the parent when printing
I am trying to format an html page as a court pleading which needs to print neatly on an 8.5 x 11 piece of paper. I have it looking to spec as an HTML, but when I go to print, the Container holding the contents expands beyond the body.

I have tried setting a specific width to the container to match the body, but that has not worked.

I created a fiddle with both the HTML and CSS:

See fiddle here

Here is the CSS for the BODY and CONTAINER:

```<code>body {
    width: 8.5in;
    height: 11in;
    padding-left: 1.5in;
    padding-right: .5in;
    margin: 0;
    border-left: 1px solid grey;
    border-right: 1px solid grey;
}

.container {
    border-left: 2px solid black;
    border-right: 2px solid black;
    width: 8.5in;
    margin: 0;
    padding: 5px;
    height: 100%;
}
</code>```

If you click on the "Open print preview" text at the bottom of the result, and then attempt to print, you can see how the document changes in the print preview window in Chrome.

This application is meant to work in Chrome specifically. I am trying to produce a document that looks similar to the following, with the grey thinner lines indicating the edge of the page:

答:
I'm not sure this is the solution which you are looking for. I tested your code in different browser's print preview  functionality and found different result. Then I stick with google chrome and coded accordingly.

I found you used same code twice so it was not working properly! I put the other code for screen only. and change the following code for print

```<code> @media print {
    body {
        /* width: 8.5in; */
        /* height: 11in; */
        margin: 0;
        border-left: 1px solid gray;
        border-right: 1px solid gray;
        /*Newly added codes */
        box-sizing: border-box;
    }

    .container {
        border-left: 2px solid black;
        border-right: 2px solid black;
        width: 100%;
        margin: 0;
        padding: 5px;
        height: 100%;
        /*Newly added codes  */
        box-sizing: border-box;
        /* Copied from body */
        padding-left: 1.5in;
        padding-right: .5in;
    }
}
</code>```

In my code I removed the textarea, instead I put a
 tag with editable capability. Please review the code and let me know your opinion.

And this is what I have here in Google Chrome.

I tried several option but not found any proper one! But this one is tricky! Just used the following code for print CSS. Please replace and test this code.

```<code>@media print {
    body {
        /* width: 8.5in; */
        /* height: 11in; */
        padding-left: 1.5in;
        padding-right: .5in;
        margin: 0;
        border-left: 1px solid gray;
        border-right: 1px solid gray;
        /*Newly added codes */
        box-sizing: border-box;
    }
    .container {
        border-left: 2px solid black;
        border-right: 2px solid black;
        width: 6.5in;
        margin: 0 auto;
        padding: 10pt 36pt;
        /* height: 100%; */
        /*Newly added codes  */
        box-sizing: border-box;
        /* Copied from body */
    }
}
</code>```

After that I used the custom margin in google chrome (Though I have not printed it! So you better test it for final output).

Hopefully this will satisfy your need! :)

Body:
I am trying to format an html page as a court pleading which needs to print neatly on an 8.5 x 11 piece of paper. I have it looking to spec as an HTML, but when I go to print, the Container holding the contents expands beyond the body.

I have tried setting a specific width to the container to match the body, but that has not worked.

I created a fiddle with both the HTML and CSS:

See fiddle here

Here is the CSS for the BODY and CONTAINER:

body {
    width: 8.5in;
    height: 11in;
    padding-left: 1.5in;
    padding-right: .5in;
    margin: 0;
    border-left: 1px solid grey;
    border-right: 1px solid grey;
}

.container {
    border-left: 2px solid black;
    border-right: 2px solid black;
    width: 8.5in;
    margin: 0;
    padding: 5px;
    height: 100%;
}

If you click on the "Open print preview" text at the bottom of the result, and then attempt to print, you can see how the document changes in the print preview window in Chrome.

This application is meant to work in Chrome specifically. I am trying to produce a document that looks similar to the following, with the grey thinner lines indicating the edge of the page:

Body:
I'm not sure this is the solution which you are looking for. I tested your code in different browser's print preview  functionality and found different result. Then I stick with google chrome and coded accordingly.

I found you used same code twice so it was not working properly! I put the other code for screen only. and change the following code for print

 @media print {
    body {
        /* width: 8.5in; */
        /* height: 11in; */
        margin: 0;
        border-left: 1px solid gray;
        border-right: 1px solid gray;
        /*Newly added codes */
        box-sizing: border-box;
    }

    .container {
        border-left: 2px solid black;
        border-right: 2px solid black;
        width: 100%;
        margin: 0;
        padding: 5px;
        height: 100%;
        /*Newly added codes  */
        box-sizing: border-box;
        /* Copied from body */
        padding-left: 1.5in;
        padding-right: .5in;
    }
}

In my code I removed the textarea, instead I put a <p> tag with editable capability. Please review the code and let me know your opinion.

And this is what I have here in Google Chrome.

I tried several option but not found any proper one! But this one is tricky! Just used the following code for print CSS. Please replace and test this code.

@media print {
    body {
        /* width: 8.5in; */
        /* height: 11in; */
        padding-left: 1.5in;
        padding-right: .5in;
        margin: 0;
        border-left: 1px solid gray;
        border-right: 1px solid gray;
        /*Newly added codes */
        box-sizing: border-box;
    }
    .container {
        border-left: 2px solid black;
        border-right: 2px solid black;
        width: 6.5in;
        margin: 0 auto;
        padding: 10pt 36pt;
        /* height: 100%; */
        /*Newly added codes  */
        box-sizing: border-box;
        /* Copied from body */
    }
}

After that I used the custom margin in google chrome (Though I have not printed it! So you better test it for final output).

Hopefully this will satisfy your need! :)


来源: stackexchange

问:
Executable missing full library path after build
I am using CMake to compile an executable that is linked against several libraries that I have built and installed into a local project directory (libs/3rdparty). Note that this is prior to installation of the project, primarily for the purpose of running unit tests and debugging. The problem I am having is that sometimes there is a library that is linked, but the executable is missing the path to the library. The library I am currently having an issue with is leptonica. However, I have run into this issue several times with different libraries on different platforms (osx, fedora, centos, ubuntu). Through research I have seen similar issues, but I have never been able to find a definitive answer of why the full path to the library would be missing.

I've tried playing with:

```<code>CMAKE_BUILD_WITH_INSTALL_RPATH
CMAKE_INSTALL_RPATH
CMAKE_INSTALL_RPATH_USE_LINK_PATH
</code>```

and these don't seem to have much effect.

My CMakeLists contains:

```<code>find_package(Leptonica REQUIRED)

target_link_libraries(${target}
    PRIVATE
        ...
        ${Leptonica_LIBRARIES}
)
</code>```

Here is the output from ldd on one of the unit test executables:

```<code>ldd test_utilities
...
libleptonica.so.5.3.0 => not found
libtesseract.so.4 => {MY PROJECT}/libs/3rdparty/tesseract/lib/libtesseract.so.4
</code>```

leptonica is the only library that is not found out of ~30 other libraries.

Does anyone know what the root cause of this problem is? I am not looking to work around the problem by modifying LD_LIBRARY_PATH.

-- Added LeptonicaTargets-release.cmake. According to this the full path to the lib should be in the target.

```<code>#----------------------------------------------------------------
# Generated CMake target import file for configuration "RELEASE".
#----------------------------------------------------------------

# Commands may need to know the format version.
set(CMAKE_IMPORT_FILE_VERSION 1)

# Import target "leptonica" for configuration "RELEASE"
set_property(TARGET leptonica APPEND PROPERTY IMPORTED_CONFIGURATIONS RELEASE)
set_target_properties(leptonica PROPERTIES
  IMPORTED_LINK_INTERFACE_LIBRARIES_RELEASE "/usr/lib/x86_64-linux-gnu/libpng.so;/usr/lib/x86_64-linux-gnu/libz.so;m"
  IMPORTED_LOCATION_RELEASE "${_IMPORT_PREFIX}/lib/libleptonica.so.1.77.0"
  IMPORTED_SONAME_RELEASE "libleptonica.so.5.3.0"
  )

list(APPEND _IMPORT_CHECK_TARGETS leptonica )
list(APPEND _IMPORT_CHECK_FILES_FOR_leptonica "${_IMPORT_PREFIX}/lib/libleptonica.so.1.77.0" )

# Commands beyond this point should not need to know the version.
set(CMAKE_IMPORT_FILE_VERSION)
</code>```

Here are the files in the leptonica/lib directory:

```<code>ll libs/3rdparty/leptonica/lib/
total 2776
drwxr-xr-x 3 user user    4096 May 30 14:17 ./
drwxr-xr-x 5 user user    4096 May 30 14:17 ../
lrwxrwxrwx 1 user user      21 May 30 14:17 libleptonica.so -> libleptonica.so.5.3.0
-rw-r--r-- 1 user user 2829784 May 30 09:49 libleptonica.so.1.77.0
lrwxrwxrwx 1 user user      22 May 30 14:17 libleptonica.so.5.3.0 -> libleptonica.so.1.77.0
drwxr-xr-x 2 user user    4096 May 30 14:17 pkgconfig/
</code>```

Output from chrpath --list test_utilities appears to contain the correct path to the library as well:

```<code>chrpath --list test_utilities
test_utilities: RUNPATH=...:{MY PROJECT}/libs/3rdparty/leptonica/lib:...
</code>```

答:
For anyone who runs across this, I have finally figured it out.

The issue was related to the library being a transitive dependency of OpenCV. On Ubuntu, ld now defaults to using using --enable-new-dtags which uses RUNPATH, not RPATH. There is an issue where RUNPATH is not searched for transitive dependencies.

See https://bugs.launchpad.net/ubuntu/+source/eglibc/+bug/1253638

Simply adding "-Wl,--disable-new-dtags" to the target linker options resolved my issue. All libraries are now found, including other libraries than leptonica that I added today. I am sure that I will likely have to make changes when building a package for installation though.

ContentLicense: CC BY-SA 4.0

Body:
I am using CMake to compile an executable that is linked against several libraries that I have built and installed into a local project directory (libs/3rdparty). Note that this is prior to installation of the project, primarily for the purpose of running unit tests and debugging. The problem I am having is that sometimes there is a library that is linked, but the executable is missing the path to the library. The library I am currently having an issue with is leptonica. However, I have run into this issue several times with different libraries on different platforms (osx, fedora, centos, ubuntu). Through research I have seen similar issues, but I have never been able to find a definitive answer of why the full path to the library would be missing.

I've tried playing with:

CMAKE_BUILD_WITH_INSTALL_RPATH
CMAKE_INSTALL_RPATH
CMAKE_INSTALL_RPATH_USE_LINK_PATH

and these don't seem to have much effect.

My CMakeLists contains:

find_package(Leptonica REQUIRED)

target_link_libraries(${target}
    PRIVATE
        ...
        ${Leptonica_LIBRARIES}
)

Here is the output from ldd on one of the unit test executables:

ldd test_utilities
...
libleptonica.so.5.3.0 => not found
libtesseract.so.4 => {MY PROJECT}/libs/3rdparty/tesseract/lib/libtesseract.so.4

leptonica is the only library that is not found out of ~30 other libraries.

Does anyone know what the root cause of this problem is? I am not looking to work around the problem by modifying LD_LIBRARY_PATH.

-- Added LeptonicaTargets-release.cmake. According to this the full path to the lib should be in the target.

#----------------------------------------------------------------
# Generated CMake target import file for configuration "RELEASE".
#----------------------------------------------------------------

# Commands may need to know the format version.
set(CMAKE_IMPORT_FILE_VERSION 1)

# Import target "leptonica" for configuration "RELEASE"
set_property(TARGET leptonica APPEND PROPERTY IMPORTED_CONFIGURATIONS RELEASE)
set_target_properties(leptonica PROPERTIES
  IMPORTED_LINK_INTERFACE_LIBRARIES_RELEASE "/usr/lib/x86_64-linux-gnu/libpng.so;/usr/lib/x86_64-linux-gnu/libz.so;m"
  IMPORTED_LOCATION_RELEASE "${_IMPORT_PREFIX}/lib/libleptonica.so.1.77.0"
  IMPORTED_SONAME_RELEASE "libleptonica.so.5.3.0"
  )

list(APPEND _IMPORT_CHECK_TARGETS leptonica )
list(APPEND _IMPORT_CHECK_FILES_FOR_leptonica "${_IMPORT_PREFIX}/lib/libleptonica.so.1.77.0" )

# Commands beyond this point should not need to know the version.
set(CMAKE_IMPORT_FILE_VERSION)

Here are the files in the leptonica/lib directory:

ll libs/3rdparty/leptonica/lib/
total 2776
drwxr-xr-x 3 user user    4096 May 30 14:17 ./
drwxr-xr-x 5 user user    4096 May 30 14:17 ../
lrwxrwxrwx 1 user user      21 May 30 14:17 libleptonica.so -> libleptonica.so.5.3.0
-rw-r--r-- 1 user user 2829784 May 30 09:49 libleptonica.so.1.77.0
lrwxrwxrwx 1 user user      22 May 30 14:17 libleptonica.so.5.3.0 -> libleptonica.so.1.77.0
drwxr-xr-x 2 user user    4096 May 30 14:17 pkgconfig/

Output from chrpath --list test_utilities appears to contain the correct path to the library as well:

chrpath --list test_utilities
test_utilities: RUNPATH=...:{MY PROJECT}/libs/3rdparty/leptonica/lib:...


问:
MYSQL, ignore whitespace, punctuation, substitute accents in query
I need a way to use my dictionary with province abbreviations, full names and territories without having to add an entry for every possible misspelling of Ontario.
Table is as such:

```<code>state       |name     | territory
===================================
AB           Alberta   West
</code>```

Data is as such:

```<code>"Ontario,"
"ON,"
"ON"
"On"
" Ontario"
"Ontario "
" Ontario "

Quebec
Québec
QU
QB
Quebec,
</code>```

答:
Just an idea, knowing it can't be used for all your db.

Anyway: what about using

SELECT * FROM table WHERE name LIKE '%ontario%'?

ContentLicense: CC BY-SA 3.0

Body:
I need a way to use my dictionary with province abbreviations, full names and territories without having to add an entry for every possible misspelling of Ontario.
Table is as such:

state       |name     | territory
===================================
AB           Alberta   West

Data is as such:

"Ontario,"
"ON,"
"ON"
"On"
" Ontario"
"Ontario "
" Ontario "

Quebec
Québec
QU
QB
Quebec,


问:
Kotlin custom attribute databinding
I am trying to set custom attribute using the Android DataBinding Library
in my Kotlin project like this:

Layout

```<code><ImageView
    android:id="@+id/imgView”
    android:layout_width="40dp"
    android:layout_height="40dp"
    android:layout_gravity="center"
    android:adjustViewBounds="true"
    app:imageUrl="@{segment.url}"/>

</code>```

Code

```<code>class Utils {
    companion object {
        @BindingAdapter("bind:imageUrl")
        @JvmStatic
        fun loadImage(view: ImageView, url:String)
        {Picasso.with(view.context).load(url).error(R.drawable.error).into(view)}
    }
}

</code>```

The runtime error I get is:

A BindingAdapter in in <package.Utils.Companion> is not static and requires an object to use, retrieved from the DataBindingComponent. If you don't use an inflation method taking a DataBindingComponent, use DataBindingUtil.setDefaultComponent or make all BindingAdapter methods static.

Any pointers to solve it?

This happens only for custom attributes. The rest of the databindings work fine

答:
This worked for me

```<code>object ImageUtils {

        @JvmStatic @BindingAdapter("imageUrl")
        fun ImageView.loadImage(url: String?){
                GlideHelper.loadImage(url,this)
        }
}
</code>```

in xml like this:

```<code>imageUrl="@{file.thumbnailLink}"
</code>```

Title: Kotlin custom attribute databinding

Body:
I am trying to set custom attribute using the Android DataBinding Library
in my Kotlin project like this:

Layout

<ImageView
    android:id="@+id/imgView”
    android:layout_width="40dp"
    android:layout_height="40dp"
    android:layout_gravity="center"
    android:adjustViewBounds="true"
    app:imageUrl="@{segment.url}"/>

Code

class Utils {
    companion object {
        @BindingAdapter("bind:imageUrl")
        @JvmStatic
        fun loadImage(view: ImageView, url:String)
        {Picasso.with(view.context).load(url).error(R.drawable.error).into(view)}
    }
}

The runtime error I get is:

A BindingAdapter in in <package.Utils.Companion> is not static and requires an object to use, retrieved from the DataBindingComponent. If you don't use an inflation method taking a DataBindingComponent, use DataBindingUtil.setDefaultComponent or make all BindingAdapter methods static.

Any pointers to solve it?

This happens only for custom attributes. The rest of the databindings work fine

Body:
This worked for me

object ImageUtils {

        @JvmStatic @BindingAdapter("imageUrl")
        fun ImageView.loadImage(url: String?){
                GlideHelper.loadImage(url,this)
        }
}

in xml like this:

imageUrl="@{file.thumbnailLink}"


问:
How do I setState?
When making setState() in onchange and trying to change the value, it writes or deletes only 1 character. What is the problem?</p>

```<code>enter code here:

  constructor() {
      super();
       this.state = {lw1val:null}
   }

   {this.state.isLw1 ? (
                <input
                onChange={e => {
                  this.setState({ lw1val: e.target.value })

                }}
                value={this.state.lw1val}
                  onKeyPress={event => {

                    if (event.keyCode === 13 || event.which === 13) {
                      var inPutData = [
                        {
                          filterType: "is-equal-to",
                          value: event.target.value
                        }
                      ];

                      onChange(inPutData);
                    }
                  }}
                />
              ) : null}
</code>```

答:
In input tag, specify which is your value:</p>

```<code><input value={this.state.lw1val} onChange= {event => this.setState({ lw1val: event.target.value })} />
</code>```

Title: How do I setState?

Body:
When making setState() in onchange and trying to change the value, it writes or deletes only 1 character. What is the problem?

enter code here:

  constructor() {
      super();
       this.state = {lw1val:null}
   }

   {this.state.isLw1 ? (
                <input
                onChange={e => {
                  this.setState({ lw1val: e.target.value })

                }}
                value={this.state.lw1val}
                  onKeyPress={event => {

                    if (event.keyCode === 13 || event.which === 13) {
                      var inPutData = [
                        {
                          filterType: "is-equal-to",
                          value: event.target.value
                        }
                      ];

                      onChange(inPutData);
                    }
                  }}
                />
              ) : null}

Body:
In input tag, specify which is your value:

<input value={this.state.lw1val} onChange= {event => this.setState({ lw1val: event.target.value })} />


问:
How to give different bg color to each  created using php function?
I've a table showing 7 days of week created using php function. How can i give different background color to each day in the table. I'm new to this, any and all help would be great.

```<code><?php
for($prev_days = 0 ; $prev_days<7;$prev_days++) {
    $curr_date = date('Y-m-d', strtotime(-$prev_days.' days'));
    $dayOfWeek = date("l",strtotime(strval($curr_date)));
    /*echo $dayOfWeek;*/
?>
    <td title="click here to see the files">
        <label>
            <a onclick="document.getElementById('id01').style.display='block'" class="clr">
                <?php echo substr(strval($dayOfWeek),0,3); ?>
            </a>
        </label>
    </td>
<?php
    }
?>

.CSSTableGenerator tr:first-child td{
background:-o-linear-gradient(bottom, #005fbf 5%, #003f7f 100%);
background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #005fbf), color-stop(1, #003f7f) );
background:-moz-linear-gradient( center top, #005fbf 5%, #003f7f 100% );
filter:progid:DXImageTransform.Microsoft.gradient(startColorstr="#005fbf", endColorstr="#003f7f");  background: -o-linear-gradient(top,#005fbf,003f7f);
background-color:#005fbf;
}
</code>```

This is the table created
: https://i.stack.imgur.com/nLnxP.png

答:
There are a number of way to do that. I can see some good solutions here. But here is a PHP only solution with minimal changes in your code.

```<code><?php
$day_color = ["#ffccee","#ccccee","#f1dcee","#a2ccf3","#d7c3e3","#f3cc3e","#6fc63e"];
for($prev_days = 0 ; $prev_days<7;$prev_days++) {
    $curr_date = date('Y-m-d', strtotime(-$prev_days.' days'));
    $dayOfWeek = date("l",strtotime(strval($curr_date)));
    /*echo $dayOfWeek;*/
?>
    <td title="click here to see the files">
        <label style="background-color:<?php echo $day_color[$prev_days]?>">
            <a onclick="document.getElementById('id01').style.display='block'" class="clr">
                <?php echo substr(strval($dayOfWeek),0,3); ?>
            </a>
        </label>
    </td>
<?php
    }
?>
</code>```

you can choose your desired colors in the $day_color array as you see fit.

Title: How to give different bg color to each <td> created using php function?

Body:
I've a table showing 7 days of week created using php function. How can i give different background color to each day in the table. I'm new to this, any and all help would be great.

<?php
for($prev_days = 0 ; $prev_days<7;$prev_days++) {
    $curr_date = date('Y-m-d', strtotime(-$prev_days.' days'));
    $dayOfWeek = date("l",strtotime(strval($curr_date)));
    /*echo $dayOfWeek;*/
?>

                <?php echo substr(strval($dayOfWeek),0,3); ?>

<?php
    }
?>

.CSSTableGenerator tr:first-child td{
background:-o-linear-gradient(bottom, #005fbf 5%, #003f7f 100%);
background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #005fbf), color-stop(1, #003f7f) );
background:-moz-linear-gradient( center top, #005fbf 5%, #003f7f 100% );
filter:progid:DXImageTransform.Microsoft.gradient(startColorstr="#005fbf", endColorstr="#003f7f");  background: -o-linear-gradient(top,#005fbf,003f7f);
background-color:#005fbf;
}

This is the table created
: https://i.stack.imgur.com/nLnxP.png

Body:
There are a number of way to do that. I can see some good solutions here. But here is a PHP only solution with minimal changes in your code.

<?php
$day_color = ["#ffccee","#ccccee","#f1dcee","#a2ccf3","#d7c3e3","#f3cc3e","#6fc63e"];
for($prev_days = 0 ; $prev_days<7;$prev_days++) {
    $curr_date = date('Y-m-d', strtotime(-$prev_days.' days'));
    $dayOfWeek = date("l",strtotime(strval($curr_date)));
    /*echo $dayOfWeek;*/
?>
    <td title="click here to see the files">
        <label style="background-color:<?php echo $day_color[$prev_days]?>">
            <a onclick="document.getElementById('id01').style.display='block'" class="clr">
                <?php echo substr(strval($dayOfWeek),0,3); ?>
            </a>
        </label>
    </td>
<?php
    }
?>

you can choose your desired colors in the $day_color array as you see fit.


问:
Prompt for choice. Re-prompt if option is invalid
I'm wondering how to re-prompt if someone typos or enters something other than yes/no
Would it have to be a created as a prompting function or is there an easier way?</p>

```<code>$Continue = Read-Host -Prompt "Continue? Yes/No"
Switch($Continue){
    'Yes' { Write-host -ForegroundColor Yellow "Moving on..." }
    'No' {Write-host "...GoodBye"
            Exit
         }
    default { #HOW TO RE-PROMPT USER FOR YES/No?
        }
}
</code>```

答:
Using a While loop which a check variable. If Yes is typed then $Check will equal $true exiting the loop. Else it will stay false and rerun the loop again.

```<code>$Check = $false
while($Check -eq $false){
    Switch(Read-Host -Prompt "Continue? Yes/No"){
        'Yes' {
            Write-host -ForegroundColor Yellow "Moving on..."
            $Check = $true
        }
        'No' {
            Write-host "...GoodBye"
            return
        }
    }
}
</code>```

Body:
I'm wondering how to re-prompt if someone typos or enters something other than yes/no
Would it have to be a created as a prompting function or is there an easier way?

$Continue = Read-Host -Prompt "Continue? Yes/No"
Switch($Continue){
    'Yes' { Write-host -ForegroundColor Yellow "Moving on..." }
    'No' {Write-host "...GoodBye"
            Exit
         }
    default { #HOW TO RE-PROMPT USER FOR YES/No?
        }
}

Body:
Using a While loop which a check variable. If Yes is typed then $Check will equal $true exiting the loop. Else it will stay false and rerun the loop again.

$Check = $false
while($Check -eq $false){
    Switch(Read-Host -Prompt "Continue? Yes/No"){
        'Yes' {
            Write-host -ForegroundColor Yellow "Moving on..."
            $Check = $true
        }
        'No' {
            Write-host "...GoodBye"
            return
        }
    }
}


问:
C# Timer firing too early
When I call the Method random_Start() it works at first: The second console print comes at a reasonable time, but then the gap between the console prints gets smaller and smaller.

After some prints, almost every print comes after way less than 5 Seconds, although the code should set a Timer for at least 5 Seconds, right?

        static Timer timer;
        static Random random = new Random();
        public static void random_Start()
        {
            timer = new Timer(random.NextDouble()*10000+5000);
            timer.Elapsed += OnTimedEvent;
            timer.Start();
            Console.WriteLine("Start");
        }

        private static void OnTimedEvent(Object source, ElapsedEventArgs e)
        {
            random_Start();
        }
```

答:
Setup your timer so that you aren't creating a new instance with every timer tick. In the example below, I've disabled AutoReset so that we can set a new interval and start the timer again manually.

```<code>    static Timer timer;
    static Random random = new Random();
    public static void random_Start()
    {
        timer = new Timer(random.NextDouble()*10000+5000);
        timer.Elapsed += OnTimedEvent;
        timer.AutoReset = false;
        timer.Start();
        Console.WriteLine("Start");
    }

    private static void OnTimedEvent(Object source, ElapsedEventArgs e)
    {
        Console.WriteLine("Tick");
        timer.Interval = random.NextDouble()*10000+5000;
        timer.Start();
    }
</code>```

Title: C# Timer firing too early

Body:
Setup your timer so that you aren't creating a new instance with every timer tick. In the example below, I've disabled AutoReset so that we can set a new interval and start the timer again manually.

    static Timer timer;
    static Random random = new Random();
    public static void random_Start()
    {
        timer = new Timer(random.NextDouble()*10000+5000);
        timer.Elapsed += OnTimedEvent;
        timer.AutoReset = false;
        timer.Start();
        Console.WriteLine("Start");
    }

    private static void OnTimedEvent(Object source, ElapsedEventArgs e)
    {
        Console.WriteLine("Tick");
        timer.Interval = random.NextDouble()*10000+5000;
        timer.Start();
    }


问:
How to create a wall using Design Automation API for Revit
I am trying to create a wall using Design Automation API for Revit. How can I achieve this.

I am working on a project which creates walls based on excel file.
First I convert the excel file to json and pass them as parameter to a Revit template file (.rte file) and the result output is a Revit file (.rvt) with the wall. This process happens in a loop based on the number of rows in the excel file.

I have achieved this task in the Revit API desktop addins, but I am unable to understand as to how this can be achieved in the Design Automation API for Revit.

I have followed the steps given in the link

https://forge.autodesk.com/en/docs/design-automation/v3/tutorials/revit/step1-convert-addin/

But I am unable to understand how send the template file (.rte) to the Forge API to output the .rvt file. Can multiple revit files be returned through the API?

Can someone please guide me in the right direction to create a wall

Thanks in advance

答:
Please refer code samples for SketchIt app. It takes json inputs for Wall locations and creates a Revit file with Walls in them.

https://forge.autodesk.com/en/docs/design-automation/v3/tutorials/revit/more-learning-resources/
https://github.com/Autodesk-Forge/design.automation-nodejs-sketchIt
https://s3.amazonaws.com/revitio/documentation/SketchIt.mp4


问:
Android Webview: Detect when rendering is finished
I want to snapshot the WebView after the WebView is loaded. However, the returned bitmap is always null because the render  hasn't loaded completed even though I use onPageFinished.
I search on Internet and people suggest to use WebView.PictureListener, but this function is deprecated in API 12.

Some codes

```<code>public class MainActivity extends Activity {
    private WebView mButterflyWebView;

    /**
     * Gets html content from the assets folder.
     */
    private String getHtmlFromAsset() {
        InputStream is;
        StringBuilder builder = new StringBuilder();
        String htmlString = null;
        try {
            is = getAssets().open(getString(R.string.butterfly_html));
            if (is != null) {
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(is));
                String line;
                while ((line = reader.readLine()) != null) {
                    builder.append(line);
                }

                htmlString = builder.toString();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return htmlString;
    }

    /**
     * Initializes views, controls...
     */

    private void init() {
        mButterflyWebView = (WebView) findViewById(R.id.butterfly_webview);

        mButterflyWebView.setWebChromeClient(new WebChromeClient() {
        public void onProgressChanged(WebView view, int newProgress) {

            if (newProgress == 100){
                if (capturePictureWebView() != null){
                    saveBitmapToFile(capturePictureWebView());
                }
            }
        }
    });

    }

    /**
     * Loads html page with the content.
     */
    private void loadHtmlPage() {
        String htmlString = getHtmlFromAsset();
        if (htmlString != null)
            mButterflyWebView.loadDataWithBaseURL(
                    "file:///android_asset/images/", htmlString, "text/html",
                    "UTF-8", null);

        else
            Toast.makeText(this, R.string.no_such_page, Toast.LENGTH_LONG)
                    .show();
    }

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        init();
        loadHtmlPage();
    }

    private Bitmap capturePictureWebView() {
        mButterflyWebView.measure(MeasureSpec.makeMeasureSpec(
                MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED),
                MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
        mButterflyWebView.layout(0, 0, mButterflyWebView.getMeasuredWidth(),
                mButterflyWebView.getMeasuredHeight());
        mButterflyWebView.setDrawingCacheEnabled(true);
        mButterflyWebView.buildDrawingCache();

        if (mButterflyWebView.getMeasuredWidth() == 0 || mButterflyWebView.getMeasuredHeight() == 0){
            return null;
        }
        Bitmap bm = Bitmap.createBitmap(720, 1280, Bitmap.Config.ARGB_8888);

        System.out.println("width=" + mButterflyWebView.getMeasuredWidth());
        System.out.println("height=" + mButterflyWebView.getMeasuredHeight());
        Canvas bigcanvas = new Canvas(bm);
//        bigcanvas.scale(720/mButterflyWebView.getMeasuredWidth(), 1280/mButterflyWebView.getMeasuredHeight());
        Paint paint = new Paint();
        int iHeight = bm.getHeight();
        bigcanvas.drawBitmap(bm, 0, iHeight, paint);
        mButterflyWebView.draw(bigcanvas);
        return bm;
    }

    private void saveBitmapToFile(Bitmap bitmap) {
        try {

            FileOutputStream out = new FileOutputStream("/storage/sdcard0/a.png");
            bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
</code>```

答:
The renderer will not finish rendering when the OnPageFinshed method is called or the progress reaches 100% so both methods don't guarantee you that the view was completely rendered.

But you can figure out from OnLoadResource method what has been already rendered and what is still rendering. And this method gets called several times.

```<code>        @Override
        public void onLoadResource(WebView view, String url) {
            super.onLoadResource(view, url);
           // Log and see all the urls and know exactly what is being rendered and visible. If you wanna know when the entire page is completely rendered, find the last url from log and check it with if clause and implement your logic there.
            if (url.contains("assets/loginpage/img/ui/forms/")) {
                // loginpage is rendered and visible now.
               // your logic here.

            }
        }
</code>```

Body:
I want to snapshot the WebView after the WebView is loaded. However, the returned bitmap is always null because the render  hasn't loaded completed even though I use onPageFinished.
I search on Internet and people suggest to use WebView.PictureListener, but this function is deprecated in API 12.

Some codes

public class MainActivity extends Activity {
    private WebView mButterflyWebView;

    /**
     * Gets html content from the assets folder.
     */
    private String getHtmlFromAsset() {
        InputStream is;
        StringBuilder builder = new StringBuilder();
        String htmlString = null;
        try {
            is = getAssets().open(getString(R.string.butterfly_html));
            if (is != null) {
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(is));
                String line;
                while ((line = reader.readLine()) != null) {
                    builder.append(line);
                }

                htmlString = builder.toString();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return htmlString;
    }

    /**
     * Initializes views, controls...
     */

    private void init() {
        mButterflyWebView = (WebView) findViewById(R.id.butterfly_webview);

        mButterflyWebView.setWebChromeClient(new WebChromeClient() {
        public void onProgressChanged(WebView view, int newProgress) {

            if (newProgress == 100){
                if (capturePictureWebView() != null){
                    saveBitmapToFile(capturePictureWebView());
                }
            }
        }
    });

    }

    /**
     * Loads html page with the content.
     */
    private void loadHtmlPage() {
        String htmlString = getHtmlFromAsset();
        if (htmlString != null)
            mButterflyWebView.loadDataWithBaseURL(
                    "file:///android_asset/images/", htmlString, "text/html",
                    "UTF-8", null);

        else
            Toast.makeText(this, R.string.no_such_page, Toast.LENGTH_LONG)
                    .show();
    }

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        init();
        loadHtmlPage();
    }

    private Bitmap capturePictureWebView() {
        mButterflyWebView.measure(MeasureSpec.makeMeasureSpec(
                MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED),
                MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
        mButterflyWebView.layout(0, 0, mButterflyWebView.getMeasuredWidth(),
                mButterflyWebView.getMeasuredHeight());
        mButterflyWebView.setDrawingCacheEnabled(true);
        mButterflyWebView.buildDrawingCache();

        if (mButterflyWebView.getMeasuredWidth() == 0 || mButterflyWebView.getMeasuredHeight() == 0){
            return null;
        }
        Bitmap bm = Bitmap.createBitmap(720, 1280, Bitmap.Config.ARGB_8888);

        System.out.println("width=" + mButterflyWebView.getMeasuredWidth());
        System.out.println("height=" + mButterflyWebView.getMeasuredHeight());
        Canvas bigcanvas = new Canvas(bm);
//        bigcanvas.scale(720/mButterflyWebView.getMeasuredWidth(), 1280/mButterflyWebView.getMeasuredHeight());
        Paint paint = new Paint();
        int iHeight = bm.getHeight();
        bigcanvas.drawBitmap(bm, 0, iHeight, paint);
        mButterflyWebView.draw(bigcanvas);
        return bm;
    }

    private void saveBitmapToFile(Bitmap bitmap) {
        try {

            FileOutputStream out = new FileOutputStream("/storage/sdcard0/a.png");
            bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Body:
The renderer will not finish rendering when the OnPageFinshed method is called or the progress reaches 100% so both methods don't guarantee you that the view was completely rendered.

But you can figure out from OnLoadResource method what has been already rendered and what is still rendering. And this method gets called several times.

        @Override
        public void onLoadResource(WebView view, String url) {
            super.onLoadResource(view, url);
           // Log and see all the urls and know exactly what is being rendered and visible. If you wanna know when the entire page is completely rendered, find the last url from log and check it with if clause and implement your logic there.
            if (url.contains("assets/loginpage/img/ui/forms/")) {
                // loginpage is rendered and visible now.
               // your logic here.

            }
        }


问:
Keytab Validation failing
I am trying to validate a keytab file. I am getting the following error message

```<code>kinit: Keytab contains no suitable keys for HTTP/HTTP/xxxx.abc.com@abc.com while getting initial credentials
</code>```

When enabled trace I got the following messages

```<code>#KRB5_TRACE=/dev/stdout kinit -k -t xxx.keytab HTTP/xxxx.abc.com@abc.com
Using default cache: /tmp/krb5cc_1001
Using principal: HTTP/xxxx.abc.com@abc.com
Using keytab: xxx.keytab
[20299] 1557905070.909564: Getting initial credentials for HTTP/xxxx.abc.com@abc.com
[20299] 1557905070.909565: Looked up etypes in keytab: (empty)
[20299] 1557905070.909566: Getting initial credentials for HTTP/xxxx.abc.com@abc.com
[20299] 1557905070.909567: Looked up etypes in keytab: (empty)
kinit: Keytab contains no suitable keys for HTTP/HTTP/xxxx.abc.com@abc.com while getting initial credentials
</code>```

Any idea why I am getting the etypes list as empty. I created the keytab file using -crypto ALL option.

Any help in this issue is highly appreciated

答:
The issue I believe is happening when you create the keytab. I guided a colleague that was using ktutil to create a keytab, but the KDC was Active Directory. To create a keytab in AD he must use ktpass command.

Hope this helps.

Regards

Title: Keytab Validation failing

Body:
I am trying to validate a keytab file. I am getting the following error message

kinit: Keytab contains no suitable keys for HTTP/HTTP/xxxx.abc.com@abc.com while getting initial credentials

When enabled trace I got the following messages

#KRB5_TRACE=/dev/stdout kinit -k -t xxx.keytab HTTP/xxxx.abc.com@abc.com
Using default cache: /tmp/krb5cc_1001
Using principal: HTTP/xxxx.abc.com@abc.com
Using keytab: xxx.keytab
[20299] 1557905070.909564: Getting initial credentials for HTTP/xxxx.abc.com@abc.com
[20299] 1557905070.909565: Looked up etypes in keytab: (empty)
[20299] 1557905070.909566: Getting initial credentials for HTTP/xxxx.abc.com@abc.com
[20299] 1557905070.909567: Looked up etypes in keytab: (empty)
kinit: Keytab contains no suitable keys for HTTP/HTTP/xxxx.abc.com@abc.com while getting initial credentials

Any idea why I am getting the etypes list as empty. I created the keytab file using -crypto ALL option.

Any help in this issue is highly appreciated


问:
Not getting all the necessary data when going through my loop in php
I'm trying to create a page where I list all the users that sold items on different months, but each user could have sold the items on different days of the month. This is what
I'm trying to get.

```<code>January
user 1
user 4
user 5

February
user 4
user 2
user 3
</code>```

I've managed to get it to list the months, but it only displays one user per month. For example

```<code>January
user 1

February
user 4
</code>```

Here is my code

```<code>$sql = "SELECT * FROM users INNER JOIN items ON users.id = items.user_id GROUP BY Year(items.sold_date), Month(items.sold_date)";
$result = mysqli_query($con, $sql);

$mnt = "";
while($row = mysqli_fetch_array($result))
{
    if($row['sold_date'] != $mnt)
    {
        echo date('F, Y', strtotime($row['order_date']));
        echo "<br/>";
    }

    echo $row['name'];
}
</code>```

My users table

```<code>id | name   | lastname
1  | user 1 | user 1 lastname
2  | user 2 | user 2 lastname
3  | user 3 | user 3 lastname
4  | user 4 | user 4 lastname
5  | user 5 | user 5 lastname
</code>```

my items table

```<code>id| name   |description         | user_id | sold_date
1 | item 1 | item 1 description | 3       | 2017-01-25
2 | item 2 | item 2 description | 1       | 2017-01-30
3 | item 3 | item 3 description | 5       | 2017-02-14
4 | item 4 | item 4 description | 2       | 2017-05-01
5 | item 5 | item 5 description | 1       | 2018-09-06
6 | item 6 | item 6 description | 4       | 2018-10-23
</code>```

I hope I've explained properly. If not please let me know.

答:
This looked Like it gave the output you were looking for.</p>

```<code>$sql = '
SELECT
    YEAR(I.sold_date) sold_date_Y,
    MONTH(I.sold_date) sold_date_M,
    U.name,
    COUNT(I.user_id)

FROM users
    AS U

INNER JOIN items
    AS I
    ON I.user_id = U.id

GROUP BY
    YEAR(I.sold_date),
    MONTH(I.sold_date),
    U.name

ORDER BY
    YEAR(I.sold_date),
    MONTH(I.sold_date),
    U.name';

$result = mysqli_query($con, $sql);

$savYM = '';
while($row = mysqli_fetch_array($result)){
    $curYM = $row['sold_date_Y'].'-'.$row['sold_date_M'];
    if($curYM != $savYM){
        echo '<br/>'. date('F, Y', strtotime($curYM)) .'<br/>';
    }
    echo $row['name'].'<br/>';
    $savYM = $curYM;
}
</code>```

Body:
I'm trying to create a page where I list all the users that sold items on different months, but each user could have sold the items on different days of the month. This is what
I'm trying to get.

January
user 1
user 4
user 5

February
user 4
user 2
user 3

I've managed to get it to list the months, but it only displays one user per month. For example

January
user 1

February
user 4

Here is my code

$sql = "SELECT * FROM users INNER JOIN items ON users.id = items.user_id GROUP BY Year(items.sold_date), Month(items.sold_date)";
$result = mysqli_query($con, $sql);

$mnt = "";
while($row = mysqli_fetch_array($result))
{
    if($row['sold_date'] != $mnt)
    {
        echo date('F, Y', strtotime($row['order_date']));
        echo "
";
    }

    echo $row['name'];
}

My users table

id | name   | lastname
1  | user 1 | user 1 lastname
2  | user 2 | user 2 lastname
3  | user 3 | user 3 lastname
4  | user 4 | user 4 lastname
5  | user 5 | user 5 lastname

my items table

id| name   |description         | user_id | sold_date
1 | item 1 | item 1 description | 3       | 2017-01-25
2 | item 2 | item 2 description | 1       | 2017-01-30
3 | item 3 | item 3 description | 5       | 2017-02-14
4 | item 4 | item 4 description | 2       | 2017-05-01
5 | item 5 | item 5 description | 1       | 2018-09-06
6 | item 6 | item 6 description | 4       | 2018-10-23

I hope I've explained properly. If not please let me know.

Body:
This looked Like it gave the output you were looking for.

$sql = '
SELECT
    YEAR(I.sold_date) sold_date_Y,
    MONTH(I.sold_date) sold_date_M,
    U.name,
    COUNT(I.user_id)

FROM users
    AS U

INNER JOIN items
    AS I
    ON I.user_id = U.id

GROUP BY
    YEAR(I.sold_date),
    MONTH(I.sold_date),
    U.name

ORDER BY
    YEAR(I.sold_date),
    MONTH(I.sold_date),
    U.name';

$result = mysqli_query($con, $sql);

$savYM = '';
while($row = mysqli_fetch_array($result)){
    $curYM = $row['sold_date_Y'].'-'.$row['sold_date_M'];
    if($curYM != $savYM){
        echo '<br/>'. date('F, Y', strtotime($curYM)) .'<br/>';
    }
    echo $row['name'].'<br/>';
    $savYM = $curYM;
}


问:
Android Material Calendar View how to highlight date range with rounded corner background?
Currently I working of prolificinteractive Material Calendar View from github. I able to setBackgroundDrawable of selected the date I wanted. But for now I want to set setBackgroundDrawable of the range of the date as picture below:

How do I can achieve this kind of rounded corner image background when I got a range of the date. Example From date 18th March 2014 to 22th March 2014.

Link:

https://github.com/prolificinteractive/material-calendarview

答:
I implemented like this:

find smaple code here->
https://github.com/Thanvandh/Date-Range-Highlight

MainActivity.java

```<code>final List<String> pinkDateList = Arrays.asList(
        "2019-01-01",
        "2019-01-03", "2019-01-04", "2019-01-05", "2019-01-06");
final List<String> grayDateList = Arrays.asList(
        "2019-01-09", "2019-01-10", "2019-01-11",
        "2019-01-24", "2019-01-25", "2019-01-26", "2019-01-27", "2019-01-28", "2019-01-29");

final String DATE_FORMAT = "yyyy-MM-dd";

int pink = 0;
int gray = 1;

MaterialCalendarView calendarView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    calendarView = findViewById(R.id.calendarView);
    calendarView.setShowOtherDates(MaterialCalendarView.SHOW_ALL);

    final LocalDate min = getLocalDate("2019-01-01");
    final LocalDate max = getLocalDate("2019-12-30");

    calendarView.state().edit().setMinimumDate(min).setMaximumDate(max).commit();

    setEvent(pinkDateList, pink);
    setEvent(grayDateList, gray);

    calendarView.invalidateDecorators();
}

void setEvent(List<String> dateList, int color) {
    List<LocalDate> localDateList = new ArrayList<>();

    for (String string : dateList) {
        LocalDate calendar = getLocalDate(string);
        if (calendar != null) {
            localDateList.add(calendar);
        }
    }

    List<CalendarDay> datesLeft = new ArrayList<>();
    List<CalendarDay> datesCenter = new ArrayList<>();
    List<CalendarDay> datesRight = new ArrayList<>();
    List<CalendarDay> datesIndependent = new ArrayList<>();

    for (LocalDate localDate : localDateList) {

        boolean right = false;
        boolean left = false;

        for (LocalDate day1 : localDateList) {

            if (localDate.isEqual(day1.plusDays(1))) {
                left = true;
            }
            if (day1.isEqual(localDate.plusDays(1))) {
                right = true;
            }
        }

        if (left && right) {
            datesCenter.add(CalendarDay.from(localDate));
        } else if (left) {
            datesLeft.add(CalendarDay.from(localDate));
        } else if (right) {
            datesRight.add(CalendarDay.from(localDate));
        } else {
            datesIndependent.add(CalendarDay.from(localDate));
        }
    }

    if (color == pink) {
        setDecor(datesCenter, R.drawable.p_center);
        setDecor(datesLeft, R.drawable.p_left);
        setDecor(datesRight, R.drawable.p_right);
        setDecor(datesIndependent, R.drawable.p_independent);
    } else {
        setDecor(datesCenter, R.drawable.g_center);
        setDecor(datesLeft, R.drawable.g_left);
        setDecor(datesRight, R.drawable.g_right);
        setDecor(datesIndependent, R.drawable.g_independent);
    }
}

void setDecor(List<CalendarDay> calendarDayList, int drawable) {
    calendarView.addDecorators(new EventDecorator(MainActivity.this
            , drawable
            , calendarDayList));
}

LocalDate getLocalDate(String date) {
    SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT, Locale.ENGLISH);
    try {
        Date input = sdf.parse(date);
        Calendar cal = Calendar.getInstance();
        cal.setTime(input);
        return LocalDate.of(cal.get(Calendar.YEAR),
                cal.get(Calendar.MONTH) + 1,
                cal.get(Calendar.DAY_OF_MONTH));

    } catch (NullPointerException e) {
        return null;
    } catch (ParseException e) {
        return null;
    }
}
</code>```

EventDecorator.java

```<code>public class EventDecorator implements DayViewDecorator {
Context context;
private int drawable;
private HashSet<CalendarDay> dates;

public EventDecorator(Context context, int drawable, List<CalendarDay> calendarDays1) {
    this.context = context;
    this.drawable = drawable;
    this.dates = new HashSet<>(calendarDays1);
}

@Override
public boolean shouldDecorate(CalendarDay day) {
    return dates.contains(day);
}

@Override
public void decorate(DayViewFacade view) {
    // apply drawable to dayView
    view.setSelectionDrawable(context.getResources().getDrawable(drawable));
    // white text color
    view.addSpan(new ForegroundColorSpan(Color.WHITE));
}
}
</code>```

Body:
I implemented like this:

find smaple code here->
https://github.com/Thanvandh/Date-Range-Highlight

MainActivity.java

final List<String> pinkDateList = Arrays.asList(
        "2019-01-01",
        "2019-01-03", "2019-01-04", "2019-01-05", "2019-01-06");
final List<String> grayDateList = Arrays.asList(
        "2019-01-09", "2019-01-10", "2019-01-11",
        "2019-01-24", "2019-01-25", "2019-01-26", "2019-01-27", "2019-01-28", "2019-01-29");

final String DATE_FORMAT = "yyyy-MM-dd";

int pink = 0;
int gray = 1;

MaterialCalendarView calendarView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    calendarView = findViewById(R.id.calendarView);
    calendarView.setShowOtherDates(MaterialCalendarView.SHOW_ALL);

    final LocalDate min = getLocalDate("2019-01-01");
    final LocalDate max = getLocalDate("2019-12-30");

    calendarView.state().edit().setMinimumDate(min).setMaximumDate(max).commit();

    setEvent(pinkDateList, pink);
    setEvent(grayDateList, gray);

    calendarView.invalidateDecorators();
}

void setEvent(List<String> dateList, int color) {
    List<LocalDate> localDateList = new ArrayList<>();

    for (String string : dateList) {
        LocalDate calendar = getLocalDate(string);
        if (calendar != null) {
            localDateList.add(calendar);
        }
    }

    List<CalendarDay> datesLeft = new ArrayList<>();
    List<CalendarDay> datesCenter = new ArrayList<>();
    List<CalendarDay> datesRight = new ArrayList<>();
    List<CalendarDay> datesIndependent = new ArrayList<>();

    for (LocalDate localDate : localDateList) {

        boolean right = false;
        boolean left = false;

        for (LocalDate day1 : localDateList) {

            if (localDate.isEqual(day1.plusDays(1))) {
                left = true;
            }
            if (day1.isEqual(localDate.plusDays(1))) {
                right = true;
            }
        }

        if (left && right) {
            datesCenter.add(CalendarDay.from(localDate));
        } else if (left) {
            datesLeft.add(CalendarDay.from(localDate));
        } else if (right) {
            datesRight.add(CalendarDay.from(localDate));
        } else {
            datesIndependent.add(CalendarDay.from(localDate));
        }
    }

    if (color == pink) {
        setDecor(datesCenter, R.drawable.p_center);
        setDecor(datesLeft, R.drawable.p_left);
        setDecor(datesRight, R.drawable.p_right);
        setDecor(datesIndependent, R.drawable.p_independent);
    } else {
        setDecor(datesCenter, R.drawable.g_center);
        setDecor(datesLeft, R.drawable.g_left);
        setDecor(datesRight, R.drawable.g_right);
        setDecor(datesIndependent, R.drawable.g_independent);
    }
}

void setDecor(List<CalendarDay> calendarDayList, int drawable) {
    calendarView.addDecorators(new EventDecorator(MainActivity.this
            , drawable
            , calendarDayList));
}

LocalDate getLocalDate(String date) {
    SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT, Locale.ENGLISH);
    try {
        Date input = sdf.parse(date);
        Calendar cal = Calendar.getInstance();
        cal.setTime(input);
        return LocalDate.of(cal.get(Calendar.YEAR),
                cal.get(Calendar.MONTH) + 1,
                cal.get(Calendar.DAY_OF_MONTH));

    } catch (NullPointerException e) {
        return null;
    } catch (ParseException e) {
        return null;
    }
}

EventDecorator.java

public class EventDecorator implements DayViewDecorator {
Context context;
private int drawable;
private HashSet<CalendarDay> dates;

public EventDecorator(Context context, int drawable, List<CalendarDay> calendarDays1) {
    this.context = context;
    this.drawable = drawable;
    this.dates = new HashSet<>(calendarDays1);
}

@Override
public boolean shouldDecorate(CalendarDay day) {
    return dates.contains(day);
}

@Override
public void decorate(DayViewFacade view) {
    // apply drawable to dayView
    view.setSelectionDrawable(context.getResources().getDrawable(drawable));
    // white text color
    view.addSpan(new ForegroundColorSpan(Color.WHITE));
}
}


问:
JavaScript querySelector versions of Jquery
I am trying to move away from JQuery.

I have a div called 'clientProfiles'

```<code><div class="paperlist" data-role='listview' data-inset='true' data-split-icon='delete' id='clientProfiles'></div>
</code>```

my application will fill the 'div' with buttons like so.

```<code>function getClientHtml(device) {

                var html = "";
                html += '<div data-name="' + device.Name + '" data-id="' + device.Id + '"data-app="' + device.AppName + '" style="border-radius: 2px; border: 1px solid rgba(0,0,0,0.158)" class="clientProfile listItem">';
                html += '<img style="float-left; width:3%;" src="' + deviceNameImage(device.Name) + '"/>';
                html += '<div class="listItemBody">';
                html += '<h3 class="listItemBodyText">' + device.Name + ' - ' + device.AppName + '</h3>';
                html += '</div>';
                html += '<i class="md-icon btnDeleteProfile" data-index="0">close</i>';
                html += '</div>';
                html += '<br />';
                return html;
            };
</code>```

The html after a button has been added by a user looks like this:

```<code><div class="paperlist" data-role="listview" data-inset="true" data-split-icon="delete" id="clientProfiles">
<div data-name="Xbox One" data-id="mcX7xXZksA1fJooKY2SRS5soNbFgM4lQurFx3bxr2s" data-app="Theater" style="border-radius: 2px; border: 1px solid rgba(0,0,0,0.158)" class="clientProfile listItem">
<img style="float-left; width:3%;" src="../images/devices/xboxone.png"><div class="listItemBody"><h3 class="listItemBodyText">XBLAHBLAHNAME</h3>
</div>
<i class="md-icon btnDeleteProfile" data-index="0">close</i>
</div>
<br>
</div>
</code>```

These dynamically created buttons can be removed from the page by clicking an icon  inside the main button labeled with a with a class called '.btnDeleteProfile'.

When I wanted to add a click event to my 'btnDeleteProfile' in JQuery I could use this:

```<code> $('#clientProfiles', page).on('click', '.btnDeleteProfile', function () {});
</code>```

But now that I am not using JQuery, I'm having an issue targeting the '.btnDeleteProfile'.

document.querySelector('.btnDeleteProfile').addEventListener('click', function() {});

However MDN says that querySelector will only find the first instance of this, and there could very well be a ton of these buttons created all with different profile info attached.

the query Selector can't find the 'btnDeleteProfile'.

The error I am experiencing is 'can't add click event to null.

答:
You could generalize this a bit, by making your own delegate event listener logic.

Bind the event listener to the parent

When the event happens, find all the children of the parent that match the child selector

If the element the event originated from is in that child list, apply the event callback to it.

Element.prototype.addDelegateEventListener = function (eventType, childSelector, callback) {
  var parentElement = this;

  parentElement.addEventListener(eventType, function(event){
    var children = [...parentElement.querySelectorAll(childSelector)];

    if (children.includes(event.target)) {
      callback.apply(event.target, arguments);
    }
  });
};

document.getElementsByTagName('button')[0].addEventListener('click', function(){
  document.querySelector('#parent').innerHTML += `<div class="clickMe" data-created-on="${Date.now()}">Click Me</div>`;
});

document.getElementById('parent').addDelegateEventListener( 'click', '.clickMe', function(e){
  console.log(this);
  console.log(e.target);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button>Add Element</button>
<div id="parent">
  <div>No Match</div>
  <div>
    <div class="clickMe">Indirect Child</div>
  </div>
</div></code>```

Body:
I am trying to move away from JQuery.

I have a div called 'clientProfiles'

my application will fill the 'div' with buttons like so.

function getClientHtml(device) {

                var html = "";
                html += '
';
                html += '';
                html += '
';
                html += '
' + device.Name + ' - ' + device.AppName + '
';
                html += '
';
                html += 'close';
                html += '
';
                html += '
';
                return html;
            };

The html after a button has been added by a user looks like this:

XBLAHBLAHNAME

close

These dynamically created buttons can be removed from the page by clicking an icon  inside the main button labeled with a with a class called '.btnDeleteProfile'.

When I wanted to add a click event to my 'btnDeleteProfile' in JQuery I could use this:

 $('#clientProfiles', page).on('click', '.btnDeleteProfile', function () {});

But now that I am not using JQuery, I'm having an issue targeting the '.btnDeleteProfile'.

document.querySelector('.btnDeleteProfile').addEventListener('click', function() {});

However MDN says that querySelector will only find the first instance of this, and there could very well be a ton of these buttons created all with different profile info attached.

the query Selector can't find the 'btnDeleteProfile'.

The error I am experiencing is 'can't add click event to null.

Body:
You could generalize this a bit, by making your own delegate event listener logic.

Bind the event listener to the parent

When the event happens, find all the children of the parent that match the child selector

If the element the event originated from is in that child list, apply the event callback to it.

Element.prototype.addDelegateEventListener = function (eventType, childSelector, callback) {
  var parentElement = this;

  parentElement.addEventListener(eventType, function(event){
    var children = [...parentElement.querySelectorAll(childSelector)];

    if (children.includes(event.target)) {
      callback.apply(event.target, arguments);
    }
  });
};

document.getElementsByTagName('button')[0].addEventListener('click', function(){
  document.querySelector('#parent').innerHTML += `<div class="clickMe" data-created-on="${Date.now()}">Click Me</div>`;
});

document.getElementById('parent').addDelegateEventListener( 'click', '.clickMe', function(e){
  console.log(this);
  console.log(e.target);
});

<button>Add Element</button>
<div id="parent">
  <div>No Match</div>
  <div>
    <div class="clickMe">Indirect Child</div>
  </div>
</div>


问:
Cluetip for every dynamically generated row in table
I would like to display cluetip [jQuery] plugin for every row of dynamic grid in .aspx  page. The content in cluetip should be fetched from database dynamically while loading the cluetip plugin.

Can anyone suggest any way of doing this?

答:
the thing with the dynamic content is easy (when you now how) ^^
just append an id as an GET-Var on the link (test.com$id=3) and catch it within the cluetip-content ($id = $_GET['id']).

There is still another way with the ajax-settings, but it doesn't work well for me

Cheers,
Chris

ContentLicense: CC BY-SA 2.5


问:
Inserting empty values as string to sql table
I have a project which has a Class which has some members as string which equal "". My teacher had shown examples with Class members declared as String = "NULL". I try to insert to SQL and I get this message:

Error insertion... Error converting data type varchar to numeric.

I know many will suggest to use parameterized values for inserting but I like to finish the way I started this.

I have tried to cast query string Object values with CDec, CInt, Cbit and still no clue how to do it right because I got Exceptions for trying to cast an "".

Also, I have changed to default values of members like this;

Dim NumberOfPackage As String = ""
```

<p>instead of;</p>

<pre class="lang-vb prettyprint-override"><code>Dim NumberOfPackage As String = "NULL"
</code>```

Some Columns in SQL table had ALLOW NULL checkBox set to NOT allowed, I changed the design of the Table to make it easier for insertion.

答: The field in database have been set to not null? I think that dbnull.value do what you want</p>

Body:
I have a project which has a Class which has some members as string which equal "". My teacher had shown examples with Class members declared as String = "NULL". I try to insert to SQL and I get this message:

Error insertion... Error converting data type varchar to numeric.

I know many will suggest to use parameterized values for inserting but I like to finish the way I started this.

I have tried to cast query string Object values with CDec, CInt, Cbit and still no clue how to do it right because I got Exceptions for trying to cast an "".

Also, I have changed to default values of members like this;

Dim NumberOfPackage As String = ""

instead of;

Dim NumberOfPackage As String = "NULL"

Some Columns in SQL table had ALLOW NULL checkBox set to NOT allowed, I changed the design of the Table to make it easier for insertion.


问:
SpringbootTest + TestContainers: how do I refresh the database after tests pollute the database
I am using an abstract class like this:

```<code>@SpringBootTest(classes = MyAppApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT)
@ActiveProfiles("test")
public abstract class AbstractIntegrationTest {

    static {
        PostgreSQLContainer postgreSQLContainer = new PostgreSQLContainer().withPassword("password")
                .withUsername("postgres").withDatabaseName("MyApp");
        postgreSQLContainer.start();

        System.setProperty("spring.datasource.url", postgreSQLContainer.getJdbcUrl());
        System.setProperty("spring.datasource.password", postgreSQLContainer.getPassword());
        System.setProperty("spring.datasource.username", postgreSQLContainer.getUsername());

    }
</code>```

Then I have many tests that leverage that use that class like this:

```<code>public class moreTests extends AbstractIntegrationTest {

    TestRestTemplate restTemplate = new TestRestTemplate("my-user", "password");
    HttpHeaders headers = new HttpHeaders();

    @Test
    public void SimpleHealthCheck() {
        HttpEntity<String> entity = new HttpEntity<String>(null, headers);
        ResponseEntity<String> response = restTemplate.exchange(
                createURLWithPort("/api/v1/healthcheck"),
                HttpMethod.GET, entity, String.class);
        assertThat(response.getStatusCode(), equalTo(HttpStatus.OK));
    }

    @Test
    public void GetInst() {
        HttpEntity<String> entity = new HttpEntity<String>(null, headers);
        ResponseEntity<String> response = restTemplate.exchange(
                createURLWithPort("/api/v1/institutions"),
                HttpMethod.GET, entity, String.class);
        assertThat(response.getStatusCode(), equalTo(HttpStatus.OK));
    }
</code>```

However, some of my tests will pollute the database.  I'd like to control if a test runs with a fresh database or not.  What's the prescribed way to do this?

答:
After more reading about Spring boot integration testing, it appears the prescribed way is to use the "@DirtiesContext" annotation for tests that are destructive (or dirty).

EDIT:  After a few months, I realized @DirtiesContext is not awesome.  It basically resets the whole app which can be expensive.  Also, @DirtiesContext May not reset your database in some cases depending on how your app works.  I suggest having a cleanup SQL script that runs in your @BeforeAll or @AfterAll section of each test class.  This cleanup SQL script needs to be carefully written.

Body:
I am using an abstract class like this:

@SpringBootTest(classes = MyAppApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT)
@ActiveProfiles("test")
public abstract class AbstractIntegrationTest {

    static {
        PostgreSQLContainer postgreSQLContainer = new PostgreSQLContainer().withPassword("password")
                .withUsername("postgres").withDatabaseName("MyApp");
        postgreSQLContainer.start();

        System.setProperty("spring.datasource.url", postgreSQLContainer.getJdbcUrl());
        System.setProperty("spring.datasource.password", postgreSQLContainer.getPassword());
        System.setProperty("spring.datasource.username", postgreSQLContainer.getUsername());

    }

Then I have many tests that leverage that use that class like this:

public class moreTests extends AbstractIntegrationTest {

    TestRestTemplate restTemplate = new TestRestTemplate("my-user", "password");
    HttpHeaders headers = new HttpHeaders();

    @Test
    public void SimpleHealthCheck() {
        HttpEntity<String> entity = new HttpEntity<String>(null, headers);
        ResponseEntity<String> response = restTemplate.exchange(
                createURLWithPort("/api/v1/healthcheck"),
                HttpMethod.GET, entity, String.class);
        assertThat(response.getStatusCode(), equalTo(HttpStatus.OK));
    }

    @Test
    public void GetInst() {
        HttpEntity<String> entity = new HttpEntity<String>(null, headers);
        ResponseEntity<String> response = restTemplate.exchange(
                createURLWithPort("/api/v1/institutions"),
                HttpMethod.GET, entity, String.class);
        assertThat(response.getStatusCode(), equalTo(HttpStatus.OK));
    }

However, some of my tests will pollute the database.  I'd like to control if a test runs with a fresh database or not.  What's the prescribed way to do this?


问:
Any way to block access to Tor's directory server for bridge testing purposes? (Simulating a restricted network)
For testing purposes, I would like to simulate a restricted network that would block access to Tor's directory server.

In other words, I would like to reproduce this error that would normally occur if one is on a restricted network:

```<code>[warn] Problem bootstrapping. Stuck at 10%: Finishing handshake with directory server.
</code>```

Anyone know how to achieve this, or what server ip I should be blocking?

答:
Tor doesn't have a single directory server.  Newer versions will try to contact directory authorities and directory fallbacks.  The fallback directory list updates occasionally.

See Section 5.1 of the Tor directory specification for more details.

Body:
For testing purposes, I would like to simulate a restricted network that would block access to Tor's directory server.

In other words, I would like to reproduce this error that would normally occur if one is on a restricted network:

[warn] Problem bootstrapping. Stuck at 10%: Finishing handshake with directory server.

Anyone know how to achieve this, or what server ip I should be blocking?


问:
What's wrong in this loop?
I checked and i don't found errors:

```<code>$_SESSION['variable'] = 2
$preparado[1] = "Miguel";
$preparado[2] = "Carlos";
$segundo[1]= "Beltran";
$segundo[2] = "Sanz";

for($i = 1; $i <=$_SESSION['variable']; $i++){
  $listo[$i] = $preparado1[$i] . $segundo[1];
}

for($i = ($_SESSION['variable'] + 1) ; $i <= ($_SESSION['variable'] * 2); $i++){
  for($n = 1; $n <=$_SESSION['variable']; $n++){
    $listo[$i] = $preparado1[$n] . $segundo[2];
  }
}

for($i = 1;$i <=$_SESSION['variable'] * $_SESSION['extension']; $i++ ){
  echo   $final[$i] . "</br>";
}
</code>```

I  recibe this:

```<code>MiguelBeltran
CarlosBeltran
CarlosSanz
CarlosSanz
</code>```

But I should recibe this:

```<code>MiguelBeltran
CarlosBeltran
MiguelSanz
CarlosSanz
</code>```

Thanks!!

答:
Given:

```<code>$_SESSION['variable'] = 2
$preparado[1] = "Miguel";
$preparado[2] = "Carlos";
$segundo[1]= "Beltran";
$segundo[2] = "Sanz";
</code>```

Use:

```<code>for ($i = 1; $i <= $_SESSION['variable']; ++$i) {
    for ($j = 1; $j <= $_SESSION['variable']; ++$j) {
        $listo[] = $preparado[$j].$segundo[$i];
    }
}
</code>```

Title: What's wrong in this loop?

Body:
I checked and i don't found errors:

$_SESSION['variable'] = 2
$preparado[1] = "Miguel";
$preparado[2] = "Carlos";
$segundo[1]= "Beltran";
$segundo[2] = "Sanz";

for($i = 1; $i <=$_SESSION['variable']; $i++){
  $listo[$i] = $preparado1[$i] . $segundo[1];
}

for($i = ($_SESSION['variable'] + 1) ; $i <= ($_SESSION['variable'] * 2); $i++){
  for($n = 1; $n <=$_SESSION['variable']; $n++){
    $listo[$i] = $preparado1[$n] . $segundo[2];
  }
}

for($i = 1;$i <=$_SESSION['variable'] * $_SESSION['extension']; $i++ ){
  echo   $final[$i] . "
";
}

I  recibe this:

MiguelBeltran
CarlosBeltran
CarlosSanz
CarlosSanz

But I should recibe this:

MiguelBeltran
CarlosBeltran
MiguelSanz
CarlosSanz

Thanks!!

Body:
Given:

$_SESSION['variable'] = 2
$preparado[1] = "Miguel";
$preparado[2] = "Carlos";
$segundo[1]= "Beltran";
$segundo[2] = "Sanz";

Use:

for ($i = 1; $i <= $_SESSION['variable']; ++$i) {
    for ($j = 1; $j <= $_SESSION['variable']; ++$j) {
        $listo[] = $preparado[$j].$segundo[$i];
    }
}


问:
How to make a BootstrapVue tooltip fade away after 2 seconds?
I created a button that when clicked, copies some text and shows me a tooltip, acknowledging that the text was copied. I want to make the tooltip fade away after 2 seconds.

I tried to use a timeOut() method to fade away the tooltip, but it doesn't work. I'm using the tooltip from BootstrapVue. How can I solve this?

Copy Translation

  Text Copied

```

答:
You could programmatically show/hide the tooltip by binding .show to a Boolean that is set false after a setTimeout-delay:

<template>

    Copy

</template>

```

Body:
You could programmatically show/hide the tooltip by binding <b-tooltip>.show to a Boolean that is set false after a setTimeout-delay:

<template>
  <div>
    <b-button id="copyBtn" @click="showTooltip = true">Copy</b-button>
    <b-tooltip target="copyBtn"
               :show.sync="showTooltip"
               @shown="hideTooltipLater"
               triggers
               title="Text Copied">
    </b-tooltip>
  </div>
</template>

<script>
export default {
  data() {
    return {
      showTooltip: false
    };
  },
  methods: {
    hideTooltipLater() {
      setTimeout(() => {
        this.showTooltip = false;
      }, 2000);
    }
  }
};
</script>


问:
Why doesn't javascript parse HTML from fetch?
I'm creating a chrome extension that scrapes photos from various websites. I have the URLs of each website and I want to fetch and parse those websites, and then grab specific img elements by class or ID.

I'm using the Javascript fetch() function together with DOMParser to parse the HTML and it returns the Document successfully, but any DOM query returns empty NodeLists / HTMLCollections.

```<code>fetch("www.example.com")
.then(res => {
    const parser = new DOMParser();
    const htmlDoc = parser.parseFromString(res, "text/html");
    console.log(htmlDoc.querySelectorAll('h1'))
})
</code>```

This gives me an empty NodeList. Why?? And how can I get the elements I'm looking for?

答:
You'll need to parse the response before you use it. Like this:

fetch("//randycasburn.com")
  .then(res => res.text())
  .then(html => {
    const parser = new DOMParser();
    const htmlDoc = parser.parseFromString(html, "text/html");
    console.log(htmlDoc.querySelector('span').textContent)
  })```
</div>
</div>
</p>

<p>Otherwise by passing <code>res</code> itself a DOM will be created and <code>res</code> will be casted to a string (<code>[object Response]</code>), which results in this DOM: (note no H1)</p>

```

  [object Response]

```

Body:
I'm creating a chrome extension that scrapes photos from various websites. I have the URLs of each website and I want to fetch and parse those websites, and then grab specific img elements by class or ID.

I'm using the Javascript fetch() function together with DOMParser to parse the HTML and it returns the Document successfully, but any DOM query returns empty NodeLists / HTMLCollections.

fetch("www.example.com")
.then(res => {
    const parser = new DOMParser();
    const htmlDoc = parser.parseFromString(res, "text/html");
    console.log(htmlDoc.querySelectorAll('h1'))
})

This gives me an empty NodeList. Why?? And how can I get the elements I'm looking for?

Body:
You'll need to parse the response before you use it. Like this:

fetch("//randycasburn.com")
  .then(res => res.text())
  .then(html => {
    const parser = new DOMParser();
    const htmlDoc = parser.parseFromString(html, "text/html");
    console.log(htmlDoc.querySelector('span').textContent)
  })

Otherwise by passing res itself a DOM will be created and res will be casted to a string ([object Response]), which results in this DOM: (note no H1)

<html>
  <head></head>
  <body>[object Response]</body>
</html>


问:
How to use complex or irregular shape as my roi for image detection and tracking using mouse function?
I am currently trying to create roi of complex/irregular shape for detection and tracking.But unable to create it.

I am able to draw a curve around my complex shape using mouse callbackfunction but i don't know how to use my closed curve for roi.

This is the frame from the video which I am working on.

Image 1

Image 2

The shape in the image2 is the area I want my roi to be for tracking.I don't want my roi to be rectangle in shape because it is not able to track my roi. The shape in the image2 is actually an object which I want to track in the video.

Below is the code for tracking with rectangle roi.

```<code>import cv2
import sys
from matplotlib import pyplot as plt

(major_ver, minor_ver, subminor_ver) = (cv2.__version__).split('.')

# Set up tracker.
# Instead of MIL, you can also use

tracker_types = ['BOOSTING', 'MIL','KCF', 'TLD', 'MEDIANFLOW', 'GOTURN', 'MOSSE', 'CSRT']
tracker_type = tracker_types[1]

if tracker_type == 'BOOSTING':
    tracker = cv2.TrackerBoosting_create()
elif tracker_type == 'MIL':
    tracker = cv2.TrackerMIL_create()
elif tracker_type == 'KCF':
    tracker = cv2.TrackerKCF_create()
elif tracker_type == 'TLD':
    tracker = cv2.TrackerTLD_create()
elif tracker_type == 'MEDIANFLOW':
    tracker = cv2.TrackerMedianFlow_create()
elif tracker_type == 'GOTURN':
    tracker = cv2.TrackerGOTURN_create()
elif tracker_type == 'MOSSE':
    tracker = cv2.TrackerMOSSE_create()
elif tracker_type == "CSRT":
    tracker = cv2.TrackerCSRT_create()

# Read video
video = cv2.VideoCapture("3umresize4.avi")

# Exit if video not opened.
if not video.isOpened():
    print "Could not open video"
    sys.exit()

# Read first frame.
ok, frame = video.read()
if not ok:
    print 'Cannot read video file'
    sys.exit()

# Define an initial bounding box
bbox = (287, 23, 86, 320)

# Uncomment the line below to select a different bounding box
bbox = cv2.selectROI(frame, False)

# Initialize tracker with first frame and bounding box
ok = tracker.init(frame, bbox)

while True:
    # Read a new frame
    ok, frame = video.read()
    if not ok:
        break

    # Start timer
    timer = cv2.getTickCount()

    # Update tracker
    ok, bbox = tracker.update(frame)

    # Calculate Frames per second (FPS)
    fps = cv2.getTickFrequency() / (cv2.getTickCount() - timer);

    # Draw bounding box
    if ok:
        # Tracking success
        p1 = (int(bbox[0]), int(bbox[1]))
        p2 = (int(bbox[0] + bbox[2]), int(bbox[1] + bbox[3]))
        cv2.rectangle(frame, p1, p2, (255,0,0), 2, 1)
    else :
        # Tracking failure
        cv2.putText(frame, "Tracking failure detected", (100,80), cv2.FONT_HERSHEY_SIMPLEX, 0.75,(0,0,255),2)

    # Display tracker type on frame
    cv2.putText(frame, tracker_type + " Tracker", (100,20), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (50,170,50),2);

    # Display FPS on frame
    cv2.putText(frame, "FPS : " + str(int(fps)), (100,50), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (50,170,50), 2);

    # Display result
    cv2.namedWindow("Tracking",cv2.WINDOW_NORMAL)
    cv2.imshow("Tracking", frame)

    # Exit if ESC pressed
    k = cv2.waitKey(1) & 0xff
    if k == 27 :

        break

cv2.destroyAllWindows()
</code>```

Below is the mouse callback to create image2 in which I want the area under the contour to be the roi in the above code.

```<code>import cv2
import numpy as np

drawing=False # true if mouse is pressed
mode=True # if True, draw rectangle. Press 'm' to toggle to curve

# mouse callback function
def drawcurve(event,former_x,former_y,flags,param):
    global current_former_x,current_former_y,drawing, mode

    if event==cv2.EVENT_LBUTTONDOWN:
        drawing=True
        current_former_x,current_former_y=former_x,former_y

    elif event==cv2.EVENT_MOUSEMOVE:
        if drawing==True:
            if mode==True:
                cv2.line(im,(current_former_x,current_former_y),(former_x,former_y),(0,0,255),5)
                current_former_x = former_x
                current_former_y = former_y
                #print former_x,former_y
    elif event==cv2.EVENT_LBUTTONUP:
        drawing=False
        if mode==True:
            cv2.line(im,(current_former_x,current_former_y),(former_x,former_y),(0,0,255),5)
            current_former_x = former_x
            current_former_y = former_y
    return former_x,former_y

im = cv2.imread("sampleuct.bmp")
cv2.namedWindow("Bill BEGUERADJ OpenCV")
cv2.setMouseCallback('Bill BEGUERADJ OpenCV',drawcurve)
while(1):
    cv2.imshow('Bill BEGUERADJ OpenCV',im)
    k=cv2.waitKey(1)&0xFF
    if k==27:
        break
cv2.destroyAllWindows()
</code>```

Can you help me out it integrating my roi with tracking. Or any other way I could track it.

答:
OpenCV's functions will not directly get you what you want, all these trackers are designed to do specific things which in the end track a localised region which is a box.

Since you want to track the shape as it is you may consider Kalman Filter based tracking, where you essentially track points. You could pick points of interest and connnect them in every frame and track only these points. You may want to implement one yourself too. You can refer this link as a tutorial to directly use OpenCV's implementation of Kalman Filter tracking.

You could also consider a deep learning based approach by using Semantic Networks, where you segment regions of interest at every frame.

One dirty trick is to create your roi as it is and every time the box is detected, you could adjust your roi size to the box size as required and use it.

Body:
I am currently trying to create roi of complex/irregular shape for detection and tracking.But unable to create it.

I am able to draw a curve around my complex shape using mouse callbackfunction but i don't know how to use my closed curve for roi.

This is the frame from the video which I am working on.

Image 1

Image 2

The shape in the image2 is the area I want my roi to be for tracking.I don't want my roi to be rectangle in shape because it is not able to track my roi. The shape in the image2 is actually an object which I want to track in the video.

Below is the code for tracking with rectangle roi.

import cv2
import sys
from matplotlib import pyplot as plt

(major_ver, minor_ver, subminor_ver) = (cv2.__version__).split('.')

# Set up tracker.
# Instead of MIL, you can also use

tracker_types = ['BOOSTING', 'MIL','KCF', 'TLD', 'MEDIANFLOW', 'GOTURN', 'MOSSE', 'CSRT']
tracker_type = tracker_types[1]

if tracker_type == 'BOOSTING':
    tracker = cv2.TrackerBoosting_create()
elif tracker_type == 'MIL':
    tracker = cv2.TrackerMIL_create()
elif tracker_type == 'KCF':
    tracker = cv2.TrackerKCF_create()
elif tracker_type == 'TLD':
    tracker = cv2.TrackerTLD_create()
elif tracker_type == 'MEDIANFLOW':
    tracker = cv2.TrackerMedianFlow_create()
elif tracker_type == 'GOTURN':
    tracker = cv2.TrackerGOTURN_create()
elif tracker_type == 'MOSSE':
    tracker = cv2.TrackerMOSSE_create()
elif tracker_type == "CSRT":
    tracker = cv2.TrackerCSRT_create()

# Read video
video = cv2.VideoCapture("3umresize4.avi")

# Exit if video not opened.
if not video.isOpened():
    print "Could not open video"
    sys.exit()

# Read first frame.
ok, frame = video.read()
if not ok:
    print 'Cannot read video file'
    sys.exit()

# Define an initial bounding box
bbox = (287, 23, 86, 320)

# Uncomment the line below to select a different bounding box
bbox = cv2.selectROI(frame, False)

# Initialize tracker with first frame and bounding box
ok = tracker.init(frame, bbox)

while True:
    # Read a new frame
    ok, frame = video.read()
    if not ok:
        break

    # Start timer
    timer = cv2.getTickCount()

    # Update tracker
    ok, bbox = tracker.update(frame)

    # Calculate Frames per second (FPS)
    fps = cv2.getTickFrequency() / (cv2.getTickCount() - timer);

    # Draw bounding box
    if ok:
        # Tracking success
        p1 = (int(bbox[0]), int(bbox[1]))
        p2 = (int(bbox[0] + bbox[2]), int(bbox[1] + bbox[3]))
        cv2.rectangle(frame, p1, p2, (255,0,0), 2, 1)
    else :
        # Tracking failure
        cv2.putText(frame, "Tracking failure detected", (100,80), cv2.FONT_HERSHEY_SIMPLEX, 0.75,(0,0,255),2)

    # Display tracker type on frame
    cv2.putText(frame, tracker_type + " Tracker", (100,20), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (50,170,50),2);

    # Display FPS on frame
    cv2.putText(frame, "FPS : " + str(int(fps)), (100,50), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (50,170,50), 2);

    # Display result
    cv2.namedWindow("Tracking",cv2.WINDOW_NORMAL)
    cv2.imshow("Tracking", frame)

    # Exit if ESC pressed
    k = cv2.waitKey(1) & 0xff
    if k == 27 :

        break

cv2.destroyAllWindows()

Below is the mouse callback to create image2 in which I want the area under the contour to be the roi in the above code.

import cv2
import numpy as np

drawing=False # true if mouse is pressed
mode=True # if True, draw rectangle. Press 'm' to toggle to curve

# mouse callback function
def drawcurve(event,former_x,former_y,flags,param):
    global current_former_x,current_former_y,drawing, mode

    if event==cv2.EVENT_LBUTTONDOWN:
        drawing=True
        current_former_x,current_former_y=former_x,former_y

    elif event==cv2.EVENT_MOUSEMOVE:
        if drawing==True:
            if mode==True:
                cv2.line(im,(current_former_x,current_former_y),(former_x,former_y),(0,0,255),5)
                current_former_x = former_x
                current_former_y = former_y
                #print former_x,former_y
    elif event==cv2.EVENT_LBUTTONUP:
        drawing=False
        if mode==True:
            cv2.line(im,(current_former_x,current_former_y),(former_x,former_y),(0,0,255),5)
            current_former_x = former_x
            current_former_y = former_y
    return former_x,former_y

im = cv2.imread("sampleuct.bmp")
cv2.namedWindow("Bill BEGUERADJ OpenCV")
cv2.setMouseCallback('Bill BEGUERADJ OpenCV',drawcurve)
while(1):
    cv2.imshow('Bill BEGUERADJ OpenCV',im)
    k=cv2.waitKey(1)&0xFF
    if k==27:
        break
cv2.destroyAllWindows()

Can you help me out it integrating my roi with tracking. Or any other way I could track it.


问:
Deep learning Keras model CTC_Loss gives loss = infinity
i've a CRNN model for text recognition, it was published on Github, trained on english language,

Now i'm doing the same thing using this algorithm but for arabic.

My ctc function is:

```<code>def ctc_lambda_func(args):
        y_pred, labels, input_length, label_length = args
        # the 2 is critical here since the first couple outputs of the RNN
        # tend to be garbage:
        y_pred = y_pred[:, 2:, :]
        return K.ctc_batch_cost(labels, y_pred, input_length, label_length)
</code>```

My Model is:

```<code>def get_Model(training):

        img_w = 128
        img_h = 64

        # Network parameters
        conv_filters = 16
        kernel_size = (3, 3)
        pool_size = 2
        time_dense_size = 32
        rnn_size = 128

        if K.image_data_format() == 'channels_first':
            input_shape = (1, img_w, img_h)
        else:
            input_shape = (img_w, img_h, 1)
        # Initialising the CNN
        act = 'relu'
        input_data = Input(name='the_input', shape=input_shape, dtype='float32')
        inner = Conv2D(conv_filters, kernel_size, padding='same',
                           activation=act, kernel_initializer='he_normal',
                           name='conv1')(input_data)
        inner = MaxPooling2D(pool_size=(pool_size, pool_size), name='max1')(inner)
        inner = Conv2D(conv_filters, kernel_size, padding='same',
                           activation=act, kernel_initializer='he_normal',
                           name='conv2')(inner)
        inner = MaxPooling2D(pool_size=(pool_size, pool_size), name='max2')(inner)

        conv_to_rnn_dims = (img_w // (pool_size ** 2), (img_h // (pool_size ** 2)) * conv_filters)
        inner = Reshape(target_shape=conv_to_rnn_dims, name='reshape')(inner)

            # cuts down input size going into RNN:
        inner = Dense(time_dense_size, activation=act, name='dense1')(inner)

            # Two layers of bidirectional GRUs
            # GRU seems to work as well, if not better than LSTM:
        gru_1 = GRU(rnn_size, return_sequences=True, kernel_initializer='he_normal', name='gru1')(inner)
        gru_1b = GRU(rnn_size, return_sequences=True, go_backwards=True, kernel_initializer='he_normal', name='gru1_b')(inner)
        gru1_merged = add([gru_1, gru_1b])
        gru_2 = GRU(rnn_size, return_sequences=True, kernel_initializer='he_normal', name='gru2')(gru1_merged)
        gru_2b = GRU(rnn_size, return_sequences=True, go_backwards=True, kernel_initializer='he_normal', name='gru2_b')(gru1_merged)

            # transforms RNN output to character activations:
        inner = Dense(num_classes+1, kernel_initializer='he_normal',
                          name='dense2')(concatenate([gru_2, gru_2b]))
        y_pred = Activation('softmax', name='softmax')(inner)
        Model(inputs=input_data, outputs=y_pred).summary()

        labels = Input(name='the_labels', shape=[30], dtype='float32')
        input_length = Input(name='input_length', shape=[1], dtype='int64')
        label_length = Input(name='label_length', shape=[1], dtype='int64')
            # Keras doesn't currently support loss funcs with extra parameters
            # so CTC loss is implemented in a lambda layer
        loss_out = Lambda(ctc_lambda_func, output_shape=(1,), name='ctc')([y_pred, labels, input_length, label_length])

            # clipnorm seems to speeds up convergence

            # the loss calc occurs elsewhere, so use a dummy lambda func for the loss

        if training:
            return Model(inputs=[input_data, labels, input_length, label_length], outputs=loss_out)

            return Model(inputs=[input_data], outputs=y_pred)
</code>```

Then i compile it with SGD optimizer (Tried SGD,adam)

```<code>sgd = SGD(lr=0.0000002, decay=1e-6, momentum=0.9, nesterov=True, clipnorm=5)
model.compile(loss={'ctc': lambda y_true, y_pred: y_pred}, optimizer=sgd)
</code>```

Then i fit the model with my training set (Images of words up to 30 characters) into (sequence of labels of 30

```<code>model.fit_generator(generator=tiger_train.next_batch(),
                steps_per_epoch=int(tiger_train.n / batch_size),
                epochs=30,
                callbacks=[checkpoint],
                validation_data=tiger_val.next_batch(),
                validation_steps=int(tiger_val.n / val_batch_size))
</code>```

Once it starts, it give me loss = inf, after many searches, i didn't find any similar problem.

So my questions is, how can i solve this, what can make a ctc_loss compute an infinite cost?

Thanks in advance

答: This error is happened when image text have two equal characters in the same sequence e.g happen --> pp.  for so that you can remove data that has this characteristic.  </p>

Body:
i've a CRNN model for text recognition, it was published on Github, trained on english language,

Now i'm doing the same thing using this algorithm but for arabic.

My ctc function is:

def ctc_lambda_func(args):
        y_pred, labels, input_length, label_length = args
        # the 2 is critical here since the first couple outputs of the RNN
        # tend to be garbage:
        y_pred = y_pred[:, 2:, :]
        return K.ctc_batch_cost(labels, y_pred, input_length, label_length)

My Model is:

def get_Model(training):

        img_w = 128
        img_h = 64

        # Network parameters
        conv_filters = 16
        kernel_size = (3, 3)
        pool_size = 2
        time_dense_size = 32
        rnn_size = 128

        if K.image_data_format() == 'channels_first':
            input_shape = (1, img_w, img_h)
        else:
            input_shape = (img_w, img_h, 1)
        # Initialising the CNN
        act = 'relu'
        input_data = Input(name='the_input', shape=input_shape, dtype='float32')
        inner = Conv2D(conv_filters, kernel_size, padding='same',
                           activation=act, kernel_initializer='he_normal',
                           name='conv1')(input_data)
        inner = MaxPooling2D(pool_size=(pool_size, pool_size), name='max1')(inner)
        inner = Conv2D(conv_filters, kernel_size, padding='same',
                           activation=act, kernel_initializer='he_normal',
                           name='conv2')(inner)
        inner = MaxPooling2D(pool_size=(pool_size, pool_size), name='max2')(inner)

        conv_to_rnn_dims = (img_w // (pool_size ** 2), (img_h // (pool_size ** 2)) * conv_filters)
        inner = Reshape(target_shape=conv_to_rnn_dims, name='reshape')(inner)

            # cuts down input size going into RNN:
        inner = Dense(time_dense_size, activation=act, name='dense1')(inner)

            # Two layers of bidirectional GRUs
            # GRU seems to work as well, if not better than LSTM:
        gru_1 = GRU(rnn_size, return_sequences=True, kernel_initializer='he_normal', name='gru1')(inner)
        gru_1b = GRU(rnn_size, return_sequences=True, go_backwards=True, kernel_initializer='he_normal', name='gru1_b')(inner)
        gru1_merged = add([gru_1, gru_1b])
        gru_2 = GRU(rnn_size, return_sequences=True, kernel_initializer='he_normal', name='gru2')(gru1_merged)
        gru_2b = GRU(rnn_size, return_sequences=True, go_backwards=True, kernel_initializer='he_normal', name='gru2_b')(gru1_merged)

            # transforms RNN output to character activations:
        inner = Dense(num_classes+1, kernel_initializer='he_normal',
                          name='dense2')(concatenate([gru_2, gru_2b]))
        y_pred = Activation('softmax', name='softmax')(inner)
        Model(inputs=input_data, outputs=y_pred).summary()

        labels = Input(name='the_labels', shape=[30], dtype='float32')
        input_length = Input(name='input_length', shape=[1], dtype='int64')
        label_length = Input(name='label_length', shape=[1], dtype='int64')
            # Keras doesn't currently support loss funcs with extra parameters
            # so CTC loss is implemented in a lambda layer
        loss_out = Lambda(ctc_lambda_func, output_shape=(1,), name='ctc')([y_pred, labels, input_length, label_length])

            # clipnorm seems to speeds up convergence

            # the loss calc occurs elsewhere, so use a dummy lambda func for the loss

        if training:
            return Model(inputs=[input_data, labels, input_length, label_length], outputs=loss_out)

            return Model(inputs=[input_data], outputs=y_pred)

Then i compile it with SGD optimizer (Tried SGD,adam)

sgd = SGD(lr=0.0000002, decay=1e-6, momentum=0.9, nesterov=True, clipnorm=5)
model.compile(loss={'ctc': lambda y_true, y_pred: y_pred}, optimizer=sgd)

Then i fit the model with my training set (Images of words up to 30 characters) into (sequence of labels of 30

model.fit_generator(generator=tiger_train.next_batch(),
                steps_per_epoch=int(tiger_train.n / batch_size),
                epochs=30,
                callbacks=[checkpoint],
                validation_data=tiger_val.next_batch(),
                validation_steps=int(tiger_val.n / val_batch_size))

Once it starts, it give me loss = inf, after many searches, i didn't find any similar problem.

So my questions is, how can i solve this, what can make a ctc_loss compute an infinite cost?

Thanks in advance


答:
Use event delegation. With event delegation, you add an event handler to an element that will exist prior to the dynamic content being added. All events that occur to dynamically added elements will bubble up the DOM to the existing element that you've attached your handler to. Your event handler will then need to inspect the event to know if it should do what it should do.

In my simple example, I've attached a delegated handler to #list. It waits for an element with the .close class to be clicked, issuing a click event, to remove the li from the list.

var addItemToList = function addItemToList( listNode, text ) {

  var li          = document.createElement( 'li' );
  var spanClose   = document.createElement( 'span' );
  var spanNothing = document.createElement( 'span' );

  li.textContent = text;

  spanClose.className = 'close';
  spanClose.innerHTML = '⨯';

  spanNothing.className = 'nothing';
  spanNothing.innerHTML = '★';

  li.appendChild( spanClose )
  li.appendChild( spanNothing );
  listNode.appendChild( li );

};

var getRandomText = function getRandomText() {
  return randomText[ Math.floor(Math.random() * 3) ];
};

var removeListItem = function removeListItem( e ) {

  // e.target =
  if ( e.target.classList.contains( 'close' ) ) {

    var li = e.target.parentNode;
    var ul = li.parentNode;

    ul.removeChild( li );

  }

}

var addToListBtn = document.querySelector( 'button' );
var theList      = document.querySelector( '#list' );
var randomText   = [ 'Hello!', 'Huh?', 'Okay' ];

addToListBtn.addEventListener( 'click', function ( e ) {
  addItemToList( theList, getRandomText() );
} );

theList.addEventListener( 'click', removeListItem );```
<pre class="snippet-code-css lang-css prettyprint-override"><code>li {
  line-height: 1.5;
}

li span {
  border: 1px solid #ccc;
  margin-left: 1rem;
  padding: 0.25rem 0.5rem;
  cursor: pointer;
}</code>```

<button>Add to List</button>

```

Title: JavaScript querySelector versions of Jquery

Body:
Use event delegation. With event delegation, you add an event handler to an element that will exist prior to the dynamic content being added. All events that occur to dynamically added elements will bubble up the DOM to the existing element that you've attached your handler to. Your event handler will then need to inspect the event to know if it should do what it should do.

In my simple example, I've attached a delegated handler to #list. It waits for an element with the .close class to be clicked, issuing a click event, to remove the li from the list.

var addItemToList = function addItemToList( listNode, text ) {

  var li          = document.createElement( 'li' );
  var spanClose   = document.createElement( 'span' );
  var spanNothing = document.createElement( 'span' );

  li.textContent = text;

  spanClose.className = 'close';
  spanClose.innerHTML = '⨯';

  spanNothing.className = 'nothing';
  spanNothing.innerHTML = '★';

  li.appendChild( spanClose )
  li.appendChild( spanNothing );
  listNode.appendChild( li );

};

var getRandomText = function getRandomText() {
  return randomText[ Math.floor(Math.random() * 3) ];
};

var removeListItem = function removeListItem( e ) {

  // e.target = <span>
  if ( e.target.classList.contains( 'close' ) ) {

    var li = e.target.parentNode;
    var ul = li.parentNode;

    ul.removeChild( li );

  }

}

var addToListBtn = document.querySelector( 'button' );
var theList      = document.querySelector( '#list' );
var randomText   = [ 'Hello!', 'Huh?', 'Okay' ];

addToListBtn.addEventListener( 'click', function ( e ) {
  addItemToList( theList, getRandomText() );
} );

theList.addEventListener( 'click', removeListItem );

li {
  line-height: 1.5;
}

li span {
  border: 1px solid #ccc;
  margin-left: 1rem;
  padding: 0.25rem 0.5rem;
  cursor: pointer;
}

<button>Add to List</button>

<ul id="list"></ul>