问:
How to increase text input width (with transition) when it is hovered in Tailwindcss
I was able to change the width of a text when it is hovered after adding hover in tailwind.config.js

```<code>width: ['responsive', 'hover', 'focus'],
.
.
.
transitionProperty: ['responsive', 'hover', 'focus'],
transitionTimingFunction: ['responsive', 'hover', 'focus'],
transitionDuration: ['responsive', 'hover', 'focus'],
transitionDelay: ['responsive', 'hover', 'focus'],
</code>```

However the animation effect is ugly and I wanted to add some transition but it doesn't seem to work. Here is the HTML part:

```<code><input type="text" placeholder="Search" class="placeholder-gray-500 rounded-full px-3 pl-8 py-1 outline-none transition duration-700 ease-in-out focus:shadow-outline hover:w-64" />
</code>```

Sample fiddle:
https://jsfiddle.net/codename2200/30wjcndm/9/

Since there is no tailwind config in jsfiddle I just extracted the styles (with purge) to replicate what I've got so far.

答:
Transition of size (height, width) will not work with "auto" value. You did not set any width on this input so it is auto be default. So if you have hover:w-64 then you need to set for ex. w-56.

Second issue with your code is transition class. By default it covers transitons of: background-color, border-color, color, fill, stroke, opacity, box-shadow, transform Check docs. Like you see there is no "width". So you can change it in tailwind config or just use transition-all instead.

body {
  background: #DEDEDE;
}

/*-- Extracted from tailwindcss --*/
/*! normalize.css v8.0.1 | MIT License | github.com/necolas/normalize.css */

/* Document
   ========================================================================== */

/**
 * 1. Correct the line height in all browsers.
 * 2. Prevent adjustments of font size after orientation changes in iOS.
 */

html {
  line-height: 1.15; /* 1 */
  -webkit-text-size-adjust: 100%; /* 2 */
}

/* Sections
   ========================================================================== */

/**
 * Remove the margin in all browsers.
 */

body {
  margin: 0;
}

/**
 * Render the `main` element consistently in IE.
 */

/**
 * Correct the font size and margin on `h1` elements within `section` and
 * `article` contexts in Chrome, Firefox, and Safari.
 */

/* Grouping content
   ========================================================================== */

/**
 * 1. Add the correct box sizing in Firefox.
 * 2. Show the overflow in Edge and IE.
 */

/**
 * 1. Correct the inheritance and scaling of font size in all browsers.
 * 2. Correct the odd `em` font sizing in all browsers.
 */

/* Text-level semantics
   ========================================================================== */

/**
 * Remove the gray background on active links in IE 10.
 */

a {
  background-color: transparent;
}

/**
 * 1. Remove the bottom border in Chrome 57-
 * 2. Add the correct text decoration in Chrome, Edge, IE, Opera, and Safari.
 */

/**
 * Add the correct font weight in Chrome, Edge, and Safari.
 */

/**
 * 1. Correct the inheritance and scaling of font size in all browsers.
 * 2. Correct the odd `em` font sizing in all browsers.
 */

/**
 * Add the correct font size in all browsers.
 */

/**
 * Prevent `sub` and `sup` elements from affecting the line height in
 * all browsers.
 */

/* Embedded content
   ========================================================================== */

/**
 * Remove the border on images inside links in IE 10.
 */

img {
  border-style: none;
}

/* Forms
   ========================================================================== */

/**
 * 1. Change the font styles in all browsers.
 * 2. Remove the margin in Firefox and Safari.
 */

button,
input {
  font-family: inherit; /* 1 */
  font-size: 100%; /* 1 */
  line-height: 1.15; /* 1 */
  margin: 0; /* 2 */
}

/**
 * Show the overflow in IE.
 * 1. Show the overflow in Edge.
 */

button,
input { /* 1 */
  overflow: visible;
}

/**
 * Remove the inheritance of text transform in Edge, Firefox, and IE.
 * 1. Remove the inheritance of text transform in Firefox.
 */

button { /* 1 */
  text-transform: none;
}

/**
 * Correct the inability to style clickable types in iOS and Safari.
 */

button,
[type="button"] {
  -webkit-appearance: button;
}

/**
 * Remove the inner border and padding in Firefox.
 */

button::-moz-focus-inner,
[type="button"]::-moz-focus-inner {
  border-style: none;
  padding: 0;
}

/**
 * Restore the focus styles unset by the previous rule.
 */

button:-moz-focusring,
[type="button"]:-moz-focusring {
  outline: 1px dotted ButtonText;
}

/**
 * Correct the padding in Firefox.
 */

/**
 * 1. Correct the text wrapping in Edge and IE.
 * 2. Correct the color inheritance from `fieldset` elements in IE.
 * 3. Remove the padding so developers are not caught out when they zero out
 *    `fieldset` elements in all browsers.
 */

/**
 * Add the correct vertical alignment in Chrome, Firefox, and Opera.
 */

/**
 * Remove the default vertical scrollbar in IE 10+.
 */

/**
 * 1. Add the correct box sizing in IE 10.
 * 2. Remove the padding in IE 10.
 */

/**
 * Correct the cursor style of increment and decrement buttons in Chrome.
 */

/**
 * 1. Correct the odd appearance in Chrome and Safari.
 * 2. Correct the outline style in Safari.
 */

/**
 * Remove the inner padding in Chrome and Safari on macOS.
 */

/**
 * 1. Correct the inability to style clickable types in iOS and Safari.
 * 2. Change font properties to `inherit` in Safari.
 */

/* Interactive
   ========================================================================== */

/*
 * Add the correct display in Edge, IE 10+, and Firefox.
 */

/*
 * Add the correct display in all browsers.
 */

/* Misc
   ========================================================================== */

/**
 * Add the correct display in IE 10+.
 */

/**
 * Add the correct display in IE 10.
 */

/**
 * Manually forked from SUIT CSS Base: https://github.com/suitcss/base
 * A thin layer on top of normalize.css that provides a starting point more
 * suitable for web applications.
 */

/**
 * Removes the default spacing and border for appropriate elements.
 */

h2,
h3 {
  margin: 0;
}

button {
  background-color: transparent;
  background-image: none;
  padding: 0;
}

/**
 * Work around a Firefox/IE bug where the transparent `button` background
 * results in a loss of the default `button` focus styles.
 */

button:focus {
  outline: 1px dotted;
  outline: 5px auto -webkit-focus-ring-color;
}

ul {
  list-style: none;
  margin: 0;
  padding: 0;
}

/**
 * Tailwind custom reset styles
 */

/**
 * 1. Use the user's configured `sans` font-family (with Tailwind's default
 *    sans-serif font stack as a fallback) as a sane default.
 * 2. Use Tailwind's default "normal" line-height so the user isn't forced
 *    to override it to ensure consistency even when using the default theme.
 */

html {
  font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"; /* 1 */
  line-height: 1.5; /* 2 */
}

/**
 * 1. Prevent padding and border from affecting element width.
 *
 *    We used to set this in the html element and inherit from
 *    the parent element for everything else. This caused issues
 *    in shadow-dom-enhanced elements like  where the content
 *    is wrapped by a div with box-sizing set to `content-box`.
 *
 *    https://github.com/mozdevs/cssremedy/issues/4
 *
 *
 * 2. Allow adding a border to an element by just adding a border-width.
 *
 *    By default, the way the browser specifies that an element should have no
 *    border is by setting it's border-style to `none` in the user-agent
 *    stylesheet.
 *
 *    In order to easily add borders to elements by just setting the `border-width`
 *    property, we change the default border-style for all elements to `solid`, and
 *    use border-width to hide them instead. This way our `border` utilities only
 *    need to set the `border-width` property instead of the entire `border`
 *    shorthand, making our border utilities much more straightforward to compose.
 *
 *    https://github.com/tailwindcss/tailwindcss/pull/116
 */

*,
::before,
::after {
  box-sizing: border-box; /* 1 */
  border-width: 0; /* 2 */
  border-style: solid; /* 2 */
  border-color: #e2e8f0; /* 2 */
}

/*
 * Ensure horizontal rules are visible by default
 */

/**
 * Undo the `border-style: none` reset that Normalize applies to images so that
 * our `border-{width}` utilities have the expected effect.
 *
 * The Normalize reset is unnecessary for us since we default the border-width
 * to 0 on all elements.
 *
 * https://github.com/tailwindcss/tailwindcss/issues/362
 */

img {
  border-style: solid;
}

input::-moz-placeholder {
  color: #a0aec0;
}

input:-ms-input-placeholder {
  color: #a0aec0;
}

input::-ms-input-placeholder {
  color: #a0aec0;
}

input::placeholder {
  color: #a0aec0;
}

button {
  cursor: pointer;
}

table {
  border-collapse: collapse;
}

h2,
h3 {
  font-size: inherit;
  font-weight: inherit;
}

/**
 * Reset links to optimize for opt-in styling instead of
 * opt-out.
 */

a {
  color: inherit;
  text-decoration: inherit;
}

/**
 * Reset form element properties that are easy to forget to
 * style explicitly so you don't inadvertently introduce
 * styles that deviate from your design system. These styles
 * supplement a partial reset that is already applied by
 * normalize.css.
 */

button,
input {
  padding: 0;
  line-height: inherit;
  color: inherit;
}

/**
 * Use the configured 'mono' font family for elements that
 * are expected to be rendered with a monospace font, falling
 * back to the system monospace stack if there is no configured
 * 'mono' font family.
 */

/**
 * Make replaced elements `display: block` by default as that's
 * the behavior you want almost all of the time. Inspired by
 * CSS Remedy, with `svg` added as well.
 *
 * https://github.com/mozdevs/cssremedy/issues/14
 */

img {
  display: block;
  vertical-align: middle;
}

/**
 * Constrain images and videos to the parent width and preserve
 * their instrinsic aspect ratio.
 *
 * https://github.com/mozdevs/cssremedy/issues/14
 */

img {
  max-width: 100%;
  height: auto;
}

.bg-white {
  --bg-opacity: 1;
  background-color: #fff;
  background-color: rgba(255, 255, 255, var(--bg-opacity));
}

.bg-custom-bgnormal {
  --bg-opacity: 1;
  background-color: #E7E7E7;
  background-color: rgba(231, 231, 231, var(--bg-opacity));
}

.bg-custom-dividerbg {
  --bg-opacity: 1;
  background-color: #F3F4F6;
  background-color: rgba(243, 244, 246, var(--bg-opacity));
}

.hover\:bg-gray-600:hover {
  --bg-opacity: 1;
  background-color: #718096;
  background-color: rgba(113, 128, 150, var(--bg-opacity));
}

.border-gray-400 {
  --border-opacity: 1;
  border-color: #cbd5e0;
  border-color: rgba(203, 213, 224, var(--border-opacity));
}

.rounded-full {
  border-radius: 9999px;
}

.border-b {
  border-bottom-width: 1px;
}

.flex {
  display: flex;
}

.table {
  display: table;
}

.flex-col {
  flex-direction: column;
}

.items-center {
  align-items: center;
}

.justify-between {
  justify-content: space-between;
}

.flex-1 {
  flex: 1 1 0%;
}

.flex-none {
  flex: none;
}

.font-semibold {
  font-weight: 600;
}

.h-16 {
  height: 4rem;
}

.h-auto {
  height: auto;
}

.h-screen {
  height: 100vh;
}

.text-xs {
  font-size: 0.75rem;
}

.text-sm {
  font-size: 0.875rem;
}

.text-xl {
  font-size: 1.25rem;
}

.leading-7 {
  line-height: 1.75rem;
}

.mx-4 {
  margin-left: 1rem;
  margin-right: 1rem;
}

.mt-2 {
  margin-top: 0.5rem;
}

.ml-2 {
  margin-left: 0.5rem;
}

.mt-4 {
  margin-top: 1rem;
}

.ml-4 {
  margin-left: 1rem;
}

.mt-6 {
  margin-top: 1.5rem;
}

.outline-none {
  outline: 0;
}

.focus\:outline-none:focus {
  outline: 0;
}

.overflow-y-auto {
  overflow-y: auto;
}

.overflow-y-hidden {
  overflow-y: hidden;
}

.py-1 {
  padding-top: 0.25rem;
  padding-bottom: 0.25rem;
}

.py-2 {
  padding-top: 0.5rem;
  padding-bottom: 0.5rem;
}

.px-2 {
  padding-left: 0.5rem;
  padding-right: 0.5rem;
}

.px-3 {
  padding-left: 0.75rem;
  padding-right: 0.75rem;
}

.px-4 {
  padding-left: 1rem;
  padding-right: 1rem;
}

.px-5 {
  padding-left: 1.25rem;
  padding-right: 1.25rem;
}

.pt-1 {
  padding-top: 0.25rem;
}

.pl-2 {
  padding-left: 0.5rem;
}

.pl-8 {
  padding-left: 2rem;
}

.pb-10 {
  padding-bottom: 2.5rem;
}

.placeholder-gray-500::-moz-placeholder {
  --placeholder-opacity: 1;
  color: #a0aec0;
  color: rgba(160, 174, 192, var(--placeholder-opacity));
}

.placeholder-gray-500:-ms-input-placeholder {
  --placeholder-opacity: 1;
  color: #a0aec0;
  color: rgba(160, 174, 192, var(--placeholder-opacity));
}

.placeholder-gray-500::-ms-input-placeholder {
  --placeholder-opacity: 1;
  color: #a0aec0;
  color: rgba(160, 174, 192, var(--placeholder-opacity));
}

.placeholder-gray-500::placeholder {
  --placeholder-opacity: 1;
  color: #a0aec0;
  color: rgba(160, 174, 192, var(--placeholder-opacity));
}

.absolute {
  position: absolute;
}

.relative {
  position: relative;
}

.top-0 {
  top: 0;
}

.focus\:shadow-outline:focus {
  box-shadow: 0 0 0 3px rgba(255,153,51,0.5);
}

.fill-current {
  fill: currentColor;
}

.text-left {
  text-align: left;
}

.text-center {
  text-align: center;
}

.text-custom-txtnormal {
  --text-opacity: 1;
  color: #5B5E65;
  color: rgba(91, 94, 101, var(--text-opacity));
}

.text-custom-iconnormal {
  --text-opacity: 1;
  color: #A0A7AD;
  color: rgba(160, 167, 173, var(--text-opacity));
}

.text-gray-600 {
  --text-opacity: 1;
  color: #718096;
  color: rgba(113, 128, 150, var(--text-opacity));
}

.hover\:text-white:hover {
  --text-opacity: 1;
  color: #fff;
  color: rgba(255, 255, 255, var(--text-opacity));
}

.hover\:text-orange-600:hover {
  --text-opacity: 1;
  color: #dd6b20;
  color: rgba(221, 107, 32, var(--text-opacity));
}

.hover\:text-orange-800:hover {
  --text-opacity: 1;
  color: #9c4221;
  color: rgba(156, 66, 33, var(--text-opacity));
}

.group:hover .group-hover\:text-gray-800 {
  --text-opacity: 1;
  color: #2d3748;
  color: rgba(45, 55, 72, var(--text-opacity));
}

.group:hover .group-hover\:text-orange-400 {
  --text-opacity: 1;
  color: #f6ad55;
  color: rgba(246, 173, 85, var(--text-opacity));
}

.group:hover .group-hover\:text-orange-800 {
  --text-opacity: 1;
  color: #9c4221;
  color: rgba(156, 66, 33, var(--text-opacity));
}

.uppercase {
  text-transform: uppercase;
}

.hover\:underline:hover {
  text-decoration: underline;
}

.tracking-wide {
  letter-spacing: 0.025em;
}

.truncate {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.w-4 {
  width: 1rem;
}

.w-48 {
  width: 12rem;
}

.w-auto {
  width: auto;
}

.w-full {
  width: 100%;
}

.hover\:w-64:hover {
  width: 16rem;
}

.transition {
  transition-property: background-color, border-color, color, fill, stroke, opacity, box-shadow, transform;
}

.ease-in-out {
  transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
}

.duration-200 {
  transition-duration: 200ms;
}

.duration-700 {
  transition-duration: 700ms;
}

.sidebar-spotify::-webkit-scrollbar{
  width: 8px;
  background-color: #f5f5f5;
}

.sidebar-spotify::-webkit-scrollbar-thumb {
  border-radius: 8px;
  background-color: #c98a00;
}

.content-spotify::-webkit-scrollbar {
  width: 8px;
  background-color: #f5f5f5;
}

.content-spotify::-webkit-scrollbar-thumb {
  border-radius: 8px;
  background-color: #c98a00;
}

.sidebar-active {
  --border-opacity: 1;
  border-color: #dd6b20;
  border-color: rgba(221, 107, 32, var(--border-opacity));
  border-left-width: 4px;
}

.sidebar-active a {
  --text-opacity: 1;
  color: #7b341e;
  color: rgba(123, 52, 30, var(--text-opacity));
}

.sidebar-active i {
  --text-opacity: 1;
  color: #dd6b20;
  color: rgba(221, 107, 32, var(--text-opacity));
}

.sidebar li:not(.logo) {
  transition-property: background-color, border-color, color, fill, stroke, opacity, box-shadow, transform;
  transition-duration: 200ms;
  transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
}

.sidebar li:hover:not(.logo) {
  border-left-width: 4px;
  --border-opacity: 1;
  border-color: #dd6b20;
  border-color: rgba(221, 107, 32, var(--border-opacity));
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet">

<input type="text" placeholder="Search" class="placeholder-gray-500 w-56 rounded-full px-3 pl-8 py-1 outline-none transition-all duration-700 ease-in-out focus:shadow-outline hover:w-64 hover:w-64"/></code>```

Body:
I was able to change the width of a text when it is hovered after adding hover in tailwind.config.js

width: ['responsive', 'hover', 'focus'],
.
.
.
transitionProperty: ['responsive', 'hover', 'focus'],
transitionTimingFunction: ['responsive', 'hover', 'focus'],
transitionDuration: ['responsive', 'hover', 'focus'],
transitionDelay: ['responsive', 'hover', 'focus'],

However the animation effect is ugly and I wanted to add some transition but it doesn't seem to work. Here is the HTML part:

<input type="text" placeholder="Search" class="placeholder-gray-500 rounded-full px-3 pl-8 py-1 outline-none transition duration-700 ease-in-out focus:shadow-outline hover:w-64" />

Sample fiddle:
https://jsfiddle.net/codename2200/30wjcndm/9/

Since there is no tailwind config in jsfiddle I just extracted the styles (with purge) to replicate what I've got so far.

Body:
Transition of size (height, width) will not work with "auto" value. You did not set any width on this input so it is auto be default. So if you have hover:w-64 then you need to set for ex. w-56.

Second issue with your code is transition class. By default it covers transitons of: background-color, border-color, color, fill, stroke, opacity, box-shadow, transform Check docs. Like you see there is no "width". So you can change it in tailwind config or just use transition-all instead.

body {
  background: #DEDEDE;
}

/*-- Extracted from tailwindcss --*/
/*! normalize.css v8.0.1 | MIT License | github.com/necolas/normalize.css */

/* Document
   ========================================================================== */

/**
 * 1. Correct the line height in all browsers.
 * 2. Prevent adjustments of font size after orientation changes in iOS.
 */

html {
  line-height: 1.15; /* 1 */
  -webkit-text-size-adjust: 100%; /* 2 */
}

/* Sections
   ========================================================================== */

/**
 * Remove the margin in all browsers.
 */

body {
  margin: 0;
}

/**
 * Render the `main` element consistently in IE.
 */

/**
 * Correct the font size and margin on `h1` elements within `section` and
 * `article` contexts in Chrome, Firefox, and Safari.
 */

/* Grouping content
   ========================================================================== */

/**
 * 1. Add the correct box sizing in Firefox.
 * 2. Show the overflow in Edge and IE.
 */

/**
 * 1. Correct the inheritance and scaling of font size in all browsers.
 * 2. Correct the odd `em` font sizing in all browsers.
 */

/* Text-level semantics
   ========================================================================== */

/**
 * Remove the gray background on active links in IE 10.
 */

a {
  background-color: transparent;
}

/**
 * 1. Remove the bottom border in Chrome 57-
 * 2. Add the correct text decoration in Chrome, Edge, IE, Opera, and Safari.
 */

/**
 * Add the correct font weight in Chrome, Edge, and Safari.
 */

/**
 * 1. Correct the inheritance and scaling of font size in all browsers.
 * 2. Correct the odd `em` font sizing in all browsers.
 */

/**
 * Add the correct font size in all browsers.
 */

/**
 * Prevent `sub` and `sup` elements from affecting the line height in
 * all browsers.
 */

/* Embedded content
   ========================================================================== */

/**
 * Remove the border on images inside links in IE 10.
 */

img {
  border-style: none;
}

/* Forms
   ========================================================================== */

/**
 * 1. Change the font styles in all browsers.
 * 2. Remove the margin in Firefox and Safari.
 */

button,
input {
  font-family: inherit; /* 1 */
  font-size: 100%; /* 1 */
  line-height: 1.15; /* 1 */
  margin: 0; /* 2 */
}

/**
 * Show the overflow in IE.
 * 1. Show the overflow in Edge.
 */

button,
input { /* 1 */
  overflow: visible;
}

/**
 * Remove the inheritance of text transform in Edge, Firefox, and IE.
 * 1. Remove the inheritance of text transform in Firefox.
 */

button { /* 1 */
  text-transform: none;
}

/**
 * Correct the inability to style clickable types in iOS and Safari.
 */

button,
[type="button"] {
  -webkit-appearance: button;
}

/**
 * Remove the inner border and padding in Firefox.
 */

button::-moz-focus-inner,
[type="button"]::-moz-focus-inner {
  border-style: none;
  padding: 0;
}

/**
 * Restore the focus styles unset by the previous rule.
 */

button:-moz-focusring,
[type="button"]:-moz-focusring {
  outline: 1px dotted ButtonText;
}

/**
 * Correct the padding in Firefox.
 */

/**
 * 1. Correct the text wrapping in Edge and IE.
 * 2. Correct the color inheritance from `fieldset` elements in IE.
 * 3. Remove the padding so developers are not caught out when they zero out
 *    `fieldset` elements in all browsers.
 */

/**
 * Add the correct vertical alignment in Chrome, Firefox, and Opera.
 */

/**
 * Remove the default vertical scrollbar in IE 10+.
 */

/**
 * 1. Add the correct box sizing in IE 10.
 * 2. Remove the padding in IE 10.
 */

/**
 * Correct the cursor style of increment and decrement buttons in Chrome.
 */

/**
 * 1. Correct the odd appearance in Chrome and Safari.
 * 2. Correct the outline style in Safari.
 */

/**
 * Remove the inner padding in Chrome and Safari on macOS.
 */

/**
 * 1. Correct the inability to style clickable types in iOS and Safari.
 * 2. Change font properties to `inherit` in Safari.
 */

/* Interactive
   ========================================================================== */

/*
 * Add the correct display in Edge, IE 10+, and Firefox.
 */

/*
 * Add the correct display in all browsers.
 */

/* Misc
   ========================================================================== */

/**
 * Add the correct display in IE 10+.
 */

/**
 * Add the correct display in IE 10.
 */

/**
 * Manually forked from SUIT CSS Base: https://github.com/suitcss/base
 * A thin layer on top of normalize.css that provides a starting point more
 * suitable for web applications.
 */

/**
 * Removes the default spacing and border for appropriate elements.
 */

h2,
h3 {
  margin: 0;
}

button {
  background-color: transparent;
  background-image: none;
  padding: 0;
}

/**
 * Work around a Firefox/IE bug where the transparent `button` background
 * results in a loss of the default `button` focus styles.
 */

button:focus {
  outline: 1px dotted;
  outline: 5px auto -webkit-focus-ring-color;
}

ul {
  list-style: none;
  margin: 0;
  padding: 0;
}

/**
 * Tailwind custom reset styles
 */

/**
 * 1. Use the user's configured `sans` font-family (with Tailwind's default
 *    sans-serif font stack as a fallback) as a sane default.
 * 2. Use Tailwind's default "normal" line-height so the user isn't forced
 *    to override it to ensure consistency even when using the default theme.
 */

html {
  font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"; /* 1 */
  line-height: 1.5; /* 2 */
}

/**
 * 1. Prevent padding and border from affecting element width.
 *
 *    We used to set this in the html element and inherit from
 *    the parent element for everything else. This caused issues
 *    in shadow-dom-enhanced elements like <details> where the content
 *    is wrapped by a div with box-sizing set to `content-box`.
 *
 *    https://github.com/mozdevs/cssremedy/issues/4
 *
 *
 * 2. Allow adding a border to an element by just adding a border-width.
 *
 *    By default, the way the browser specifies that an element should have no
 *    border is by setting it's border-style to `none` in the user-agent
 *    stylesheet.
 *
 *    In order to easily add borders to elements by just setting the `border-width`
 *    property, we change the default border-style for all elements to `solid`, and
 *    use border-width to hide them instead. This way our `border` utilities only
 *    need to set the `border-width` property instead of the entire `border`
 *    shorthand, making our border utilities much more straightforward to compose.
 *
 *    https://github.com/tailwindcss/tailwindcss/pull/116
 */

*,
::before,
::after {
  box-sizing: border-box; /* 1 */
  border-width: 0; /* 2 */
  border-style: solid; /* 2 */
  border-color: #e2e8f0; /* 2 */
}

/*
 * Ensure horizontal rules are visible by default
 */

/**
 * Undo the `border-style: none` reset that Normalize applies to images so that
 * our `border-{width}` utilities have the expected effect.
 *
 * The Normalize reset is unnecessary for us since we default the border-width
 * to 0 on all elements.
 *
 * https://github.com/tailwindcss/tailwindcss/issues/362
 */

img {
  border-style: solid;
}

input::-moz-placeholder {
  color: #a0aec0;
}

input:-ms-input-placeholder {
  color: #a0aec0;
}

input::-ms-input-placeholder {
  color: #a0aec0;
}

input::placeholder {
  color: #a0aec0;
}

button {
  cursor: pointer;
}

table {
  border-collapse: collapse;
}

h2,
h3 {
  font-size: inherit;
  font-weight: inherit;
}

/**
 * Reset links to optimize for opt-in styling instead of
 * opt-out.
 */

a {
  color: inherit;
  text-decoration: inherit;
}

/**
 * Reset form element properties that are easy to forget to
 * style explicitly so you don't inadvertently introduce
 * styles that deviate from your design system. These styles
 * supplement a partial reset that is already applied by
 * normalize.css.
 */

button,
input {
  padding: 0;
  line-height: inherit;
  color: inherit;
}

/**
 * Use the configured 'mono' font family for elements that
 * are expected to be rendered with a monospace font, falling
 * back to the system monospace stack if there is no configured
 * 'mono' font family.
 */

/**
 * Make replaced elements `display: block` by default as that's
 * the behavior you want almost all of the time. Inspired by
 * CSS Remedy, with `svg` added as well.
 *
 * https://github.com/mozdevs/cssremedy/issues/14
 */

img {
  display: block;
  vertical-align: middle;
}

/**
 * Constrain images and videos to the parent width and preserve
 * their instrinsic aspect ratio.
 *
 * https://github.com/mozdevs/cssremedy/issues/14
 */

img {
  max-width: 100%;
  height: auto;
}

.bg-white {
  --bg-opacity: 1;
  background-color: #fff;
  background-color: rgba(255, 255, 255, var(--bg-opacity));
}

.bg-custom-bgnormal {
  --bg-opacity: 1;
  background-color: #E7E7E7;
  background-color: rgba(231, 231, 231, var(--bg-opacity));
}

.bg-custom-dividerbg {
  --bg-opacity: 1;
  background-color: #F3F4F6;
  background-color: rgba(243, 244, 246, var(--bg-opacity));
}

.hover\:bg-gray-600:hover {
  --bg-opacity: 1;
  background-color: #718096;
  background-color: rgba(113, 128, 150, var(--bg-opacity));
}

.border-gray-400 {
  --border-opacity: 1;
  border-color: #cbd5e0;
  border-color: rgba(203, 213, 224, var(--border-opacity));
}

.rounded-full {
  border-radius: 9999px;
}

.border-b {
  border-bottom-width: 1px;
}

.flex {
  display: flex;
}

.table {
  display: table;
}

.flex-col {
  flex-direction: column;
}

.items-center {
  align-items: center;
}

.justify-between {
  justify-content: space-between;
}

.flex-1 {
  flex: 1 1 0%;
}

.flex-none {
  flex: none;
}

.font-semibold {
  font-weight: 600;
}

.h-16 {
  height: 4rem;
}

.h-auto {
  height: auto;
}

.h-screen {
  height: 100vh;
}

.text-xs {
  font-size: 0.75rem;
}

.text-sm {
  font-size: 0.875rem;
}

.text-xl {
  font-size: 1.25rem;
}

.leading-7 {
  line-height: 1.75rem;
}

.mx-4 {
  margin-left: 1rem;
  margin-right: 1rem;
}

.mt-2 {
  margin-top: 0.5rem;
}

.ml-2 {
  margin-left: 0.5rem;
}

.mt-4 {
  margin-top: 1rem;
}

.ml-4 {
  margin-left: 1rem;
}

.mt-6 {
  margin-top: 1.5rem;
}

.outline-none {
  outline: 0;
}

.focus\:outline-none:focus {
  outline: 0;
}

.overflow-y-auto {
  overflow-y: auto;
}

.overflow-y-hidden {
  overflow-y: hidden;
}

.py-1 {
  padding-top: 0.25rem;
  padding-bottom: 0.25rem;
}

.py-2 {
  padding-top: 0.5rem;
  padding-bottom: 0.5rem;
}

.px-2 {
  padding-left: 0.5rem;
  padding-right: 0.5rem;
}

.px-3 {
  padding-left: 0.75rem;
  padding-right: 0.75rem;
}

.px-4 {
  padding-left: 1rem;
  padding-right: 1rem;
}

.px-5 {
  padding-left: 1.25rem;
  padding-right: 1.25rem;
}

.pt-1 {
  padding-top: 0.25rem;
}

.pl-2 {
  padding-left: 0.5rem;
}

.pl-8 {
  padding-left: 2rem;
}

.pb-10 {
  padding-bottom: 2.5rem;
}

.placeholder-gray-500::-moz-placeholder {
  --placeholder-opacity: 1;
  color: #a0aec0;
  color: rgba(160, 174, 192, var(--placeholder-opacity));
}

.placeholder-gray-500:-ms-input-placeholder {
  --placeholder-opacity: 1;
  color: #a0aec0;
  color: rgba(160, 174, 192, var(--placeholder-opacity));
}

.placeholder-gray-500::-ms-input-placeholder {
  --placeholder-opacity: 1;
  color: #a0aec0;
  color: rgba(160, 174, 192, var(--placeholder-opacity));
}

.placeholder-gray-500::placeholder {
  --placeholder-opacity: 1;
  color: #a0aec0;
  color: rgba(160, 174, 192, var(--placeholder-opacity));
}

.absolute {
  position: absolute;
}

.relative {
  position: relative;
}

.top-0 {
  top: 0;
}

.focus\:shadow-outline:focus {
  box-shadow: 0 0 0 3px rgba(255,153,51,0.5);
}

.fill-current {
  fill: currentColor;
}

.text-left {
  text-align: left;
}

.text-center {
  text-align: center;
}

.text-custom-txtnormal {
  --text-opacity: 1;
  color: #5B5E65;
  color: rgba(91, 94, 101, var(--text-opacity));
}

.text-custom-iconnormal {
  --text-opacity: 1;
  color: #A0A7AD;
  color: rgba(160, 167, 173, var(--text-opacity));
}

.text-gray-600 {
  --text-opacity: 1;
  color: #718096;
  color: rgba(113, 128, 150, var(--text-opacity));
}

.hover\:text-white:hover {
  --text-opacity: 1;
  color: #fff;
  color: rgba(255, 255, 255, var(--text-opacity));
}

.hover\:text-orange-600:hover {
  --text-opacity: 1;
  color: #dd6b20;
  color: rgba(221, 107, 32, var(--text-opacity));
}

.hover\:text-orange-800:hover {
  --text-opacity: 1;
  color: #9c4221;
  color: rgba(156, 66, 33, var(--text-opacity));
}

.group:hover .group-hover\:text-gray-800 {
  --text-opacity: 1;
  color: #2d3748;
  color: rgba(45, 55, 72, var(--text-opacity));
}

.group:hover .group-hover\:text-orange-400 {
  --text-opacity: 1;
  color: #f6ad55;
  color: rgba(246, 173, 85, var(--text-opacity));
}

.group:hover .group-hover\:text-orange-800 {
  --text-opacity: 1;
  color: #9c4221;
  color: rgba(156, 66, 33, var(--text-opacity));
}

.uppercase {
  text-transform: uppercase;
}

.hover\:underline:hover {
  text-decoration: underline;
}

.tracking-wide {
  letter-spacing: 0.025em;
}

.truncate {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.w-4 {
  width: 1rem;
}

.w-48 {
  width: 12rem;
}

.w-auto {
  width: auto;
}

.w-full {
  width: 100%;
}

.hover\:w-64:hover {
  width: 16rem;
}

.transition {
  transition-property: background-color, border-color, color, fill, stroke, opacity, box-shadow, transform;
}

.ease-in-out {
  transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
}

.duration-200 {
  transition-duration: 200ms;
}

.duration-700 {
  transition-duration: 700ms;
}

.sidebar-spotify::-webkit-scrollbar{
  width: 8px;
  background-color: #f5f5f5;
}

.sidebar-spotify::-webkit-scrollbar-thumb {
  border-radius: 8px;
  background-color: #c98a00;
}

.content-spotify::-webkit-scrollbar {
  width: 8px;
  background-color: #f5f5f5;
}

.content-spotify::-webkit-scrollbar-thumb {
  border-radius: 8px;
  background-color: #c98a00;
}

.sidebar-active {
  --border-opacity: 1;
  border-color: #dd6b20;
  border-color: rgba(221, 107, 32, var(--border-opacity));
  border-left-width: 4px;
}

.sidebar-active a {
  --text-opacity: 1;
  color: #7b341e;
  color: rgba(123, 52, 30, var(--text-opacity));
}

.sidebar-active i {
  --text-opacity: 1;
  color: #dd6b20;
  color: rgba(221, 107, 32, var(--text-opacity));
}

.sidebar li:not(.logo) {
  transition-property: background-color, border-color, color, fill, stroke, opacity, box-shadow, transform;
  transition-duration: 200ms;
  transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
}

.sidebar li:hover:not(.logo) {
  border-left-width: 4px;
  --border-opacity: 1;
  border-color: #dd6b20;
  border-color: rgba(221, 107, 32, var(--border-opacity));
}

<link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet">

<input type="text" placeholder="Search" class="placeholder-gray-500 w-56 rounded-full px-3 pl-8 py-1 outline-none transition-all duration-700 ease-in-out focus:shadow-outline hover:w-64 hover:w-64"/>


来源: stackexchange

问:
Is it possible to pick random values from enum in a different class?
I am just wondering how to pick random values from enum in a different class. For example, I have Person and Victorian as classes and both classes do not have main method. In the Person class, there is enum Profession which takes on “doctor”, “ceo”, “unemployed” and “unknown”, and in the Victorian class, I want to pick random values from this enum. Is it possible? </p>

答:
You can do:

```<code>Profession randomValue =
  Profession.values()[new Random().nextInt(Profession.values().length)];
</code>```

If you want to do this more often you should initialize the Random only once:

```<code>Random random = new Random();
Profession[] enumValues = Profession.values();
for (int i = 0; i < 100; i++) {
    Profession randomValue = enumValues[random.nextInt(enumValues.length)];
    System.out.println(randomValue);
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
You can do:

Profession randomValue =
  Profession.values()[new Random().nextInt(Profession.values().length)];

If you want to do this more often you should initialize the Random only once:

Random random = new Random();
Profession[] enumValues = Profession.values();
for (int i = 0; i < 100; i++) {
    Profession randomValue = enumValues[random.nextInt(enumValues.length)];
    System.out.println(randomValue);
}


问:
window.focus() not working in Google Chrome
Just wondering if Google Chrome is going to support window.focus() at some point. When I mean support, I mean have it work. The call to it doesn't fail, it just doesn't do anything. All other major browsers do not have this problem: FireFox, IE6-IE8 and Safari.

I have a client-side class for managing browser windows. When I first create a window the window comes into focus, but subsequent attempts to bring focus to the window do not work.

From what I can tell, this appears to be a security feature to avoid annoying pop-ups and it does not appear to be a WebKit issue as it works in Safari.

I know one idea someone brought forward was to close the window then reopen it, but this is a horrible solution. Googling shows that I do not appear to be the only person frustrated with this.

And just to be 100% clear, I mean new windows, not tabs (tabs cannot be focused from what I've read) and all the windows being opened are in the same domain.

Any ideas, workarounds aside from the bad one I mention above?

There is a bug logged on the Chromium project about this, check it out here. Thanks for posting that Rich.

```<code>MyCompany = { UI: {} }; // Put this here if you want to test the code. I create these namespaces elsewhere in code.

MyCompany.UI.Window = new function() {
    // Private fields
    var that = this;
    var windowHandles = {};

    // Public Members
    this.windowExists = function(windowTarget) {
        return windowTarget && windowHandles[windowTarget] && !windowHandles[windowTarget].closed;
    }

    this.open = function(url, windowTarget, windowProperties) {
        // See if we have a window handle and if it's closed or not.
        if (that.windowExists(windowTarget)) {

            // We still have our window object so let's check if the URLs is the same as the one we're trying to load.
            var currentLocation = windowHandles[windowTarget].location;

            if (
                (
                    /^http(?:s?):/.test(url) && currentLocation.href !== url
                )
                    ||
                (
                    // This check is required because the URL might be the same, but absolute,
                    // e.g. /Default.aspx ... instead of http://localhost/Default.aspx ...
                    !/^http(?:s?):/.test(url) &&
                    (currentLocation.pathname + currentLocation.search + currentLocation.hash) !== url
                )
            ) {
                // Not the same URL, so load the new one.
                windowHandles[windowTarget].location = url;
            }

            // Give focus to the window. This works in IE 6/7/8, FireFox, Safari but not Chrome.
            // Well in Chrome it works the first time, but subsequent focus attempts fail,. I believe this is a security feature in Chrome to avoid annoying popups.
            windowHandles[windowTarget].focus();
        }
        else
        {
            // Need to do this so that tabbed browsers (pretty much all browsers except IE6) actually open a new window
            // as opposed to a tab. By specifying at least one window property, we're guaranteed to have a new window created instead
            // of a tab.
            windowProperties = windowProperties || 'menubar=yes,location=yes,width=700, height=400, scrollbars=yes, resizable= yes';
            windowTarget = windowTarget || "_blank";

            // Create a new window.
            var windowHandle = windowProperties ? window.open(url, windowTarget, windowProperties) : window.open(url, windowTarget);

            if (null === windowHandle) {
                alert("You have a popup blocker enabled. Please allow popups for " + location.protocol + "//" + location.host);
            }
            else {
                if ("_blank" !== windowTarget) {
                    // Store the window handle for reuse if a handle was specified.
                    windowHandles[windowTarget] = windowHandle;
                    windowHandles[windowTarget].focus();
                }
            }
        }
    }
}
</code>```

答:
I was only able to solve my problem when I used setTimeout() and encapsulated the focus() inside an anonymous function. Here is an example:

```<code>setTimeout(function () {
   myField.focus();
}, 0);
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Just wondering if Google Chrome is going to support window.focus() at some point. When I mean support, I mean have it work. The call to it doesn't fail, it just doesn't do anything. All other major browsers do not have this problem: FireFox, IE6-IE8 and Safari.

I have a client-side class for managing browser windows. When I first create a window the window comes into focus, but subsequent attempts to bring focus to the window do not work.

From what I can tell, this appears to be a security feature to avoid annoying pop-ups and it does not appear to be a WebKit issue as it works in Safari.

I know one idea someone brought forward was to close the window then reopen it, but this is a horrible solution. Googling shows that I do not appear to be the only person frustrated with this.

And just to be 100% clear, I mean new windows, not tabs (tabs cannot be focused from what I've read) and all the windows being opened are in the same domain.

Any ideas, workarounds aside from the bad one I mention above?

There is a bug logged on the Chromium project about this, check it out here. Thanks for posting that Rich.

MyCompany = { UI: {} }; // Put this here if you want to test the code. I create these namespaces elsewhere in code.

MyCompany.UI.Window = new function() {
    // Private fields
    var that = this;
    var windowHandles = {};

    // Public Members
    this.windowExists = function(windowTarget) {
        return windowTarget && windowHandles[windowTarget] && !windowHandles[windowTarget].closed;
    }

    this.open = function(url, windowTarget, windowProperties) {
        // See if we have a window handle and if it's closed or not.
        if (that.windowExists(windowTarget)) {

            // We still have our window object so let's check if the URLs is the same as the one we're trying to load.
            var currentLocation = windowHandles[windowTarget].location;

            if (
                (
                    /^http(?:s?):/.test(url) && currentLocation.href !== url
                )
                    ||
                (
                    // This check is required because the URL might be the same, but absolute,
                    // e.g. /Default.aspx ... instead of http://localhost/Default.aspx ...
                    !/^http(?:s?):/.test(url) &&
                    (currentLocation.pathname + currentLocation.search + currentLocation.hash) !== url
                )
            ) {
                // Not the same URL, so load the new one.
                windowHandles[windowTarget].location = url;
            }

            // Give focus to the window. This works in IE 6/7/8, FireFox, Safari but not Chrome.
            // Well in Chrome it works the first time, but subsequent focus attempts fail,. I believe this is a security feature in Chrome to avoid annoying popups.
            windowHandles[windowTarget].focus();
        }
        else
        {
            // Need to do this so that tabbed browsers (pretty much all browsers except IE6) actually open a new window
            // as opposed to a tab. By specifying at least one window property, we're guaranteed to have a new window created instead
            // of a tab.
            windowProperties = windowProperties || 'menubar=yes,location=yes,width=700, height=400, scrollbars=yes, resizable= yes';
            windowTarget = windowTarget || "_blank";

            // Create a new window.
            var windowHandle = windowProperties ? window.open(url, windowTarget, windowProperties) : window.open(url, windowTarget);

            if (null === windowHandle) {
                alert("You have a popup blocker enabled. Please allow popups for " + location.protocol + "//" + location.host);
            }
            else {
                if ("_blank" !== windowTarget) {
                    // Store the window handle for reuse if a handle was specified.
                    windowHandles[windowTarget] = windowHandle;
                    windowHandles[windowTarget].focus();
                }
            }
        }
    }
}

Body:
I was only able to solve my problem when I used setTimeout() and encapsulated the focus() inside an anonymous function. Here is an example:

setTimeout(function () {
   myField.focus();
}, 0);


问:
How to create custom uitableview like that
I want to create uitableview like the following , also I need to add a third section that contains rows

any suggestion please

答:
Do all of this in an UITableViewController with -

```<code> UITableViewDelegate, UIPickerViewDelegate, UITableViewDataSource, UIPickerViewDataSource -
</code>```

For Patient & ACC => Set a UITextField as a Subview (Do this in the cellForRowAtIndexPath for their respective rows)

For Birth and Date => Use the UIDatePickerView and for row ==2 and row ==4 respectively.

For Modality => I do not know what you mean by that; But you need to do something similar

For getting another section for the other two values; Return Section = 2 in

```<code>(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
</code>```

and set title for those accordingly (if needed)

Code :

```<code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  {
static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease];
    UITextField *textField = [[UITextField alloc]initWithFrame:CGRectMake(110, 10, 185, 30)];

    textField.clearsOnBeginEditing = YES;
    textField.textAlignment = UITextAlignmentRight;
    textField.returnKeyType = UIReturnKeyDone;
    textField.delegate = self;
    [cell.contentView addSubview:textField];

    if (indexPath.row == 2)
    {
        UIDatePicker *datePicker = [[UIDatePicker alloc] init];
        datePicker.datePickerMode = UIDatePickerModeDate;
        [datePicker addTarget:self action:@selector(datePickerValueChangedd:) forControlEvents:UIControlEventValueChanged];
        datePicker.tag = indexPath.row;
        textField.inputView = datePicker;

        NSDateFormatter *df = [[NSDateFormatter alloc] init];
        df.dateStyle = NSDateFormatterMediumStyle;
        NSString *local;
        local = [self datePickerValueChangedd: datePicker];
        NSLog(@"%@", local);
        textField.text =local;
        [datePicker reloadInputViews];
        [datePicker release];

    }
}

// Configure the cell...

NSInteger row = [indexPath row];
cell.textLabel.text = [doseInfoDetailsArray objectAtIndex:row];

return cell;
</code>```

}

ContentLicense: CC BY-SA 3.0

Body:
Do all of this in an UITableViewController with -

 UITableViewDelegate, UIPickerViewDelegate, UITableViewDataSource, UIPickerViewDataSource -

For Patient & ACC => Set a UITextField as a Subview (Do this in the cellForRowAtIndexPath for their respective rows)

For Birth and Date => Use the UIDatePickerView and for row ==2 and row ==4 respectively.

For Modality => I do not know what you mean by that; But you need to do something similar

For getting another section for the other two values; Return Section = 2 in

(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView

and set title for those accordingly (if needed)

Code :

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  {
static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease];
    UITextField *textField = [[UITextField alloc]initWithFrame:CGRectMake(110, 10, 185, 30)];

    textField.clearsOnBeginEditing = YES;
    textField.textAlignment = UITextAlignmentRight;
    textField.returnKeyType = UIReturnKeyDone;
    textField.delegate = self;
    [cell.contentView addSubview:textField];

    if (indexPath.row == 2)
    {
        UIDatePicker *datePicker = [[UIDatePicker alloc] init];
        datePicker.datePickerMode = UIDatePickerModeDate;
        [datePicker addTarget:self action:@selector(datePickerValueChangedd:) forControlEvents:UIControlEventValueChanged];
        datePicker.tag = indexPath.row;
        textField.inputView = datePicker;

        NSDateFormatter *df = [[NSDateFormatter alloc] init];
        df.dateStyle = NSDateFormatterMediumStyle;
        NSString *local;
        local = [self datePickerValueChangedd: datePicker];
        NSLog(@"%@", local);
        textField.text =local;
        [datePicker reloadInputViews];
        [datePicker release];

    }
}

// Configure the cell...

NSInteger row = [indexPath row];
cell.textLabel.text = [doseInfoDetailsArray objectAtIndex:row];

return cell;

}


问:
How to get each frame as an image from a cv2.VideoCapture in python
I want to get each frame from a video as an image. background to this is following. I have written a Neural Network which is able to recognize Hand Signs. Now I want to start a video stream, where each image/frame of the stream is put through the Neural Network. To fit it into my neural Network, I want to render each frame and reduce the image to 28*28 pixels. In the end it should look similar to this: https://www.youtube.com/watch?v=JfSao30fMxY
I have searched through the web and found out that I can use cv2.VideoCapture to get the stream. But how can I pick each image of the Frame, render it and print the result back on the screen. My Code looks like this until now:</p>

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

cap = cv2.VideoCapture(0)

# Todo: each Frame/Image from the video should be saved as a variable and open imageToLabel()
# Todo: before the image is handed to the method, it needs to be translated into a 28*28 np Array
# Todo: the returned Label should be printed onto the video (otherwise it can be )

i = 0
while (True):
    # Capture frame-by-frame
    # Load model once and pass it as an parameter

    ret, frame = cap.read()
    i += 1

    image = cv2.imwrite('database/{index}.png'.format(index=i), frame)
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2BGRAY)

    cv2.imshow('frame', frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()

def imageToLabel(imgArr, checkpointLoad):
    new_model = tf.keras.models.load_model(checkpointLoad)
    imgArrNew = imgArr.reshape(1, 28, 28, 1) / 255
    prediction = new_model.predict(imgArrNew)
    label = np.argmax(prediction)
    return label

</code>```

答:
frame is the RGB Image you get from the stream.
gray is the grayscale converted image.
I suppose your network takes grayscaled images because of its shape. Therefor you need to first resize the image to (28,28) and then pass it to your imageToLabel function

```<code>resizedImg = cv2.resize(gray,(28,28))
label = imageToLabel(resizedImg,yourModel)
</code>```

now that you know the prediction you can draw it on the frame using e.g. cv2.putText() and then draw the frame it returns instead of frame

edit:

If you want to use parts of the image for your network you can slice the image like this:

```<code>slicedImg = gray[50:150,50:150]
resizedImg = cv2.resize(slicedImg,(28,28))
label = imageToLabel(resizedImg,yourModel)
</code>```

If you're not that familiar with indexing in python you might want to take a look at this

Also if you want it to look like in the linked video you can draw a rectangle from e.g. (50,50) to (150,150) that is green (0,255,0)

```<code>cv2.rectangle(frame,(50,50),(150,150),(0,255,0))
</code>```

Body:
I want to get each frame from a video as an image. background to this is following. I have written a Neural Network which is able to recognize Hand Signs. Now I want to start a video stream, where each image/frame of the stream is put through the Neural Network. To fit it into my neural Network, I want to render each frame and reduce the image to 28*28 pixels. In the end it should look similar to this: https://www.youtube.com/watch?v=JfSao30fMxY
I have searched through the web and found out that I can use cv2.VideoCapture to get the stream. But how can I pick each image of the Frame, render it and print the result back on the screen. My Code looks like this until now:

import numpy as np
import cv2

cap = cv2.VideoCapture(0)

# Todo: each Frame/Image from the video should be saved as a variable and open imageToLabel()
# Todo: before the image is handed to the method, it needs to be translated into a 28*28 np Array
# Todo: the returned Label should be printed onto the video (otherwise it can be )

i = 0
while (True):
    # Capture frame-by-frame
    # Load model once and pass it as an parameter

    ret, frame = cap.read()
    i += 1

    image = cv2.imwrite('database/{index}.png'.format(index=i), frame)
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2BGRAY)

    cv2.imshow('frame', frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()

def imageToLabel(imgArr, checkpointLoad):
    new_model = tf.keras.models.load_model(checkpointLoad)
    imgArrNew = imgArr.reshape(1, 28, 28, 1) / 255
    prediction = new_model.predict(imgArrNew)
    label = np.argmax(prediction)
    return label

Body:
frame is the RGB Image you get from the stream.
gray is the grayscale converted image.
I suppose your network takes grayscaled images because of its shape. Therefor you need to first resize the image to (28,28) and then pass it to your imageToLabel function

resizedImg = cv2.resize(gray,(28,28))
label = imageToLabel(resizedImg,yourModel)

now that you know the prediction you can draw it on the frame using e.g. cv2.putText() and then draw the frame it returns instead of frame

edit:

If you want to use parts of the image for your network you can slice the image like this:

slicedImg = gray[50:150,50:150]
resizedImg = cv2.resize(slicedImg,(28,28))
label = imageToLabel(resizedImg,yourModel)

If you're not that familiar with indexing in python you might want to take a look at this

Also if you want it to look like in the linked video you can draw a rectangle from e.g. (50,50) to (150,150) that is green (0,255,0)

cv2.rectangle(frame,(50,50),(150,150),(0,255,0))


问:
Want to set the y axis ticks to a fixed value Highcharts
I am trying a combination of line and an area graph based on data points based.

In Graph 1, Y axis looks clumsy with lot of ticks. Is there a way where these ticks can be set to may be "3" on y axis. This should remain constant for any data points, ticks should always 3

Also in the graph 2, there is an extra horizontal line, below 0. Is there any way I could avoid it, so that reference is always from 0 than having lines below 0.

Sandbox link: https://codesandbox.io/s/react-line-chart-n9g6o?file=/src/LineChart.js

```<code>import * as React from "react";
import Highcharts from "highcharts";
import HighchartsReact from "highcharts-react-official";
import HC_exporting from "highcharts/modules/exporting";
HC_exporting(Highcharts);

function LineChart(props) {
  let chartOptions = {
    chart: {
      type: "line",
      height: props.height
    },
    legend: {
      align: "center",
      verticalAlign: "bottom",
      x: 0,
      y: 0
    },
    tooltip: {
      shared: true,
      useHTML: true,
      formatter: function() {
        let self = this;
        let formattedString = "<small></small><table>";
        self.points.forEach(elem => {
          formattedString +=
            '<tr><td style="color: {series.color}">' +
            elem.series.name +
            ": </td>";
          formattedString +=
            '<td style="text-align: right"><b>' +
            elem.y +
            " (" +
            elem.point.ts +
            ")</b></td></tr>";
        });
        return formattedString;
      }
    },
    colors: props.legendColor,
    xAxis: {
      visible: true,
      step: 1,
      tickInterval: 6,
      categories: props.categories
    },
    yAxis: {
      visible: true,
      step: 1,
      tickInterval: 1,
      title: {
        enabled: true,
        text: "Value",
        style: {
          fontWeight: "100"
        }
      }
    },
    plotOptions: {
      column: {
        dataLabels: {
          enabled: true,
          crop: false,
          overflow: "none"
        }
      },
      line: {
        marker: {
          enabled: false
        }
      }
    },
    series: props.chartData
  };
  return <HighchartsReact highcharts={Highcharts} options={chartOptions} />;
}

export default LineChart;

</code>```

答:
In Graph 1, Y axis looks clumsy with lot of ticks. Is there a way
  where these ticks can be set to may be "3" on y axis. This should
  remain constant for any data points, ticks should always 3

Use tickAmount property:

```<code>yAxis: {
  tickAmount: 3,
  ..
}
</code>```

API Reference: https://api.highcharts.com/highcharts/yAxis.tickAmount

Also in the graph 2, there is an extra horizontal line, below 0. Is
  there any way I could avoid it, so that reference is always from 0
  than having lines below 0.

Yes, you can for example set softMax property. Highcharts is unable to calculate an axis scale if there are only 0 values.

```<code>yAxis: {
  softMax: 1,
  ...
}
</code>```

API Reference: https://api.highcharts.com/highcharts/yAxis.softMax

Body:
I am trying a combination of line and an area graph based on data points based.

In Graph 1, Y axis looks clumsy with lot of ticks. Is there a way where these ticks can be set to may be "3" on y axis. This should remain constant for any data points, ticks should always 3

Also in the graph 2, there is an extra horizontal line, below 0. Is there any way I could avoid it, so that reference is always from 0 than having lines below 0.

Sandbox link: https://codesandbox.io/s/react-line-chart-n9g6o?file=/src/LineChart.js

import * as React from "react";
import Highcharts from "highcharts";
import HighchartsReact from "highcharts-react-official";
import HC_exporting from "highcharts/modules/exporting";
HC_exporting(Highcharts);

function LineChart(props) {
  let chartOptions = {
    chart: {
      type: "line",
      height: props.height
    },
    legend: {
      align: "center",
      verticalAlign: "bottom",
      x: 0,
      y: 0
    },
    tooltip: {
      shared: true,
      useHTML: true,
      formatter: function() {
        let self = this;
        let formattedString = "
";
        self.points.forEach(elem => {
          formattedString +=
            '
' +
            elem.series.name +
            ": 	";
          formattedString +=
            '' +
            elem.y +
            " (" +
            elem.point.ts +
            ")
";
        });
        return formattedString;
      }
    },
    colors: props.legendColor,
    xAxis: {
      visible: true,
      step: 1,
      tickInterval: 6,
      categories: props.categories
    },
    yAxis: {
      visible: true,
      step: 1,
      tickInterval: 1,
      title: {
        enabled: true,
        text: "Value",
        style: {
          fontWeight: "100"
        }
      }
    },
    plotOptions: {
      column: {
        dataLabels: {
          enabled: true,
          crop: false,
          overflow: "none"
        }
      },
      line: {
        marker: {
          enabled: false
        }
      }
    },
    series: props.chartData
  };
  return <HighchartsReact highcharts={Highcharts} options={chartOptions} />;
}

export default LineChart;

Body:
In Graph 1, Y axis looks clumsy with lot of ticks. Is there a way
  where these ticks can be set to may be "3" on y axis. This should
  remain constant for any data points, ticks should always 3

Use tickAmount property:

yAxis: {
  tickAmount: 3,
  ..
}

API Reference: https://api.highcharts.com/highcharts/yAxis.tickAmount

Also in the graph 2, there is an extra horizontal line, below 0. Is
  there any way I could avoid it, so that reference is always from 0
  than having lines below 0.

Yes, you can for example set softMax property. Highcharts is unable to calculate an axis scale if there are only 0 values.

yAxis: {
  softMax: 1,
  ...
}

API Reference: https://api.highcharts.com/highcharts/yAxis.softMax


问:
In Azure Devops, how can i use pipeline variables in a "Azure CLI task v.2" running shell script?
I am trying to execute a task using Azure CLI and bash in Azure Devops. I am using Azure CLI task v.2 and choosing shell as script type as below.

I want to use pipeline variables in bash script. I run the command below inside the script:

```<code>#!/bin/bash
az role assignment create --role "Lab Admin" --assignee $(ownerEmail) -g $(rgName)
</code>```

and i got the error below:

```<code> line 2: ownerEmail: command not found
 line 2: rgName: command not found
</code>```

I don't understand. Normally, i should be able to use azure cli in a bash script.
Does anybody have an idea?

答:
There are a couple of ways you could read the pipeline variables in your bash script:

(Suggested) Read them straight as environment variables in the script. Azure DevOps pipeline variables are added as environment variables that can be accessed by your bash script. So just by defining/setting the pipeline variables you can access them from the bash script. i.e in your script reference them as $OWNERNAME and $RGNAME.

See > https://learn.microsoft.com/en-us/azure/devops/pipelines/process/variables#environment-variables

Reference the direct argument in the bash script. Bash arguments are numbered and can be referenced as such. e.g for your aruments $1 is the string "-labOwner" $2 is the value contained within the ownerEmail pipeline variable.

See > https://tecadmin.net/tutorial/bash-scripting/bash-command-arguments/

Body:
I am trying to execute a task using Azure CLI and bash in Azure Devops. I am using Azure CLI task v.2 and choosing shell as script type as below.

I want to use pipeline variables in bash script. I run the command below inside the script:

#!/bin/bash
az role assignment create --role "Lab Admin" --assignee $(ownerEmail) -g $(rgName)

and i got the error below:

 line 2: ownerEmail: command not found
 line 2: rgName: command not found

I don't understand. Normally, i should be able to use azure cli in a bash script.
Does anybody have an idea?


问:
OpenCL 2.0 Device command queue keeps filling up and halting execution
I am utilizing OpenCL's enqueue_kernel() function to enqueue kernels dynamically from the GPU to reduce unnecessary host interactions. Here is a simplified example of what I am trying to do in the kernels:

```<code>kernel void kernelA(args)
{
    //This kernel is the one that is enqueued from the host, with only one work item. This kernel
    //could be considered the "master" kernel that controls the logic of when to enqueue tasks
    //First, it checks if a condition is met, then it enqueues kernelB

    if (some condition)
    {
        enqueue_kernel(get_default_queue(), CLK_ENQUEUE_FLAGS_WAIT_KERNEL, ndrange_1D(some amount, 256), ^{kernelB(args);});
    }
    else
    {
        //do other things
    }
}

kernel void kernelB(args)
{
    //Do some stuff

    //Only enqueue the next kernel with the first work item. I do this because the things
    //occurring in kernelC rely on the things that kernelB does, so it must take place after kernelB is completed,
    //hence, the CLK_ENQUEUE_FLAGS_WAIT_KERNEL
    if (get_global_id(0) == 0)
    {
        enqueue_kernel(get_default_queue(), CLK_ENQUEUE_FLAGS_WAIT_KERNEL, ndrange_1D(some amount, 256), ^{kernelC(args);});
    }
}

kernel void kernelC(args)
{
    //Do some stuff. This one in particular is one step in a sorting algorithm

    //This kernel will enqueue kernelD if a condition is met, otherwise it will
    //return to kernelA
    if (get_global_id(0) == 0 && other requirements)
    {
        enqueue_kernel(get_default_queue(), CLK_ENQUEUE_FLAGS_WAIT_KERNEL, ndrange_1D(1, 1), ^{kernelD(args);});
    }
    else if (get_global_id(0) == 0)
    {
        enqueue_kernel(get_default_queue(), CLK_ENQUEUE_FLAGS_WAIT_KERNEL, ndrange_1D(1, 1), ^{kernelA(args);});
    }
}

kernel void kernelD(args)
{
    //Do some stuff

    //Finally, if some condition is met, enqueue kernelC again. What this will do is it will
    //bounce back and forth between kernelC and kernelD until the condition is
    //no longer met. If it isn't met, go back to kernelA
    if (some condition)
    {
        enqueue_kernel(get_default_queue(), CLK_ENQUEUE_FLAGS_WAIT_KERNEL, ndrange_1D(some amount, 256), ^{kernelC(args);});
    }
    else
    {
        enqueue_kernel(get_default_queue(), CLK_ENQUEUE_FLAGS_WAIT_KERNEL, ndrange_1D(1, 1), ^{kernelA(args);});
    }
}
</code>```

So that is the general flow of the program, and it works perfectly and does exactly as I intended it to do, in the exact order I intended it to do it in, except for one issue. In certain cases when the workload is very high, a random one of the enqueue_kernel()s will fail to enqueue and halt the program. This happens because the device queue is full, and it cannot fit another task into it. But I cannot for the life of me figure out why this is, even after extensive research.

I thought that once a task in the queue (a kernel for instance) is finished, it would free up that spot in the queue. So my queue should really only reach a max of like 1 or 2 tasks at a time. But this program will literally fill up the entire 262,144 byte size of the device command queue, and stop functioning.

I would greatly appreciate some potential insight as to why this is happening if anyone has any ideas. I am sort of stuck and cannot continue until I get past this issue.

Thank you in advance!

(BTW I am running on a Radeon RX 590 card, and am using the AMD APP SDK 3.0 to use with OpenCL 2.0)

答:
I don't know exactly what's going wrong, but I've noticed a few things in the code you posted and this feedback would be too long/hard to read in comments, so here goes - not a definite answer, but an attempt to get a bit closer:

Code doesn't quite do what the comments say

In kernelD, you have:

```<code>//Finally, if some condition is met, enqueue kernelC again.
</code>```

…

```<code>if (get_global_id(0) == 0)
{
    enqueue_kernel(get_default_queue(), CLK_ENQUEUE_FLAGS_WAIT_KERNEL, ndrange_1D(some amount, 256), ^{kernelD(args);});
}
</code>```

This actually enqueues kernelD itself again, not kernelC as the comments suggest. The other condition branch enqueues kernelA.

This could be a typo in the reduced version of your code.

Potential task explosion

This could again be down to the way you've abridged the code, but I don't quite see how

So my queue should really only reach a max of like 1 or 2 tasks at a time.

can be true. By my reading, all work items of both kernelC and kernelD will spawn new tasks; and as there seems to be more than 1 work item in each case, this seems like it could easily spawn a very large number of tasks:

For example, in kernelC:

```<code>if (get_global_id(0) == 0 && other requirements)
{
    enqueue_kernel(get_default_queue(), CLK_ENQUEUE_FLAGS_WAIT_KERNEL, ndrange_1D(some amount, 256), ^{kernelD(args);});
}
else
{
    enqueue_kernel(get_default_queue(), CLK_ENQUEUE_FLAGS_WAIT_KERNEL, ndrange_1D(1, 1), ^{kernelA(args);});
}
</code>```

kernelB will have created at least 256 work items running kernelC. Here, work item 0 will (if other requirements met) spawn 1 task with at least 256 more work items, and 255+ tasks with 1 work-item running kernelA. kernelD behaves similarly.

So with a few iterations, you could easily end up with a few thousand tasks for running kernelA queued. I don't really know what your code does, but it seems like a good idea to check if cutting down these hundreds of kernelA tasks improves the situation, and whether you can perhaps modify kernelA so that you just enqueue it once with a range instead of enqueueing a work size of 1 from every work item. (Or something along those lines - perhaps enqueue once per group if that makes more sense. Basically, reduce the number of times enqueue_kernel gets called.)

enqueue_kernel() return value

Have you actually checked the return value for enqueue_kernel? It tells you exactly why it failed, so even if my suggestion above isn't possible, perhaps you can set some global state which will allow kernelA to restart the calculation once more tasks have drained, if it was interrupted?

Body:
I am utilizing OpenCL's enqueue_kernel() function to enqueue kernels dynamically from the GPU to reduce unnecessary host interactions. Here is a simplified example of what I am trying to do in the kernels:

kernel void kernelA(args)
{
    //This kernel is the one that is enqueued from the host, with only one work item. This kernel
    //could be considered the "master" kernel that controls the logic of when to enqueue tasks
    //First, it checks if a condition is met, then it enqueues kernelB

    if (some condition)
    {
        enqueue_kernel(get_default_queue(), CLK_ENQUEUE_FLAGS_WAIT_KERNEL, ndrange_1D(some amount, 256), ^{kernelB(args);});
    }
    else
    {
        //do other things
    }
}

kernel void kernelB(args)
{
    //Do some stuff

    //Only enqueue the next kernel with the first work item. I do this because the things
    //occurring in kernelC rely on the things that kernelB does, so it must take place after kernelB is completed,
    //hence, the CLK_ENQUEUE_FLAGS_WAIT_KERNEL
    if (get_global_id(0) == 0)
    {
        enqueue_kernel(get_default_queue(), CLK_ENQUEUE_FLAGS_WAIT_KERNEL, ndrange_1D(some amount, 256), ^{kernelC(args);});
    }
}

kernel void kernelC(args)
{
    //Do some stuff. This one in particular is one step in a sorting algorithm

    //This kernel will enqueue kernelD if a condition is met, otherwise it will
    //return to kernelA
    if (get_global_id(0) == 0 && other requirements)
    {
        enqueue_kernel(get_default_queue(), CLK_ENQUEUE_FLAGS_WAIT_KERNEL, ndrange_1D(1, 1), ^{kernelD(args);});
    }
    else if (get_global_id(0) == 0)
    {
        enqueue_kernel(get_default_queue(), CLK_ENQUEUE_FLAGS_WAIT_KERNEL, ndrange_1D(1, 1), ^{kernelA(args);});
    }
}

kernel void kernelD(args)
{
    //Do some stuff

    //Finally, if some condition is met, enqueue kernelC again. What this will do is it will
    //bounce back and forth between kernelC and kernelD until the condition is
    //no longer met. If it isn't met, go back to kernelA
    if (some condition)
    {
        enqueue_kernel(get_default_queue(), CLK_ENQUEUE_FLAGS_WAIT_KERNEL, ndrange_1D(some amount, 256), ^{kernelC(args);});
    }
    else
    {
        enqueue_kernel(get_default_queue(), CLK_ENQUEUE_FLAGS_WAIT_KERNEL, ndrange_1D(1, 1), ^{kernelA(args);});
    }
}

So that is the general flow of the program, and it works perfectly and does exactly as I intended it to do, in the exact order I intended it to do it in, except for one issue. In certain cases when the workload is very high, a random one of the enqueue_kernel()s will fail to enqueue and halt the program. This happens because the device queue is full, and it cannot fit another task into it. But I cannot for the life of me figure out why this is, even after extensive research.

I thought that once a task in the queue (a kernel for instance) is finished, it would free up that spot in the queue. So my queue should really only reach a max of like 1 or 2 tasks at a time. But this program will literally fill up the entire 262,144 byte size of the device command queue, and stop functioning.

I would greatly appreciate some potential insight as to why this is happening if anyone has any ideas. I am sort of stuck and cannot continue until I get past this issue.

Thank you in advance!

(BTW I am running on a Radeon RX 590 card, and am using the AMD APP SDK 3.0 to use with OpenCL 2.0)

Body:
I don't know exactly what's going wrong, but I've noticed a few things in the code you posted and this feedback would be too long/hard to read in comments, so here goes - not a definite answer, but an attempt to get a bit closer:

Code doesn't quite do what the comments say

In kernelD, you have:

//Finally, if some condition is met, enqueue kernelC again.

…

if (get_global_id(0) == 0)
{
    enqueue_kernel(get_default_queue(), CLK_ENQUEUE_FLAGS_WAIT_KERNEL, ndrange_1D(some amount, 256), ^{kernelD(args);});
}

This actually enqueues kernelD itself again, not kernelC as the comments suggest. The other condition branch enqueues kernelA.

This could be a typo in the reduced version of your code.

Potential task explosion

This could again be down to the way you've abridged the code, but I don't quite see how

So my queue should really only reach a max of like 1 or 2 tasks at a time.

can be true. By my reading, all work items of both kernelC and kernelD will spawn new tasks; and as there seems to be more than 1 work item in each case, this seems like it could easily spawn a very large number of tasks:

For example, in kernelC:

if (get_global_id(0) == 0 && other requirements)
{
    enqueue_kernel(get_default_queue(), CLK_ENQUEUE_FLAGS_WAIT_KERNEL, ndrange_1D(some amount, 256), ^{kernelD(args);});
}
else
{
    enqueue_kernel(get_default_queue(), CLK_ENQUEUE_FLAGS_WAIT_KERNEL, ndrange_1D(1, 1), ^{kernelA(args);});
}

kernelB will have created at least 256 work items running kernelC. Here, work item 0 will (if other requirements met) spawn 1 task with at least 256 more work items, and 255+ tasks with 1 work-item running kernelA. kernelD behaves similarly.

So with a few iterations, you could easily end up with a few thousand tasks for running kernelA queued. I don't really know what your code does, but it seems like a good idea to check if cutting down these hundreds of kernelA tasks improves the situation, and whether you can perhaps modify kernelA so that you just enqueue it once with a range instead of enqueueing a work size of 1 from every work item. (Or something along those lines - perhaps enqueue once per group if that makes more sense. Basically, reduce the number of times enqueue_kernel gets called.)

enqueue_kernel() return value

Have you actually checked the return value for enqueue_kernel? It tells you exactly why it failed, so even if my suggestion above isn't possible, perhaps you can set some global state which will allow kernelA to restart the calculation once more tasks have drained, if it was interrupted?


问:
Passing an object's Type in a call to a Generic
I've seen several other similar posts, but they don't seem to fit with my scenario.

I'm trying to create a set of deep Cloning methods to a set of objects that inherit from a base class.  I've created some sample classes that illustrate what I'm trying to do.

I've been reading through all the similar posts here and the MS documentation, but nothing seems to work.  Any suggestions on how to approach this would be appreciated.

The offending line of code in this is below.  Using typeof(c) is invalid and I cannot find any suitable way of replacing that with something that does work.

```<code>SubEvents = (IList<IFoo>) SubEvents.Select(c => c.Clone < typeof(c) > ()).ToList()
</code>```

I cannot figure a way to pass the object's type to the Clone method.

```<code>public class MyFoo : IFoo
{
    public int Id { get; set; }
    public IList<IFoo> SubEvents { get; set; } = new List<IFoo>();

    public T Clone<T>() where T : IFoo, new()
    {
        var rtn = new T
        {
            Id = Id,
            SubEvents = (IList<IMyFoo>) SubEvents.Select(c => c.Clone < typeof(c) > ()).ToList()
        };
        return rtn;
    }
}

public class Bar: Foo, IBar
{
    public int Fred { get; set; }
    public int Betty { get; set; }

    public IEventQuestTimerChange Clone()
    {
        var rtn = base.Clone<Foo>();
        rtn.Fred = Fred;
        rtn.Betty = Betty;
        return rtn;
    }
}

public class Loader
{
    var IList<IFoo> MyList {get;set;} = new List<IFoo>();
    MyList.Add(new Foo());
    var bar = new Bar();
    bar.SubEvent.Add(new Foo());
    bar.SubEvent.Add(new Bar());
    MyList.Add(bar);

    var cloneList = MyList.Clone();
}
</code>```

答:
You cant pass a type into a generic like that and the only way to do it is using reflection.

Instead add an overload to T Clone<T>(... for object Clone(Type type)

Body:
I've seen several other similar posts, but they don't seem to fit with my scenario.

I'm trying to create a set of deep Cloning methods to a set of objects that inherit from a base class.  I've created some sample classes that illustrate what I'm trying to do.

I've been reading through all the similar posts here and the MS documentation, but nothing seems to work.  Any suggestions on how to approach this would be appreciated.

The offending line of code in this is below.  Using typeof(c) is invalid and I cannot find any suitable way of replacing that with something that does work.

SubEvents = (IList<IFoo>) SubEvents.Select(c => c.Clone < typeof(c) > ()).ToList()

I cannot figure a way to pass the object's type to the Clone method.

public class MyFoo : IFoo
{
    public int Id { get; set; }
    public IList<IFoo> SubEvents { get; set; } = new List<IFoo>();

    public T Clone<T>() where T : IFoo, new()
    {
        var rtn = new T
        {
            Id = Id,
            SubEvents = (IList<IMyFoo>) SubEvents.Select(c => c.Clone < typeof(c) > ()).ToList()
        };
        return rtn;
    }
}

public class Bar: Foo, IBar
{
    public int Fred { get; set; }
    public int Betty { get; set; }

    public IEventQuestTimerChange Clone()
    {
        var rtn = base.Clone<Foo>();
        rtn.Fred = Fred;
        rtn.Betty = Betty;
        return rtn;
    }
}

public class Loader
{
    var IList<IFoo> MyList {get;set;} = new List<IFoo>();
    MyList.Add(new Foo());
    var bar = new Bar();
    bar.SubEvent.Add(new Foo());
    bar.SubEvent.Add(new Bar());
    MyList.Add(bar);

    var cloneList = MyList.Clone();
}


问:
How to resume a suspended Camel consumer
I created a RoutePolicy that suspends a consumer when a configurable number of errors occurred in the route.

Before I suspend the consumer I want to make sure it will be resumed after a configurable amount of time (for example 30 minutes after suspension).

What is the best way to achieve this?

I tried to use the onExchangeBegin method of the RoutePolicy. But in a test I found that it is no more executed when the route is suspended (as I assumed).

I tried to create a SimpleScheduledRoutePolicy before suspending the route but I didn't found a way to register this new Bean in the Camel context (backed by Spring).

Therefore I currently create a TimerTask that sends a message to Camel Control Bus to resume the route. That works, but feels a bit of alien since Camel does not know about such resume tasks.

Is there another, more "Camel native" way to reach my goal?

答:
Before you suspend the consumer, you can create a dummy file.

Have another route polling for the dummy file with a filter to check if it was created 30 minutes prior. Something like:

```<code>from("file:dummyLocation?include=.dummy&delete=true&filter=#filterFileOlderThanThirtyMins)
.to("controlbus:route?routeId=suspendedRoute&action=start")
</code>```

This is just off the top of my head, though!

Body:
Before you suspend the consumer, you can create a dummy file.

Have another route polling for the dummy file with a filter to check if it was created 30 minutes prior. Something like:

from("file:dummyLocation?include=.dummy&delete=true&filter=#filterFileOlderThanThirtyMins)
.to("controlbus:route?routeId=suspendedRoute&action=start")

This is just off the top of my head, though!


问:
When use this code ```Form1 form = new Form1();``` something goes wrong
I'm trying to use use the code form.mainPnl.Controls.Add(background); where mainPnl is a panel I have added to Form1 that im just using for a base, and background is being created during debug.

```<code>var background = new Panel
{
Name = "background",
Dock = DockStyle.Fill,
BackColor = Color.Black,
};
</code>```

Im working in a side class (Not sure what it's called. It's just not the base class) which means I cant use anything from the mainPnl panel without getting it from Form1 so I need to use Form1 form = new Form1(); but whenever I use this I think it's looping and crashing the program.

Main Class:

```<code>public partial class Form1 : Form
    {
        public Panel mainPnl
        {
            get
            {
                return mainPanel;
            }
        }
        public TextBox textbox
        {
            get
            {
                return hey;
            }
        }

        Menu menu = new Menu();

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            menu.Main();
        }

        private void Update_Tick(object sender, EventArgs e)
        {

        }
    }
</code>```

Side Class:

```<code>class Menu
    {
        Form1 form = new Form1();

        public void Main()
        {
            createObjects();
        }

        public void createObjects()
        {
            var background = new Panel
            {
                Name = "background",
                Dock = DockStyle.Fill,
                BackColor = Color.Black,
            };
            form.mainPnl.Controls.Add(background);
        }
    }
</code>```

Thats the only code. But when I run the code, it shows an error and highlights that code and says 'Exception of type 'System.StackOverflowException' was thrown'

答:
In your form you have:

```<code>public partial class Form1 : Form
{
    Menu menu = new Menu();
}
</code>```

And in your Menu class you have:

```<code>class Menu
{
    Form1 form = new Form1();
}
</code>```

And when you instantiate your form, it creates a menu which instantiates a new form which creates a new menu and so on until you run out of stack space for the mutually recursive constructors.

I'm not sure what exactly you're trying to do or what your question is other than why you're getting a stack overflow, so here you go!

Body:
I'm trying to use use the code form.mainPnl.Controls.Add(background); where mainPnl is a panel I have added to Form1 that im just using for a base, and background is being created during debug.

var background = new Panel
{
Name = "background",
Dock = DockStyle.Fill,
BackColor = Color.Black,
};

Im working in a side class (Not sure what it's called. It's just not the base class) which means I cant use anything from the mainPnl panel without getting it from Form1 so I need to use Form1 form = new Form1(); but whenever I use this I think it's looping and crashing the program.

Main Class:

public partial class Form1 : Form
    {
        public Panel mainPnl
        {
            get
            {
                return mainPanel;
            }
        }
        public TextBox textbox
        {
            get
            {
                return hey;
            }
        }

        Menu menu = new Menu();

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            menu.Main();
        }

        private void Update_Tick(object sender, EventArgs e)
        {

        }
    }

Side Class:

class Menu
    {
        Form1 form = new Form1();

        public void Main()
        {
            createObjects();
        }

        public void createObjects()
        {
            var background = new Panel
            {
                Name = "background",
                Dock = DockStyle.Fill,
                BackColor = Color.Black,
            };
            form.mainPnl.Controls.Add(background);
        }
    }

Thats the only code. But when I run the code, it shows an error and highlights that code and says 'Exception of type 'System.StackOverflowException' was thrown'

Body:
In your form you have:

public partial class Form1 : Form
{
    Menu menu = new Menu();
}

And in your Menu class you have:

class Menu
{
    Form1 form = new Form1();
}

And when you instantiate your form, it creates a menu which instantiates a new form which creates a new menu and so on until you run out of stack space for the mutually recursive constructors.

I'm not sure what exactly you're trying to do or what your question is other than why you're getting a stack overflow, so here you go!


问:
How to create submodule in python? Thank
how to create submodule in python? Thanks!
I need write _init__.py?
It name will be pybase

答:
A folder with .py files and a init.py is called a package. One of those files containing classes and functions is a module. Folder nesting can give you subpackages.

So for example if I had the following structure:

```<code>mypackage
__init__.py
module_a.py
module_b.py
mysubpackage
__init__.py
module_c.py
module_d.py

</code>```

I could import mypackage.module_a or mypackage.mysubpacakge.module_c and so on.

You could also add functions to mypackage (like the numpy functions you mentioned) by placing that code in the init.py. Though this is usually considered to be ugly.

If you look at numpy's init.py you will see a lot of code in there - a lot of this is defining these top-level classes and functions. The init.py code is the first thing executed when the package is loaded.

Body:
A folder with .py files and a init.py is called a package. One of those files containing classes and functions is a module. Folder nesting can give you subpackages.

So for example if I had the following structure:

mypackage
__init__.py
module_a.py
module_b.py
mysubpackage
__init__.py
module_c.py
module_d.py

I could import mypackage.module_a or mypackage.mysubpacakge.module_c and so on.

You could also add functions to mypackage (like the numpy functions you mentioned) by placing that code in the init.py. Though this is usually considered to be ugly.

If you look at numpy's init.py you will see a lot of code in there - a lot of this is defining these top-level classes and functions. The init.py code is the first thing executed when the package is loaded.


问:
How to index coordinate data according to a grid in R?
I have coordinate data (x-coordinates and y-coordinates) on a scale between:
Xpos: 27-1367nm, Ypos: 67-1014nm. A data set consists of about 2500-3500 data points.
Here is the header of such a data set:

```<code>   XPos YPos
1    29  211
2    31  609
3    33 1001
4    35  508
5    37  424
6    39  584
7    40  378
8    41  204
9    41  444
10   41  872
...
</code>```

[![Data plotted][1]][1]

Now I would like to index the data points by applying a grid consisting of equal sized quadrants onto the data in R. The result should be a new column "grid_index" containing a unique quadrant_ID in which the data points are located (see image). Is there an easy way to do this? I would like to try different grid unit sizes to partition the data e.g. quadrants sized 50nm, 100nm, 200nm or 400nm and rectangles sized 100nm x 200nm or 50nm x100nm.

[![Grid for data pint indexing][2]][2]

[![Each grid quadrant should have an unique ID][3]][3]

I would be very grateful for any help.

答:
Here's an approach with findInterval:

First set up a matrix that has the appropriate number of indices:

```<code>pos.matrix <- matrix(1:35,byrow = TRUE, nrow = 5)
pos.matrix
     [,1] [,2] [,3] [,4] [,5] [,6] [,7]
[1,]    1    2    3    4    5    6    7
[2,]    8    9   10   11   12   13   14
[3,]   15   16   17   18   19   20   21
[4,]   22   23   24   25   26   27   28
[5,]   29   30   31   32   33   34   35
</code>```

Next use findInterval to find the indices of the matrix of where it lies. You can control the size of the grid using the by = argument. Note that the dimensions of the matrix must match the number of intervals provided in findInterval. We need to use abs because the y values are decreasing on the graph.

```<code>grid <- apply(cbind(findInterval(data[,"XPos"],seq(0,1400,by = 200)),
                    abs(findInterval(data[,"YPos"],seq(0,1000,by = 200)) - 6)),
              MARGIN = 1,
              function(x) pos.matrix[x[2],x[1]])
grid[1:25]
[1] 30 34 31 17 19 26 15 31 19  5 18 32 25 25 14 20 22 19 35  2 16  8 29 29 16
plot(NA,xlim = c(0,1400), ylim = c(0,1000), xlab = "XPos", ylab = "YPos", cex.axis = 0.8)
text(data[,1],data[,2], labels = grid, cex = 0.4)
</code>```

Sample Data

```<code>set.seed(3)
data <- data.frame(XPos = runif(1000,0,1400), YPos = runif(1000,0,1000))
</code>```

Body:
I have coordinate data (x-coordinates and y-coordinates) on a scale between:
Xpos: 27-1367nm, Ypos: 67-1014nm. A data set consists of about 2500-3500 data points.
Here is the header of such a data set:

   XPos YPos
1    29  211
2    31  609
3    33 1001
4    35  508
5    37  424
6    39  584
7    40  378
8    41  204
9    41  444
10   41  872
...

[![Data plotted][1]][1]

Now I would like to index the data points by applying a grid consisting of equal sized quadrants onto the data in R. The result should be a new column "grid_index" containing a unique quadrant_ID in which the data points are located (see image). Is there an easy way to do this? I would like to try different grid unit sizes to partition the data e.g. quadrants sized 50nm, 100nm, 200nm or 400nm and rectangles sized 100nm x 200nm or 50nm x100nm.

[![Grid for data pint indexing][2]][2]

[![Each grid quadrant should have an unique ID][3]][3]

I would be very grateful for any help.

Body:
Here's an approach with findInterval:

First set up a matrix that has the appropriate number of indices:

pos.matrix <- matrix(1:35,byrow = TRUE, nrow = 5)
pos.matrix
     [,1] [,2] [,3] [,4] [,5] [,6] [,7]
[1,]    1    2    3    4    5    6    7
[2,]    8    9   10   11   12   13   14
[3,]   15   16   17   18   19   20   21
[4,]   22   23   24   25   26   27   28
[5,]   29   30   31   32   33   34   35

Next use findInterval to find the indices of the matrix of where it lies. You can control the size of the grid using the by = argument. Note that the dimensions of the matrix must match the number of intervals provided in findInterval. We need to use abs because the y values are decreasing on the graph.

grid <- apply(cbind(findInterval(data[,"XPos"],seq(0,1400,by = 200)),
                    abs(findInterval(data[,"YPos"],seq(0,1000,by = 200)) - 6)),
              MARGIN = 1,
              function(x) pos.matrix[x[2],x[1]])
grid[1:25]
[1] 30 34 31 17 19 26 15 31 19  5 18 32 25 25 14 20 22 19 35  2 16  8 29 29 16
plot(NA,xlim = c(0,1400), ylim = c(0,1000), xlab = "XPos", ylab = "YPos", cex.axis = 0.8)
text(data[,1],data[,2], labels = grid, cex = 0.4)

Sample Data

set.seed(3)
data <- data.frame(XPos = runif(1000,0,1400), YPos = runif(1000,0,1000))


问:
CSS media not working on a set of devices
I have written media queries for a project i am working on. The whole devices on my chrome are working fine on samsung, pixel and I-phones but not working on Infinix and tecno phones. These are media queries i used:

```<code>@media (max-width: 320px)
@media (min-width: 360px) and (max-width: 384px)
@media (max-width: 768px)
</code>```

All the devices on my chrome device emulator is working fine but when i check with mt infinix and tecno phones, it doesnt work fine. Check the screenshots for tecno for infinix for samsung for iphone
The navigation is showing well in the last two but not in the first two

答:
Give these breakpoints a try. They are used in Bootstrap

```<code>@media (max-width: 575.98px) {
  ...
}
@media (min-width: 576px) and (max-width: 767.98px) {
  ...
}
@media (min-width: 768px) {
  ...
}
</code>```

It is best practice to have no gaps in your @media because there are so many devices you cannot test on.

Do not think in devices, but think in "@media ranges". If the webpage is looking well in each @media range then it looks fine on all devices.

Body:
I have written media queries for a project i am working on. The whole devices on my chrome are working fine on samsung, pixel and I-phones but not working on Infinix and tecno phones. These are media queries i used:

@media (max-width: 320px)
@media (min-width: 360px) and (max-width: 384px)
@media (max-width: 768px)

All the devices on my chrome device emulator is working fine but when i check with mt infinix and tecno phones, it doesnt work fine. Check the screenshots for tecno for infinix for samsung for iphone
The navigation is showing well in the last two but not in the first two

Body:
Give these breakpoints a try. They are used in Bootstrap

@media (max-width: 575.98px) {
  ...
}
@media (min-width: 576px) and (max-width: 767.98px) {
  ...
}
@media (min-width: 768px) {
  ...
}

It is best practice to have no gaps in your @media because there are so many devices you cannot test on.

Do not think in devices, but think in "@media ranges". If the webpage is looking well in each @media range then it looks fine on all devices.


问:
Android navigation component resets to start destination after configuration change
I am using the Android navigation component and I have an activity with three fragments
if I am in the second fragment and rotate the screen forcing the activity to restart the navigation is returned to the start destination.

shouldn't the navhostFragment retain the state of the graph when the activity restarts?

or is what is happening the default behavior here?

I don't want to add the following even though adding it "works"

```<code> android:configChanges="orientation|screenSize|screenLayout|keyboardHidden"
</code>```

because I don't want to handle orientation changes myself, I want it to be handled by the system normally and still retain the navigation state

I will provide some of my code if that helps

in the activity I use navController.setGraph() so I can pass data to the start destination like this

```<code> navController = Navigation.findNavController(
        this,
        R.id.nav_host_fragment
    )
 setSupportActionBar(findViewById(R.id.toolbar))
 appBarConfiguration = AppBarConfiguration.Builder(navController.graph).build()
 supportActionBar?.setDisplayHomeAsUpEnabled(true)

 intent.putExtra("EXTRA_KEY","some_data")
 navController.setGraph(R.navigation.nav_graph,intent.extras)
</code>```

and I navigate from fragment to fragment using this

```<code>navController.navigate(FirstFragmentDirections.actionFirstFragmentToSecondFragment())
</code>```

here is the code in the nav_graph

```<code><fragment
    android:id="@+id/FirstFragment"
    android:name="com.example.app.presentation.ui.FirstFragment"
    android:label="FirstFragment" >
    <action
        android:id="@+id/action_FirstFragment_to_secondFragment"
        app:destination="@id/secondFragment"
        app:enterAnim="@anim/enter_from_right"
        app:exitAnim="@anim/exit_to_left"
        app:popEnterAnim="@anim/enter_from_left"
        app:popExitAnim="@anim/exit_to_right"
        />
</fragment>
<fragment
    android:id="@+id/secondFragment"
    android:name="com.example.app.presentation.ui.secondFragment"
    android:label="secondFragment"
    tools:layout="@layout/fragment_second" />
</code>```

any help is appreciated thank you

答:
You should generally never need to call setGraph() yourself, but you can workaround it like so in this particular case (and it will actually still work as you expect, because NavController / Navigator restores state properly across config changes and process death automatically):

```<code>if (savedInstanceState == null) {
    navController.setGraph(R.navigation.nav_graph,intent.extras)
}
</code>```

Body:
I am using the Android navigation component and I have an activity with three fragments
if I am in the second fragment and rotate the screen forcing the activity to restart the navigation is returned to the start destination.

shouldn't the navhostFragment retain the state of the graph when the activity restarts?

or is what is happening the default behavior here?

I don't want to add the following even though adding it "works"

 android:configChanges="orientation|screenSize|screenLayout|keyboardHidden"

because I don't want to handle orientation changes myself, I want it to be handled by the system normally and still retain the navigation state

I will provide some of my code if that helps

in the activity I use navController.setGraph() so I can pass data to the start destination like this

 navController = Navigation.findNavController(
        this,
        R.id.nav_host_fragment
    )
 setSupportActionBar(findViewById(R.id.toolbar))
 appBarConfiguration = AppBarConfiguration.Builder(navController.graph).build()
 supportActionBar?.setDisplayHomeAsUpEnabled(true)

 intent.putExtra("EXTRA_KEY","some_data")
 navController.setGraph(R.navigation.nav_graph,intent.extras)

and I navigate from fragment to fragment using this

navController.navigate(FirstFragmentDirections.actionFirstFragmentToSecondFragment())

here is the code in the nav_graph

<fragment
    android:id="@+id/FirstFragment"
    android:name="com.example.app.presentation.ui.FirstFragment"
    android:label="FirstFragment" >
    <action
        android:id="@+id/action_FirstFragment_to_secondFragment"
        app:destination="@id/secondFragment"
        app:enterAnim="@anim/enter_from_right"
        app:exitAnim="@anim/exit_to_left"
        app:popEnterAnim="@anim/enter_from_left"
        app:popExitAnim="@anim/exit_to_right"
        />
</fragment>
<fragment
    android:id="@+id/secondFragment"
    android:name="com.example.app.presentation.ui.secondFragment"
    android:label="secondFragment"
    tools:layout="@layout/fragment_second" />

any help is appreciated thank you

Body:
You should generally never need to call setGraph() yourself, but you can workaround it like so in this particular case (and it will actually still work as you expect, because NavController / Navigator restores state properly across config changes and process death automatically):

if (savedInstanceState == null) {
    navController.setGraph(R.navigation.nav_graph,intent.extras)
}


问:
Are methods that modify reference type parameters bad?
I've seen methods like this:

```<code>public void Foo(List<string> list)
{
    list.Add("Bar");
}
</code>```

Is this good practice to modify parameters in a method?

Wouldn't this be better?

```<code>public List<string> Foo(List<string> list)
{
    // Edit
    List<string> newlist = new List<string>(list);
    newlist.Add("Bar");
    return newlist;
}
</code>```

It just feels like the first example has unexpected side effects.

答:
It's actually not that unexpected that a method that takes a list as parameter modifies the list. If you want a method that only reads from the list, you would use an interface that only allows reading:

```<code>public int GetLongest(IEnumerable<string> list) {
    int len = 0;
    foreach (string s in list) {
        len = Math.Max(len, s.Length);
    }
    return len;
}
</code>```

By using an interface like this you don't only prohibit the method from changing the list, it also gets more flexible as it can use any collection that implements the interface, like a string array for example.

Some other languages has a const keyword that can be applied to parameters to prohibit a method from changing them. As .NET has interfaces that you can use for this and strings that are immutable, there isn't really a need for const parameters.

OwnerDisplayName: Jonathan Parker

Body:
I've seen methods like this:

public void Foo(List<string> list)
{
    list.Add("Bar");
}

Is this good practice to modify parameters in a method?

Wouldn't this be better?

public List<string> Foo(List<string> list)
{
    // Edit
    List<string> newlist = new List<string>(list);
    newlist.Add("Bar");
    return newlist;
}

It just feels like the first example has unexpected side effects.

LastEditorDisplayName: Jonathan Parker

Body:
It's actually not that unexpected that a method that takes a list as parameter modifies the list. If you want a method that only reads from the list, you would use an interface that only allows reading:

public int GetLongest(IEnumerable<string> list) {
    int len = 0;
    foreach (string s in list) {
        len = Math.Max(len, s.Length);
    }
    return len;
}

By using an interface like this you don't only prohibit the method from changing the list, it also gets more flexible as it can use any collection that implements the interface, like a string array for example.

Some other languages has a const keyword that can be applied to parameters to prohibit a method from changing them. As .NET has interfaces that you can use for this and strings that are immutable, there isn't really a need for const parameters.

OwnerDisplayName: Guffa