问:
How I can change the price with the change of Text option - Opencart
How I can change the price with the change of Text option in OpenCart. The requirement is there is an input Text field (Size). When any number is put in the Text field (Size number / any number) the base price multiply with that number. Is there any extension to have same working, so I would not work on multiple pages of OpenCart.


来源: stackexchange

问:
Why is my form invalid with this error: "Select a valid choice. That choice is not one of the available choices."
forms.py:

class CategoryForm(forms.Form):
    category = forms.ModelChoiceField(queryset=Category.objects.filter(parent=None))
```
<p>models.py:</p>
<pre class="lang-py prettyprint-override"><code>class Category(models.Model):
    parent = models.ForeignKey(
        "Category",
        on_delete=models.CASCADE,
        related_name="children",
        null=True,
    )
    title = models.CharField(max_length=255)

    def __str__(self):
        return self.title
</code>```

views.py:

def category_select(request, pk):
    if request.method == "POST":
        form = CategoryForm(request.POST)

        if form.is_valid():
            category = form.cleaned_data["category"]
            if category.children.all():
                return redirect(reverse("category_select", args=[category.pk]))
            else:
                return HttpResponse("no children")
        else:
            return render(
                request,
                "ads/category_select.html",
                {
                    "form": form,
                },
            )
```

The purpose of this form is that if the user selected a category that has no children, it returns an HttpResponse('no children'). But when I select and submit the form, It gives me this error:

Select a valid choice. That choice is not one of the available choices.

ContentLicense: CC BY-SA 4.0

Body:
forms.py:

class CategoryForm(forms.Form):
    category = forms.ModelChoiceField(queryset=Category.objects.filter(parent=None))

models.py:

class Category(models.Model):
    parent = models.ForeignKey(
        "Category",
        on_delete=models.CASCADE,
        related_name="children",
        null=True,
    )
    title = models.CharField(max_length=255)

    def __str__(self):
        return self.title

views.py:

def category_select(request, pk):
    if request.method == "POST":
        form = CategoryForm(request.POST)

        if form.is_valid():
            category = form.cleaned_data["category"]
            if category.children.all():
                return redirect(reverse("category_select", args=[category.pk]))
            else:
                return HttpResponse("no children")
        else:
            return render(
                request,
                "ads/category_select.html",
                {
                    "form": form,
                },
            )

The purpose of this form is that if the user selected a category that has no children, it returns an HttpResponse('no children'). But when I select and submit the form, It gives me this error:

Select a valid choice. That choice is not one of the available choices.


问:
Printers not being found?
I am trying to set up an application that can print a ticket from a kiosk. I am attempting to use Rust along with the printers library.

https://docs.rs/printers/latest/printers/

I have attempted to do this as a Rust only application and also with Tauri.

I have followed the documentation and am receiving the following error when trying to get the printers on the system:
thread 'main' panicked at 'index out of bounds: the len is 0 but the index is 1'

This error points to the following code in the printers library code:

```<code>let printer_data: Vec<&str> = line.split_ascii_whitespace().collect();
let name = String::from(printer_data[1]);
let system_name = String::from(printer_data[0]);
</code>```

As I understand it, the error is being produced because there is no index of 1 in the printer_data variable.

```<code>use printers;
fn main() {
    let _printers = printers::get_printers();
}
</code>```

In my trawling of Google in order to find a solution to this problem I found the following thread which shows the same error with a proposed fix that refers to a line in the printers library code but my code already matches the fix, so they must have updated their code before I downloaded it, but I am still getting this error.

https://github.com/talesluna/rust-printers/issues/5

If anybody could help here it would be much appreciated! Even if it is suggesting a better way to print from a kiosk (controlled environment)!

Thanks

Title: Printers not being found?

Body:
I am trying to set up an application that can print a ticket from a kiosk. I am attempting to use Rust along with the printers library.

https://docs.rs/printers/latest/printers/

I have attempted to do this as a Rust only application and also with Tauri.

I have followed the documentation and am receiving the following error when trying to get the printers on the system:
thread 'main' panicked at 'index out of bounds: the len is 0 but the index is 1'

This error points to the following code in the printers library code:

let printer_data: Vec<&str> = line.split_ascii_whitespace().collect();
let name = String::from(printer_data[1]);
let system_name = String::from(printer_data[0]);

As I understand it, the error is being produced because there is no index of 1 in the printer_data variable.

use printers;
fn main() {
    let _printers = printers::get_printers();
}

In my trawling of Google in order to find a solution to this problem I found the following thread which shows the same error with a proposed fix that refers to a line in the printers library code but my code already matches the fix, so they must have updated their code before I downloaded it, but I am still getting this error.

https://github.com/talesluna/rust-printers/issues/5

If anybody could help here it would be much appreciated! Even if it is suggesting a better way to print from a kiosk (controlled environment)!

Thanks


问:
How can I avoid that $owner_password is set?
In your (documentation) there is only one possibility for $owner_password and that is that a password is always set as I understand.

Either I set a password myself or if I omit it/set it to zero then mpdf generates a password itself.

This is a big problem for us because we use your Libary to create invoices and automated invoicing systems from our customers think that there is a password problem.

In the following screenshot you can see that the "Security Method" is set to Password Security and "Permissions Password" is set to Yes.

The "Security Method" must be set to No Security and this only happens if this "Permissions Password" is not set.

We use the following code to set the protection:

```<code>$mpdf->SetProtection(array('print','copy','modify','annot-forms','fill-forms','extract','assemble','print-highres'));
</code>```

I hope you can help us with our problem and happy holidays :)

Body:
In your (documentation) there is only one possibility for $owner_password and that is that a password is always set as I understand.

Either I set a password myself or if I omit it/set it to zero then mpdf generates a password itself.

This is a big problem for us because we use your Libary to create invoices and automated invoicing systems from our customers think that there is a password problem.

In the following screenshot you can see that the "Security Method" is set to Password Security and "Permissions Password" is set to Yes.

The "Security Method" must be set to No Security and this only happens if this "Permissions Password" is not set.

We use the following code to set the protection:

$mpdf->SetProtection(array('print','copy','modify','annot-forms','fill-forms','extract','assemble','print-highres'));

I hope you can help us with our problem and happy holidays :)


问:
Size of element is not changing in wordpress site
I'm trying to insert a gauge into a wordpress site.
The gauge is a js object, which show a scrolling bar.

When I set style values of the element locally, the size of the guage changes.

```<code>            <div id="gauge2" class="gauge-container two" style="display:inline-block; min-height:100px;min-width:100px;float: left;width: 100%; height: 100%;padding-left: 300px;overflow: hidden"></div>
</code>```

When I set it in wordpress site, the size of the element stays the same(very small)

The full code is:

```<code><!DOCTYPE html>
<html>
   <head>
      <style>
  /* ------------------- Default Style ------------------------- */

  .gauge-container {
    width: auto;
    height: auto;
    display: block;
    /* float: left; */
    padding: 10px;
    overflow: hidden;
  }

  /* ------------------- Alternate Style ------------------------- */

  .gauge-container.two {
    height: auto;
    border: 1px solid rgba(255,255,255,0.1);
  }
  .gauge-container.two > .gauge > .dial {
    stroke: #334455;
    stroke-width: auto;
  }
  .gauge-container.two > .gauge > .value {
    /*stroke: orange;*/
    stroke-dasharray: none;
    stroke-width: 13;
  }
  .gauge-container.two > .gauge > .value {
    /*fill: orange;*/
  }

         .info {
         padding: 20px;
         }

         }
      </style>
             <script>
  /* global window, define, module */
(function(global, factory) {
  var Gauge = factory(global);
  if(typeof define === "function" && define.amd) {
    // AMD support
    define(function() {return Gauge;});
  }else if(typeof module === "object" && module.exports) {
    // CommonJS support
    module.exports = Gauge;
  }else {
    // We are probably running in the browser
    global.Gauge = Gauge;
  }
})(typeof window === "undefined" ? this : window, function(global, undefined) {

  var document = global.document,
    slice = Array.prototype.slice,
    requestAnimationFrame = (global.requestAnimationFrame ||
        global.mozRequestAnimationFrame ||
        global.webkitRequestAnimationFrame ||
        global.msRequestAnimationFrame ||
        function(cb) {
          return setTimeout(cb, 1000 / 60);
        });

  // EXPERIMENTAL!!
  /**
   * Simplistic animation function for animating the gauge. That's all!
   * Options are:
   * {
   *  duration: 1,    // In seconds
   *  start: 0,       // The start value
   *  end: 100,       // The end value
   *  step: function, // REQUIRED! The step function that will be passed the value and does something
   *  easing: function // The easing function. Default is easeInOutCubic
   * }
   */
  function Animation(options) {
    var duration = options.duration,
        currentIteration = 1,
        iterations = 60 * duration,
        start = options.start || 0,
        end = options.end,
        change = end - start,
        step = options.step,
        easing = options.easing || function easeInOutCubic(pos) {
          // https://github.com/danro/easing-js/blob/master/easing.js
          if ((pos/=0.5) < 1) return 0.5*Math.pow(pos,3);
          return 0.5 * (Math.pow((pos-2),3) + 2);
        };

    function animate() {
      var progress = currentIteration / iterations,
          value = change * easing(progress) + start;
      // console.log(progress + ", " + value);
      step(value, currentIteration);
      currentIteration += 1;

      if(progress < 1) {
        requestAnimationFrame(animate);
      }
    }
    // start!
    requestAnimationFrame(animate);
  }

  var Gauge = (function() {
    var SVG_NS = "http://www.w3.org/2000/svg";

    var GaugeDefaults = {
      centerX: 50,
      centerY: 50
    };

    var defaultOptions = {
      dialRadius: 40,
      dialStartAngle: 135,
      dialEndAngle: 45,
      value: 0,
      max: 100,
      min: 0,
      valueDialClass: "value",
      valueClass: "value-text",
      dialClass: "dial",
      gaugeClass: "gauge",
      showValue: true,
      gaugeColor: null,
      label: function(val) {return Math.round(val);}
    };

    function shallowCopy(/* source, ...targets*/) {
      var target = arguments[0], sources = slice.call(arguments, 1);
      sources.forEach(function(s) {
        for(var k in s) {
          if(s.hasOwnProperty(k)) {
            target[k] = s[k];
          }
        }
      });
      return target;
    }

    /**
     * A utility function to create SVG dom tree
     * @param {String} name The SVG element name
     * @param {Object} attrs The attributes as they appear in DOM e.g. stroke-width and not strokeWidth
     * @param {Array} children An array of children (can be created by this same function)
     * @return The SVG element
     */
    function svg(name, attrs, children) {
      var elem = document.createElementNS(SVG_NS, name);
      for(var attrName in attrs) {
        elem.setAttribute(attrName, attrs[attrName]);
      }

      if(children) {
        children.forEach(function(c) {
          elem.appendChild(c);
        });
      }
      return elem;
    }

    /**
     * Translates percentage value to angle. e.g. If gauge span angle is 180deg, then 50%
     * will be 90deg
     */
    function getAngle(percentage, gaugeSpanAngle) {
      return percentage * gaugeSpanAngle / 100;
    }

    function normalize(value, min, limit) {
      var val = Number(value);
      if(val > limit) return limit;
      if(val < min) return min;
      return val;
    }

    function getValueInPercentage(value, min, max) {
      var newMax = max - min, newVal = value - min;
      return 100 * newVal / newMax;
      // var absMin = Math.abs(min);
      // return 100 * (absMin + value) / (max + absMin);
    }

    /**
     * Gets cartesian co-ordinates for a specified radius and angle (in degrees)
     * @param cx {Number} The center x co-oriinate
     * @param cy {Number} The center y co-ordinate
     * @param radius {Number} The radius of the circle
     * @param angle {Number} The angle in degrees
     * @return An object with x,y co-ordinates
     */
    function getCartesian(cx, cy, radius, angle) {
      var rad = angle * Math.PI / 180;
      return {
        x: Math.round((cx + radius * Math.cos(rad)) * 1000) / 1000,
        y: Math.round((cy + radius * Math.sin(rad)) * 1000) / 1000
      };
    }

    // Returns start and end points for dial
    // i.e. starts at 135deg ends at 45deg with large arc flag
    // REMEMBER!! angle=0 starts on X axis and then increases clockwise
    function getDialCoords(radius, startAngle, endAngle) {
      var cx = GaugeDefaults.centerX,
          cy = GaugeDefaults.centerY;
      return {
        end: getCartesian(cx, cy, radius, endAngle),
       start: getCartesian(cx, cy, radius, startAngle)
      };
    }

    /**
     * Creates a Gauge object. This should be called without the 'new' operator. Various options
     * can be passed for the gauge:
     * {
     *    dialStartAngle: The angle to start the dial. MUST be greater than dialEndAngle. Default 135deg
     *    dialEndAngle: The angle to end the dial. Default 45deg
     *    dialRadius: The gauge's radius. Default 400
     *    max: The maximum value of the gauge. Default 100
     *    value: The starting value of the gauge. Default 0
     *    label: The function on how to render the center label (Should return a value)
     * }
     * @param {Element} elem The DOM into which to render the gauge
     * @param {Object} opts The gauge options
     * @return a Gauge object
     */
    return function Gauge(elem, opts) {
      opts = shallowCopy({}, defaultOptions, opts);
      var gaugeContainer = elem,
          limit = opts.max,
          min = opts.min,
          value = normalize(opts.value, min, limit),
          radius = opts.dialRadius,
          displayValue = opts.showValue,
          startAngle = opts.dialStartAngle,
          endAngle = opts.dialEndAngle,
          valueDialClass = opts.valueDialClass,
          valueTextClass = opts.valueClass,
          valueLabelClass = opts.valueLabelClass,
          dialClass = opts.dialClass,
          gaugeClass = opts.gaugeClass,
          gaugeColor = opts.color,
          gaugeValueElem,
          gaugeValuePath,
          label = opts.label,
          viewBox = opts.viewBox,
          instance;

      if(startAngle < endAngle) {
        console.log("WARN! startAngle < endAngle, Swapping");
        var tmp = startAngle;
        startAngle = endAngle;
        endAngle = tmp;
      }

      function pathString(radius, startAngle, endAngle, largeArc) {
        var coords = getDialCoords(radius, startAngle, endAngle),
            start = coords.start,
            end = coords.end,
            largeArcFlag = typeof(largeArc) === "undefined" ? 1 : largeArc;

        return [
          "M", start.x, start.y,
          "A", radius, radius, 0, largeArcFlag, 1, end.x, end.y
        ].join(" ");
      }

      function initializeGauge(elem) {
        gaugeValueElem = svg("text", {
          x: 50,
          y: 50,
          fill: "#999",
          "class": valueTextClass,
          "font-size": "100%",
          "font-family": "sans-serif",
          "font-weight": "normal",
          "text-anchor": "middle",
          "alignment-baseline": "middle",
          "dominant-baseline": "central"
        });

        gaugeValuePath = svg("path", {
          "class": valueDialClass,
          fill: "none",
          stroke: "#666",
          "stroke-width": 2.5,
          d: pathString(radius, startAngle, startAngle) // value of 0
        });

        var angle = getAngle(100, 360 - Math.abs(startAngle - endAngle));
        var flag = angle <= 180 ? 0 : 1;
        var gaugeElement = svg("svg", {"viewBox": viewBox || "0 0 100 100", "class": gaugeClass}, [
          svg("path", {
            "class": dialClass,
            fill: "none",
            stroke: "#eee",
            "stroke-width": 2,
            d: pathString(radius, startAngle, endAngle, flag)
          }),
          svg("g", { "class": "text-container" }, [gaugeValueElem]),
          gaugeValuePath
        ]);
        elem.appendChild(gaugeElement);
      }

      function updateGauge(theValue, frame) {
        var val = getValueInPercentage(theValue, 0, 100),
            // angle = getAngle(val, 360 - Math.abs(endAngle - startAngle)),
            angle = getAngle(val, 360 - Math.abs(startAngle - endAngle)),
            // this is because we are using arc greater than 180deg
            flag = angle <= 180 ? 0 : 1;
        if(displayValue) {
          gaugeValueElem.textContent = label.call(opts, theValue);
        }
        gaugeValuePath.setAttribute("d", pathString(radius, startAngle, angle + startAngle, flag));
      }

      function setGaugeColor(value, duration) {
        var c = gaugeColor.call(opts, value),
            dur = duration * 1000,
            pathTransition = "stroke " + dur + "ms ease";
            // textTransition = "fill " + dur + "ms ease";

        gaugeValuePath.style.stroke = c;
        gaugeValuePath.style["-webkit-transition"] = pathTransition;
        gaugeValuePath.style["-moz-transition"] = pathTransition;
        gaugeValuePath.style.transition = pathTransition;
        /*
        gaugeValueElem.style = [
          "fill: " + c,
          "-webkit-transition: " + textTransition,
          "-moz-transition: " + textTransition,
          "transition: " + textTransition,
        ].join(";");
        */
      }

      instance = {
        setMaxValue: function(max) {
          limit = max;
          updateGauge(value);
        },
        setValue: function(val) {
          value = normalize(val, 0, 100);
          if(gaugeColor) {
            setGaugeColor(value, 0)
          }
          updateGauge(value);
        },
        setValueAnimated: function(val, duration) {
           var oldVal = value;
          value = val;

          if(gaugeColor) {
            setGaugeColor(value, duration);
          }
          Animation({
            start: 50,
            end: value,
            duration: duration || 1,
            step: function(val, frame) {
              updateGauge(val, frame);
            }
          });
        },
        getValue: function() {
          return value;
        }
      };

      initializeGauge(gaugeContainer);
      instance.setValue(value);
      return instance;
    };
  })();

  return Gauge;
});

  </script>
   </head>
   <body>
  <div class="display">
                    <div id="gauge2" class="gauge-container two" style="display:inline-block; min-height:100px;min-width:100px;float: left;width: 100%; height: 100%;padding-left: 300px;overflow: hidden"></div>
         </div>

      <script>
         var pad = function(tar) {}

         var gauge2 = Gauge(
           document.getElementById("gauge2"),
         {
             min: -100,
             max: 100,
             dialStartAngle: 180,
             dialEndAngle: 0,
             value: 50,
             viewBox: "0 0 100 57",
             color: function(value) {
               if(value > 80) {
                 return "#5ee432";
               }else if(value > 60) {
                 return "#fffa50";
               }else if(value < 40) {
                 return "#f7aa38";
               }else {
                 return "#ef4655";
               }
             }
           }
         );

         (function loop() {

           gauge2.setValueAnimated(100, 3);
         })();
      </script>
   </body>
</html>
</code>```

The page is in:
http://booksandreviews.ml/?p=29

What to change in the code so in the wordpress site the size will also change?

I tried changing the style everywhere.

Body:
I'm trying to insert a gauge into a wordpress site.
The gauge is a js object, which show a scrolling bar.

When I set style values of the element locally, the size of the guage changes.

When I set it in wordpress site, the size of the element stays the same(very small)

The full code is:

<!DOCTYPE html>

The page is in:
http://booksandreviews.ml/?p=29

What to change in the code so in the wordpress site the size will also change?

I tried changing the style everywhere.


问:
AAPT: error: resource android:attr/lStar not found. :- react-native project I spend almost one week on these issue
[enter image description here](https://i.stack.imgur.com/wRkmw.png)

almost tired with all possible solution i.e. available on stack overflow

like:- -compilesdkversion-29.0.3
- buildtoolversion-31
-minisdkversion-21
-targetSdkversion-31

```<code>/    implementation 'androidx.core:core-ktx:1.3.2'
//    implementation 'androidx.appcompat:appcompat:1.2.0'
   implementation 'androidx.multidex:multidex:2.0.1'
    implementation "androidx.core:core-ktx:1.6.0"
    implementation "androidx.core:core:1.6.0"
</code>```

all these dependencies with different versions

Body:
[enter image description here](https://i.stack.imgur.com/wRkmw.png)

almost tired with all possible solution i.e. available on stack overflow

like:- -compilesdkversion-29.0.3
- buildtoolversion-31
-minisdkversion-21
-targetSdkversion-31

/    implementation 'androidx.core:core-ktx:1.3.2'
//    implementation 'androidx.appcompat:appcompat:1.2.0'
   implementation 'androidx.multidex:multidex:2.0.1'
    implementation "androidx.core:core-ktx:1.6.0"
    implementation "androidx.core:core:1.6.0"

all these dependencies with different versions


问:
How to show every LayoutAnchorable objects that are children of a LayoutAnchorablePane by default
I'm creating LayoutAnchorable dynamically in code and making them a child of a LayoutAnchorablePane. The one I add as a last child is being shown but the other ones is hidden and looks like they are tabbed. How can I show them both by default like they are stacked ?</p>
```<code>LayoutAnchorable layoutAnchorable = new LayoutAnchorable
{
    Content = listBox,
    Title = child1,
    ContentId = _selectedSchema.Key,
    IsActive = true,
    IsSelected = true,
    CanFloat = true,
    CanAutoHide = false,
    CanClose = true,
    CanHide = false,
};

//layoutAnchorable.DockWidth = new GridLength(200, GridUnitType.Pixel);

if (!panelXml.Children.Select(x => x.ContentId).Contains(layoutAnchorable.ContentId))
{
    panelXml.Children.Add(layoutAnchorable);
}
</code>```

Body:
I'm creating LayoutAnchorable dynamically in code and making them a child of a LayoutAnchorablePane. The one I add as a last child is being shown but the other ones is hidden and looks like they are tabbed. How can I show them both by default like they are stacked ?

LayoutAnchorable layoutAnchorable = new LayoutAnchorable
{
    Content = listBox,
    Title = child1,
    ContentId = _selectedSchema.Key,
    IsActive = true,
    IsSelected = true,
    CanFloat = true,
    CanAutoHide = false,
    CanClose = true,
    CanHide = false,
};

//layoutAnchorable.DockWidth = new GridLength(200, GridUnitType.Pixel);

if (!panelXml.Children.Select(x => x.ContentId).Contains(layoutAnchorable.ContentId))
{
    panelXml.Children.Add(layoutAnchorable);
}


问:
Remove MKPointAnnotation 3D effect (make flat colour)
I am trying to remove the 3D effect on an MKPointAnnotation.

This is my marker with the 3D effect (or shadow)

This is a flat colour marker (picture from the internet)

I assume that you can change this somewhere in this function, which I have been able to successfully change the color of the marker

```<code>func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
    let annotationView = MKMarkerAnnotationView(annotation: annotation, reuseIdentifier: "MyMarker")
    annotationView.markerTintColor = UIColor.blue
    return annotationView
}
</code>```

Does anyone know how to make the colour flat and remove the 3D effect?

Body:
I am trying to remove the 3D effect on an MKPointAnnotation.

This is my marker with the 3D effect (or shadow)

This is a flat colour marker (picture from the internet)

I assume that you can change this somewhere in this function, which I have been able to successfully change the color of the marker

func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
    let annotationView = MKMarkerAnnotationView(annotation: annotation, reuseIdentifier: "MyMarker")
    annotationView.markerTintColor = UIColor.blue
    return annotationView
}

Does anyone know how to make the colour flat and remove the 3D effect?


问:
Rolling Beta Estimation using fama-french factors
I needed help with this function to obtain coefficients for all the predictors. The function i used  is just giving one coefficient.

```<code>estimate_capm <- function(data, min_obs = 1) {
  if (nrow(data) < min_obs) {
    beta <- as.numeric(NA)

  } else {
    fit <- lm(excess_returns ~ mkt_excess + hml + smb , data = data)
    # note that we take into account the coefficient of mkt_excess
    beta <- as.numeric(coefficients(fit)[2])

  }
  return(beta)
}

# rolling capm estimation
roll_capm_estimation <- function(data, months, min_obs) {
  data <- data |>
    arrange(date)

  betas <- slide_period_vec(
    .x = data,
    .i = data$date,
    .period = "month",
    .f = ~ estimate_capm(., min_obs),
    .before = months - 1,
    .complete = FALSE
  )

  return(tibble(
    month = unique(data$date),
    beta = betas

  ))
}
</code>```

So i was trying change the slide_period_vec by other functions but it doesnt work as the error is it is a vector. So how to modify the rolling_capm_estimation function to get all the coefficients , rather than one the first one as in the code as.numeric(coefficients(fit)[2])

Body:
I needed help with this function to obtain coefficients for all the predictors. The function i used  is just giving one coefficient.

estimate_capm <- function(data, min_obs = 1) {
  if (nrow(data) < min_obs) {
    beta <- as.numeric(NA)

  } else {
    fit <- lm(excess_returns ~ mkt_excess + hml + smb , data = data)
    # note that we take into account the coefficient of mkt_excess
    beta <- as.numeric(coefficients(fit)[2])

  }
  return(beta)
}

# rolling capm estimation
roll_capm_estimation <- function(data, months, min_obs) {
  data <- data |>
    arrange(date)

  betas <- slide_period_vec(
    .x = data,
    .i = data$date,
    .period = "month",
    .f = ~ estimate_capm(., min_obs),
    .before = months - 1,
    .complete = FALSE
  )

  return(tibble(
    month = unique(data$date),
    beta = betas

  ))
}

So i was trying change the slide_period_vec by other functions but it doesnt work as the error is it is a vector. So how to modify the rolling_capm_estimation function to get all the coefficients , rather than one the first one as in the code as.numeric(coefficients(fit)[2])


问:
Highlight audio gap
I am developing a feature to help users to highlight silences in an audio file, so I want to detect start time silent in audio files. I am developing it using ReactJs and wavesurfer-js library. I want to ask if it is possible for this library to assist me in implementing this feature. How can this library help me to detect when the wave has a lot of straight line (i.e. too much silence), so I can know when to start silent in audio.

I've tried to check the docs if there is any function i can call or any property i can access on the WaveSurfer object but couldn't find any.

I want to detect start time silent in audio files. Could you tell me the way of doing this, please? thank you so much

Title: Highlight audio gap


问:
tinymce sets display: none on element
I've used a tinymce editor inside a tabbed display:
tinymce editor inside tabbed display
after switching tabs (which toggles the parent div's display to none).
the editor disappear:
editor disappeared
I check and some code (not mine) set the textarea element inline style to display: hidden, and when I toggle it off. the editor is uninitialized and lost it's content.
element style
after disabling the display none, the editor reverts to it's original content and no editor is initialised

I expected when switching between tabs, the editor will remain with all it's contents and just become visible again,
how can I stop the editor for loosing it's state and interactivity?

Title: tinymce sets display: none on element


问:
How do I make custom vscode keybind work multiple presses in a row without repressing modifier key?
I've rebound the workbench.action.navigateBack to '§' + 1, and workbench.action.navigateForward to '§' + 2. The § key is a great modifier on nordic keyboard layouts.

However, while pressing and holding '§', pressing 1 or 2 more than once automatically makes me edit text instead of stepping forward or back multiple times.

I have been trying to google/search for existing questions about this issue, and found nothing.

Is it possible to make a modifier key actuate and hold and keep its function against the specified keybinding combination?

I have tried rebinding to different modifier keys, and looked for different "actions" in the keybind list to see if there is a difference.


问:
all child nodes of ServiceManager
When I checked the source code of some of the dictionary extensions, I found that ServiceManager node is followed by other nodes like Dictionaries, GrammerCheckers etc. in .xcu file like dictionaries.xcu

```<code> <node oor:name="ServiceManager">
    <node oor:name="Dictionaries">
</code>```

Or something like this...

```<code> <node oor:name="ServiceManager">
    <node oor:name="GrammarCheckers">
</code>```

Where will I get the list of all child nodes of ServiceManager ?

Title: all child nodes of ServiceManager

Body:
When I checked the source code of some of the dictionary extensions, I found that ServiceManager node is followed by other nodes like Dictionaries, GrammerCheckers etc. in .xcu file like dictionaries.xcu

 <node oor:name="ServiceManager">
    <node oor:name="Dictionaries">

Or something like this...

 <node oor:name="ServiceManager">
    <node oor:name="GrammarCheckers">

Where will I get the list of all child nodes of ServiceManager ?


问:
how to increment a counter value only one of getting last value of a bluetooth serial data
i'm working on a bluetooth serial app and device send data continously i want to increment a counter value by 1 of getting last data of received how can i do this

void bluetoothDataListener( ) async {

```<code>try {

  BluetoothConnection connection = await BluetoothConnection.toAddress(widget.deviceAddress);
  print('Connected to the device form listenToBluetooth method');

  connection.input!.listen((Uint8List data) {
    conn = connection;
    setState(() {
      connection.output.add(data);
    });
    if(ascii.decode(data).contains("out of vein") ){
   setState((){
     modal.controller.checkVein = ascii.decode(data).toString();
     modal.controller.dotsShowHide();
     modal.controller.attempt++;
     // if(modal.controller.attempt == 5){
     //     scoreBasedOnCondition(0);
     // }
     modal.controller.update();
     });
    }
    else if(ascii.decode(data).contains("in vein")){
      setState((){
        modal.controller.checkVein = ascii.decode(data).toString();
        modal.controller.dotsShowHide();
        modal.controller.attempt++;

        Future.delayed(const Duration(seconds: 1), () {
          scoreBasedOnCondition(
              modal.controller.attempt==1?modal.controller.ivPoints = 5:
              modal.controller.attempt==2?modal.controller.ivPoints = 4:
              modal.controller.attempt==3?modal.controller.ivPoints = 3:
              modal.controller.attempt==4?modal.controller.ivPoints = 2:
              modal.controller.attempt==5?modal.controller.ivPoints = 1:
              0
          );

        });

        modal.controller.update();

      });

    }

  }).onDone(() {
    print('Disconnected by remote request from listenToBluetooth');

  });
}
catch (exception) {

  print("exeeppp   $exception");
}
</code>```

}

receiving the bluetooth serial data=> I/flutter (28538): out of vein
I/flutter (28538): out of vein
I/flutter (28538): out of vein
I/flutter (28538): out of vein
I/flutter (28538): out of vein
I/flutter (28538): out of vein
I/flutter (28538): out of vein
I/flutter (28538): out of vein

Body:
i'm working on a bluetooth serial app and device send data continously i want to increment a counter value by 1 of getting last data of received how can i do this

void bluetoothDataListener( ) async {

try {

  BluetoothConnection connection = await BluetoothConnection.toAddress(widget.deviceAddress);
  print('Connected to the device form listenToBluetooth method');

  connection.input!.listen((Uint8List data) {
    conn = connection;
    setState(() {
      connection.output.add(data);
    });
    if(ascii.decode(data).contains("out of vein") ){
   setState((){
     modal.controller.checkVein = ascii.decode(data).toString();
     modal.controller.dotsShowHide();
     modal.controller.attempt++;
     // if(modal.controller.attempt == 5){
     //     scoreBasedOnCondition(0);
     // }
     modal.controller.update();
     });
    }
    else if(ascii.decode(data).contains("in vein")){
      setState((){
        modal.controller.checkVein = ascii.decode(data).toString();
        modal.controller.dotsShowHide();
        modal.controller.attempt++;

        Future.delayed(const Duration(seconds: 1), () {
          scoreBasedOnCondition(
              modal.controller.attempt==1?modal.controller.ivPoints = 5:
              modal.controller.attempt==2?modal.controller.ivPoints = 4:
              modal.controller.attempt==3?modal.controller.ivPoints = 3:
              modal.controller.attempt==4?modal.controller.ivPoints = 2:
              modal.controller.attempt==5?modal.controller.ivPoints = 1:
              0
          );

        });

        modal.controller.update();

      });

    }

  }).onDone(() {
    print('Disconnected by remote request from listenToBluetooth');

  });
}
catch (exception) {

  print("exeeppp   $exception");
}

}

receiving the bluetooth serial data=> I/flutter (28538): out of vein
I/flutter (28538): out of vein
I/flutter (28538): out of vein
I/flutter (28538): out of vein
I/flutter (28538): out of vein
I/flutter (28538): out of vein
I/flutter (28538): out of vein
I/flutter (28538): out of vein


问:
Combining two items by Drag&Drop with React
I have a list of components and the list should have

```<code>display:flex;
flex-wrap: wrap;
</code>```

css properties.
I don't want to let the user change the sorts of the list. So the items doesn't have to be sortable. What I want is combining two items by using drag and drop. By combining them I mean merging two items and show the user the contents of the both items after combining them.

I have used react-beautiful-dnd. But I have two problems with this library.
1- This library doesn't support the wrapped lists. So the user experience is very bad while you are trying to drag one item and drop on another item. Because of the wrap property all the items are always moving around and it is so hard to find the right spot for dropping the item.
2- This library doesn't allow to combine the items without the sortable setup. So you need to give the user the ability of sorting the list if you want to give him the ability of combining items.

I have searched a solution for these problems but it seems that I can't achieve my goal here with react-beautiful-dnd library. Even it will be much more harder for me, I can also try to solve the problem with only React, without using any external library. So the solution way is not really matter.

If the only way to solve the problem is letting the user to sort the list, I am also okay with this.

My app is very similar to this one https://codesandbox.io/s/6b3m5
. If you make the list of this app row-direction and flex-wrap:wrap;, you will experience my problem.

If you need further information, I will provide immediately.

Body:
I have a list of components and the list should have

display:flex;
flex-wrap: wrap;

css properties.
I don't want to let the user change the sorts of the list. So the items doesn't have to be sortable. What I want is combining two items by using drag and drop. By combining them I mean merging two items and show the user the contents of the both items after combining them.

I have used react-beautiful-dnd. But I have two problems with this library.
1- This library doesn't support the wrapped lists. So the user experience is very bad while you are trying to drag one item and drop on another item. Because of the wrap property all the items are always moving around and it is so hard to find the right spot for dropping the item.
2- This library doesn't allow to combine the items without the sortable setup. So you need to give the user the ability of sorting the list if you want to give him the ability of combining items.

I have searched a solution for these problems but it seems that I can't achieve my goal here with react-beautiful-dnd library. Even it will be much more harder for me, I can also try to solve the problem with only React, without using any external library. So the solution way is not really matter.

If the only way to solve the problem is letting the user to sort the list, I am also okay with this.

My app is very similar to this one https://codesandbox.io/s/6b3m5
. If you make the list of this app row-direction and flex-wrap:wrap;, you will experience my problem.

If you need further information, I will provide immediately.


问:
Electron.js tools to handle installation and updating the games
There is so many game launchers that is done using Electron.
Is there any existing solutions that handles instalation updating and verification of game installation for electron. Maybe some best practices, boilerplates, how it should be done in the right way?</p>


问:
How to call jsonnet files on a windows mchine
I want to run jsonnet files (For Grafana) on my windows machine, but i dont know exactly what I need for it. I have installed vscode and git bash, but i dont know which command to use to run a file and then get it on my localhost for Grafana. Could someone help please?

grafonnet repo:
For example, I want to run  dashboard.libsonnet.

For that I have installed Jsonnet NG in VScode, it also says( If you don't add the jsonnet executable to the PATH then you will need to customize jsonnet.executablePath in your settings.json, so that the extension knows where to find it.) which i dont quite understand. I have added the file directory of jsonnet to my windows system path(env variables), but I dont know what else I need to do to get it work?


问:
Set PATH environment variable for my app but not to dependent Qt dlls and other dlls
I create a Qt app. It uses Qt dlls and also libusb dll and openssl dlls. And I use Qt Installer Framework and with windeployqt I bundle all these dlls in the same folder as my app. So when it's extracted on the user's system it all works well as the dlls are right next to the app exe so the dlls are discovered correctly.

Now I want to add my app.exe to PATH environment variable. I can do it with the Qt Installer Framework. But the problem is that the dlls that come with my app will be now exposed to PATH too. And it does not look good. How do people normally solve the problem?

Maybe, it's bad to add/remove my app to/from PATH on installation/deinstallation? However, I've checked out that e.g. CMake's and Python's installers do modify the PATH, though it looks like they do it using Wix toolset or something like this, while I use Qt Installer Framework: JavaScript where I specify Powershell commands to get executed.


问:
Flutter App - Google Analytics 4 conversions reported via Firebase are missing in Google Ads
We have a new ecommerce application built on Flutter

We use Firebase for tracking and it seems to work fine. We see all ecommerce events and we built an audience for Google Ads campaign and the events are attributed to this audience.

However, when we go to conversions section to Google Ads we see a very small number of events coming from Google Ads.

Talking to Google Ads support, they say that our events are unattributed.

Have you had this issue before? What would you recommend to fix this?

Thank you for your help?

We checked all setups on Google Ads / Firebase / Google Analytics and we would expect to see conversions showing up on Google Ads


问:
How to optimize the performance of a `pandas` `DataFrame` using `numexpr` and `Dask`?
I'm working with a large pandas DataFrame and I'm trying to optimize its performance using the numexpr and Dask libraries. I've tried using the numexpr.evaluate() function to perform element-wise operations on the DataFrame, but it's still taking a long time to run.

Here's an example of the code I'm using:

```<code>import numexpr
import pandas as pd

df = pd.read_csv('large_data.csv')

# Perform element-wise operation using numexpr
df['new_column'] = numexpr.evaluate('df.column1 + df.column2')
</code>```

Is there a way to further optimize the performance of this code using Dask or some other method?

Body:
I'm working with a large pandas DataFrame and I'm trying to optimize its performance using the numexpr and Dask libraries. I've tried using the numexpr.evaluate() function to perform element-wise operations on the DataFrame, but it's still taking a long time to run.

Here's an example of the code I'm using:

import numexpr
import pandas as pd

df = pd.read_csv('large_data.csv')

# Perform element-wise operation using numexpr
df['new_column'] = numexpr.evaluate('df.column1 + df.column2')

Is there a way to further optimize the performance of this code using Dask or some other method?


问:
Developer error in Sign in with google with firebase in android studio
Promise rejection error](https://i.stack.imgur.com/XKpa2.png)

I have tried clean project and rebuild project. This project is also run in ios device. I also add a SHA key in firebase console.


问:
Facing issue to Build and deploy backbase custom authenticator
I am working on backbase identity version 2022-08-LTS. Trying to use custom authenticator using link but when i execute the command java -cp ../custom-authenticator/target/custom-authenticator-2022.08-LTS-jar-with-dependencies.jar:backbase-identity-1.10.6.1-cr.0.jar io.quarkus.runner.GeneratedMain from backbase-identity module then got error Error: Could not find or load main class io.quarkus.runner.GeneratedMain Caused by: java.lang.ClassNotFoundException: io.quarkus.runner.GeneratedMain  can any one help me on it


问:
Why is the log statement in Spring WebClient subscribe() block not invoked?
I am playing around with the spring webclient to send emails via an api. The mails get send, however I am trying to do this without blocking and I want to log the successful response (or error). As I understood it so far, I could do this in the subscribe block. However, I do not manage to get the logging (or anything else) within the subscribe block to work.

MailClient.kt

```<code>fun sendMail(mail: Mail): Mono<String> {
        return getWebClient()
        .post()
        .uri("uri")
        .contentType(MediaType.APPLICATION_JSON)
        .bodyValue(..)
        .retrieve()
        .bodyToMono(String::class.java)
        //.timeout(Duration.ofSeconds(10))
    }
</code>```

Service function which uses MailClient:

```<code>       logger.info("Sending mail due to failure with id = ${failure.id}, error: $errorMessage")
        mailClient.sendMail(
            Mail(..)
        )
            .subscribe(
                { response -> logger.info("success: $response") },
                { error -> logger.error("error: $error") })
</code>```

Body:
I am playing around with the spring webclient to send emails via an api. The mails get send, however I am trying to do this without blocking and I want to log the successful response (or error). As I understood it so far, I could do this in the subscribe block. However, I do not manage to get the logging (or anything else) within the subscribe block to work.

MailClient.kt

fun sendMail(mail: Mail): Mono<String> {
        return getWebClient()
        .post()
        .uri("uri")
        .contentType(MediaType.APPLICATION_JSON)
        .bodyValue(..)
        .retrieve()
        .bodyToMono(String::class.java)
        //.timeout(Duration.ofSeconds(10))
    }

Service function which uses MailClient:

       logger.info("Sending mail due to failure with id = ${failure.id}, error: $errorMessage")
        mailClient.sendMail(
            Mail(..)
        )
            .subscribe(
                { response -> logger.info("success: $response") },
                { error -> logger.error("error: $error") })


问:
Hibernate : alias getting automatically updated ( javax.persistence.criteria.Selection.alias(String name))
My Table  Name : PO_details  :- Root<PO_details>

Column Name

PO_number

PO_discr

PO_customer

Please find below = Hibernate/ JPA

```<code> Expression Po_1 = PO_details.get(PO_number);
    Po_1.alias("SELECT");

    Expression Po_2 = PO_details.get(PO_number);
    Po_2.alias("GROUP");

    criteriaQuery.multiselect(Po_1 );
    criteriaQuery.groupBy(Po_2);
</code>```

Error
Multi-select expressions defined duplicate alias : GROUP

Observation :
Somehow Po_1 alias is getting updated with Po_2 alias .

I need both Po_1 (SELECT) and Po_2(GROUP) in the query with their respected alias

Please help me

Body:
My Table  Name : PO_details  :- Root<PO_details>

Column Name

PO_number

PO_discr

PO_customer

Please find below = Hibernate/ JPA

 Expression Po_1 = PO_details.get(PO_number);
    Po_1.alias("SELECT");

    Expression Po_2 = PO_details.get(PO_number);
    Po_2.alias("GROUP");

    criteriaQuery.multiselect(Po_1 );
    criteriaQuery.groupBy(Po_2);

Error
Multi-select expressions defined duplicate alias : GROUP

Observation :
Somehow Po_1 alias is getting updated with Po_2 alias .

I need both Po_1 (SELECT) and Po_2(GROUP) in the query with their respected alias

Please help me


问:
How to add QSplineSeries to QAreaSeries?
I want to add an area series to my chart, but I want it to be smooth, as a spline series is.

I tried to add it like I would add a line series, however the line is not smooth at all, as if I added a regular QLineSeries.


问:
Linq group by with multiple columns for the outer and then 1 other column for the inner group
Lets say I have a list of class Car. It has properties Id, Model, Year, Age,CarCode. A carCode is unique for a model but is not for all  models.

I want to group by Model and Year together and then group that grouping by Age and then for each Agegroup in each model and year group send Model, Age, and listCarCodes to a method which will update a db table with those CarCodes.

What I want

```<code>var carModelYearGroupList=GroupBy CarLIst(Model, Year)
var carAgeGL= groupBy carModelYearGroupList(key.Age)

Parallel.ForEach(carModelYearGroupList, new ParallelOptions { MaxDegreeOfParallelism = 10 }, (car) =>
{
    Parallel.ForEach(carAgeGL, new ParallelOptions { MaxDegreeOfParallelism = 10 }, (ca) =>
    {
        UpdateDb(Model m, Age a, List<string> carCodes);
    });
});
</code>```

What I tried

```<code> var consolidatedChildren =
    from c in bla
    group c by new
    {

        c.sreSif,
        c.sreSerija,
    } into gcs
    from g in gcs
    group g by new
    {
     g.sreIsplatio
    } into gcse
     select new
     {
         srecka= gcs.Key.sreSif,
         serija = gcs.Key.sreSerija,
         opBroj = gcse.Key.sreIsplatio,
         sreckeTemp = gcse.ToList(),
     };

            foreach (var c in consolidatedChildren)
            {
               foreach (var isp in c.sreckeTemp)
               {

                   List<string>IsplatniBrojevi= new List<string>();
                   IsplatniBrojevi.Add(isp.sreIspBroj);
               }
            }
</code>```

However I don't see gcs in these lines

```<code>select new
{
    srecka= gcs.Key.sreSif,
    serija = gcs.Key.sreSerija,
</code>```

Appreciate any help.

Body:
Lets say I have a list of class Car. It has properties Id, Model, Year, Age,CarCode. A carCode is unique for a model but is not for all  models.

I want to group by Model and Year together and then group that grouping by Age and then for each Agegroup in each model and year group send Model, Age, and listCarCodes to a method which will update a db table with those CarCodes.

What I want

var carModelYearGroupList=GroupBy CarLIst(Model, Year)
var carAgeGL= groupBy carModelYearGroupList(key.Age)

Parallel.ForEach(carModelYearGroupList, new ParallelOptions { MaxDegreeOfParallelism = 10 }, (car) =>
{
    Parallel.ForEach(carAgeGL, new ParallelOptions { MaxDegreeOfParallelism = 10 }, (ca) =>
    {
        UpdateDb(Model m, Age a, List<string> carCodes);
    });
});

What I tried

 var consolidatedChildren =
    from c in bla
    group c by new
    {

        c.sreSif,
        c.sreSerija,
    } into gcs
    from g in gcs
    group g by new
    {
     g.sreIsplatio
    } into gcse
     select new
     {
         srecka= gcs.Key.sreSif,
         serija = gcs.Key.sreSerija,
         opBroj = gcse.Key.sreIsplatio,
         sreckeTemp = gcse.ToList(),
     };

            foreach (var c in consolidatedChildren)
            {
               foreach (var isp in c.sreckeTemp)
               {

                   List<string>IsplatniBrojevi= new List<string>();
                   IsplatniBrojevi.Add(isp.sreIspBroj);
               }
            }

However I don't see gcs in these lines

select new
{
    srecka= gcs.Key.sreSif,
    serija = gcs.Key.sreSerija,

Appreciate any help.


问:
A question about XStream framework transformations empty tags
When the age property is empty, XStream converts to. How to convert it to？

I've tried turning null values into label output, but the format is not what I want. Please help me


问:
Setting a new system_tray_menu causes on_system_tray_event handler to no longer be called on MacOS
I'm using Tauri to build a MacOS tray bar app.

I set a menu during build as described in docs here.

Then later in a #[tauri::command] from front-end I set a a new menu but after doing so the on_system_tray_event handler is no longer called.

I tried updating the menu like this, this caused the events to no longer fire.

#[tauri::command]
fn set_system_tray_menu(app: AppHandle) {

    let menu = SystemTrayMenu::new()
      .add_item(CustomMenuItem::new("test".to_string(), "Test"));

    match app.tray_handle().set_menu(menu) {
      Ok(_) => {},
      Err(error) => panic!("Problem setting system tray menu: {}", error),
    };

}
```
<p>I tried to replace the entire system tray but that causes the app to crash on right click. See error below code snippet.</p>
<pre class="lang-rust prettyprint-override"><code>#[tauri::command]
fn set_system_tray_menu(app: AppHandle) {

    let menu = SystemTrayMenu::new()
      .add_item(CustomMenuItem::new("test".to_string(), "Test"));

    match SystemTray::new().with_menu(menu).build(&app) {
      Ok(_) => {},
      Err(error) => panic!("Problem setting system tray menu: {}", error),
    };

}

/*
2022-12-15 14:59:48.060 hotlist-tauri[49478:21361707] -[_WKInspectorConfiguration _setMenuOwner:]: unrecognized selector sent to instance 0x13e7ecdd0
thread 'main' panicked at 'Uncaught exception <NSException: 0x13e709a30>', /Users/rikschennink/.cargo/registry/src/github.com-1ecc6299db9ec823/cocoa-0.24.1/src/appkit.rs:3740:9
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
*/
</code>```

Does anyone know how I can keep the original event handlers or how I can assign new ones after replacing the system tray?

I've also submitted this as an issue but after doing so I realised that this might be caused by my own incompetence so Stack Overflow is probably a better location for it.

Body:
I'm using Tauri to build a MacOS tray bar app.

I set a menu during build as described in docs here.

Then later in a #[tauri::command] from front-end I set a a new menu but after doing so the on_system_tray_event handler is no longer called.

I tried updating the menu like this, this caused the events to no longer fire.

#[tauri::command]
fn set_system_tray_menu(app: AppHandle) {

    let menu = SystemTrayMenu::new()
      .add_item(CustomMenuItem::new("test".to_string(), "Test"));

    match app.tray_handle().set_menu(menu) {
      Ok(_) => {},
      Err(error) => panic!("Problem setting system tray menu: {}", error),
    };

}

I tried to replace the entire system tray but that causes the app to crash on right click. See error below code snippet.

#[tauri::command]
fn set_system_tray_menu(app: AppHandle) {

    let menu = SystemTrayMenu::new()
      .add_item(CustomMenuItem::new("test".to_string(), "Test"));

    match SystemTray::new().with_menu(menu).build(&app) {
      Ok(_) => {},
      Err(error) => panic!("Problem setting system tray menu: {}", error),
    };

}

/*
2022-12-15 14:59:48.060 hotlist-tauri[49478:21361707] -[_WKInspectorConfiguration _setMenuOwner:]: unrecognized selector sent to instance 0x13e7ecdd0
thread 'main' panicked at 'Uncaught exception <NSException: 0x13e709a30>', /Users/rikschennink/.cargo/registry/src/github.com-1ecc6299db9ec823/cocoa-0.24.1/src/appkit.rs:3740:9
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
*/

Does anyone know how I can keep the original event handlers or how I can assign new ones after replacing the system tray?

I've also submitted this as an issue but after doing so I realised that this might be caused by my own incompetence so Stack Overflow is probably a better location for it.


问:
How do I edit a wordpress page?
I am in here, I want to edit or add more content, but when I go to Pages > All Pages and the page I want, I cannot see any of these, how can I edit it then?

I browsed through many of the options on the sidebar, couldn't find anything helpful

Title: How do I edit a wordpress page?


问:
What is difference between factory and factoryboy package?
I am new to the factoryboy package i want to use this for unit testing of my django app, previously i used factory package,

i want to know the exact difference between this 2 package becuase syntax and structure is almost same in both package


问:
Subset Sum Problem NFA: How can I go about implementing this problem using an NFA
I have been trying to figure out how to code the following program using an NFA, (I have been at it for a week and yet to make progress on implementing correctly, currently have an inefficient bruteforce solution that takes a very long time without an NFA and was wondering if there would be some guidance on here to figure out the implementation of this problem)

The Problem in regards to being solved by an NFA goes as follows, , given an integer N and a subset D ⊆ {0, 1, … , 9} of digits, if N can be written as a sum of two integers X and Y that use only digits in D. For example, consider N = 130500633 and D = {1, 2, 8}. Since 130500633 = 128218812 + 2281821, the answer is yes. For a given D, define L(D) as the set of integers N that can be written as X + Y where X and Y use only digits in D. Build an NFA M for L(D), and implement a membership algorithm to test if N is in L(M). Assuming that the input can up to 100 digits long.


问:
Global json object in java
Is there any way to declare global json object in Java?

```<code>public class Constants {
    public static JSONObject jsonObject = new JSONObject();
    static {
        jsonObject.put("name","Raju");
        jsonObject.put("age",21);
    }
}

</code>```

Other than this, is there any other way to declare it?

Title: Global json object in java

Body:
Is there any way to declare global json object in Java?

public class Constants {
    public static JSONObject jsonObject = new JSONObject();
    static {
        jsonObject.put("name","Raju");
        jsonObject.put("age",21);
    }
}

Other than this, is there any other way to declare it?


问:
ACF get nested group from another ID
I'm testing the possibility to work totally with ACF re-structuring the acutal way of data handling.

Actualy if one size is changed I need to change 3 different pages.

Desired structure:

Custom Post Type with all ACF related to that product

datasheet page (group)

general datas

Datasheet list (group)

group datas

product page (group)

Some data

some data

main page data (group)

some datas

The datasheet and product page has a relational acf field related to the costum post type

What's my problem now:

I can get the costum post type ID from the datasheet page

```<code>$my_costum_post_type_id = get_field('id_costum_type');
$datasheet = get_field_objects($my_costum_post_type_id[0]->ID);
</code>```

Now I have the structure of the Datasheet Page (group), But I don't know how acces to the Datasheet list (group) loop trought it, any solutions? (is my first time with acf)

I need to retrive labels and values of the nested group.

Title: ACF get nested group from another ID

Body:
I'm testing the possibility to work totally with ACF re-structuring the acutal way of data handling.

Actualy if one size is changed I need to change 3 different pages.

Desired structure:

Custom Post Type with all ACF related to that product

datasheet page (group)

general datas

Datasheet list (group)

group datas

product page (group)

Some data

some data

main page data (group)

some datas

The datasheet and product page has a relational acf field related to the costum post type

What's my problem now:

I can get the costum post type ID from the datasheet page

$my_costum_post_type_id = get_field('id_costum_type');
$datasheet = get_field_objects($my_costum_post_type_id[0]->ID);

Now I have the structure of the Datasheet Page (group), But I don't know how acces to the Datasheet list (group) loop trought it, any solutions? (is my first time with acf)

I need to retrive labels and values of the nested group.


问:
Understanding of possible server logic and what's information client send with request from python
I wrote scrapper on python3.10.6 using aiohttp for https://www.tektorg.ru/rosneft/procedures. First time i didn't put any headers to requests and ~7 days everything worked fine, server sent all data in html document. One day server was starting send me html which contains only javascript in body (deleted long line after function md5cycle(e, t)...):

<!DOCTYPE html>

  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <meta http-equiv="refresh" content="10;URL=/ciez2a">

```
</div>
</div>
</p>
<p>I was thinking to coding process of parsing some random values from this script and generate cookies (using python), but i haven't enough understanding of javascript to do that.</p>
<p>After that i tried set headers. I cleared cache for this website, because noticed that if i clear cache, server send cookies in response headers.</p>
<p>I'm using google-chrome <em>usually</em>, so i copied request as curl and paste to https://curlconverter.com/python/</p>
<h1>Google Chrome</h1>
```headers = {
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
    'Accept-Language': 'ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7',
    'Connection': 'keep-alive',
    'Sec-Fetch-Dest': 'document',
    'Sec-Fetch-Mode': 'navigate',
    'Sec-Fetch-Site': 'none',
    'Sec-Fetch-User': '?1',
    'Upgrade-Insecure-Requests': '1',
    'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36',
    'sec-ch-ua': '"Not?A_Brand";v="8", "Chromium";v="108", "Google Chrome";v="108"',
    'sec-ch-ua-mobile': '?0',
    'sec-ch-ua-platform': '"Linux"',
}
```
<p><em>Didn't help, server still sent html with only javascript like above</em></p>
<p>then i decided to copied request headers using Firefox</p>
<h1>Mozilla Firefox</h1>
```headers = {
    'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:108.0) Gecko/20100101 Firefox/108.0',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8',
    'Accept-Language': 'ru-RU,ru;q=0.8,en-US;q=0.5,en;q=0.3',
    # 'Accept-Encoding': 'gzip, deflate, br',
    'Connection': 'keep-alive',
    # 'Cookie': 'Drupal.visitor.procedures_theme=blocks; SSESS8aa208d9665c28bb20b7c818a7f80de5=IY3CXhnSy7i4pUuAL9JkFvJ9OpGqzULRiCLCa2kghAY; session-cookie=17313c260ac7a80d75c675b0b4b53d1198b2bb0bd6601c145313d4cad4cf3e8d5e2951f05d86572b226d24a654bdf7b3; rerf=AAAAAGOcOt9yonIKAwq3Ag==; ipp_uid=1671183070814/X1giSSXARW9OQgKm/qQjE0XbuCnz5mfVq+oMwyw==; ipp_key=v1671183070814/v33947245ba5adc7a72e273/fpUTdIq6j3nF8PdhDbVoog==; _ga_69E4MLGLTE=GS1.1.1671183073.1.0.1671183073.0.0.0; _ga_MBKDKGVXSM=GS1.1.1671182986.6.1.1671183073.0.0.0; _ga=GA1.2.525105367.1671183073; _gid=GA1.2.752529341.1671183074; _gat_gtag_UA_61681149_1=1; _gat_gtag_UA_41780421_1=1; _ym_uid=1671183074893893721; _ym_d=1671183074; _ym_isad=2',
    'Upgrade-Insecure-Requests': '1',
    'Sec-Fetch-Dest': 'document',
    'Sec-Fetch-Mode': 'navigate',
    'Sec-Fetch-Site': 'none',
    'Sec-Fetch-User': '?1',
}
```

Idk why curlconverter commenting Accept-Encoding. If it commented, server send javascript. Otherwise, server send html with data

At this point happy me copied new script to machine with windows10. (I used Ubuntu before), launched and saw that server sent html without data.

I know that header User-Agent identify user OS and device, so i opened google-chrome on windows machine and copied 'User-Agent' to script. It was not working... Even if i copy all headers.

Then i opened Firefox on windows machine, copied 'User-Agent' and it started working...

I was thinking that, if i'm sending request to server using requests or aiohttp, server can understand my platform and OS only in headers. In other word, if i set User-Agent on windows like linux has, server will identify my OS like linux.

Questions: why server decline same request on different OS? Is aiohttp sending some info in request, but not in headers? Or may be it's unusual behavior especially of this website which store which OS used by this ip address?

Body:
I wrote scrapper on python3.10.6 using aiohttp for https://www.tektorg.ru/rosneft/procedures. First time i didn't put any headers to requests and ~7 days everything worked fine, server sent all data in html document. One day server was starting send me html which contains only javascript in body (deleted long line after function md5cycle(e, t)...):

<!DOCTYPE html>

  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <meta http-equiv="refresh" content="10;URL=/ciez2a">

I was thinking to coding process of parsing some random values from this script and generate cookies (using python), but i haven't enough understanding of javascript to do that.

After that i tried set headers. I cleared cache for this website, because noticed that if i clear cache, server send cookies in response headers.

I'm using google-chrome usually, so i copied request as curl and paste to https://curlconverter.com/python/

Google Chrome

headers = {
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
    'Accept-Language': 'ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7',
    'Connection': 'keep-alive',
    'Sec-Fetch-Dest': 'document',
    'Sec-Fetch-Mode': 'navigate',
    'Sec-Fetch-Site': 'none',
    'Sec-Fetch-User': '?1',
    'Upgrade-Insecure-Requests': '1',
    'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36',
    'sec-ch-ua': '"Not?A_Brand";v="8", "Chromium";v="108", "Google Chrome";v="108"',
    'sec-ch-ua-mobile': '?0',
    'sec-ch-ua-platform': '"Linux"',
}

Didn't help, server still sent html with only javascript like above

then i decided to copied request headers using Firefox

Mozilla Firefox

headers = {
    'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:108.0) Gecko/20100101 Firefox/108.0',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8',
    'Accept-Language': 'ru-RU,ru;q=0.8,en-US;q=0.5,en;q=0.3',
    # 'Accept-Encoding': 'gzip, deflate, br',
    'Connection': 'keep-alive',
    # 'Cookie': 'Drupal.visitor.procedures_theme=blocks; SSESS8aa208d9665c28bb20b7c818a7f80de5=IY3CXhnSy7i4pUuAL9JkFvJ9OpGqzULRiCLCa2kghAY; session-cookie=17313c260ac7a80d75c675b0b4b53d1198b2bb0bd6601c145313d4cad4cf3e8d5e2951f05d86572b226d24a654bdf7b3; rerf=AAAAAGOcOt9yonIKAwq3Ag==; ipp_uid=1671183070814/X1giSSXARW9OQgKm/qQjE0XbuCnz5mfVq+oMwyw==; ipp_key=v1671183070814/v33947245ba5adc7a72e273/fpUTdIq6j3nF8PdhDbVoog==; _ga_69E4MLGLTE=GS1.1.1671183073.1.0.1671183073.0.0.0; _ga_MBKDKGVXSM=GS1.1.1671182986.6.1.1671183073.0.0.0; _ga=GA1.2.525105367.1671183073; _gid=GA1.2.752529341.1671183074; _gat_gtag_UA_61681149_1=1; _gat_gtag_UA_41780421_1=1; _ym_uid=1671183074893893721; _ym_d=1671183074; _ym_isad=2',
    'Upgrade-Insecure-Requests': '1',
    'Sec-Fetch-Dest': 'document',
    'Sec-Fetch-Mode': 'navigate',
    'Sec-Fetch-Site': 'none',
    'Sec-Fetch-User': '?1',
}

Idk why curlconverter commenting Accept-Encoding. If it commented, server send javascript. Otherwise, server send html with data

At this point happy me copied new script to machine with windows10. (I used Ubuntu before), launched and saw that server sent html without data.

I know that header User-Agent identify user OS and device, so i opened google-chrome on windows machine and copied 'User-Agent' to script. It was not working... Even if i copy all headers.

Then i opened Firefox on windows machine, copied 'User-Agent' and it started working...

I was thinking that, if i'm sending request to server using requests or aiohttp, server can understand my platform and OS only in headers. In other word, if i set User-Agent on windows like linux has, server will identify my OS like linux.

Questions: why server decline same request on different OS? Is aiohttp sending some info in request, but not in headers? Or may be it's unusual behavior especially of this website which store which OS used by this ip address?


问:
Is it a good practice to wrap everything in useMemo/useCallback to avoid accidental reruns of useEffect?
My previous approach was to just skip functions from the dependency arrays, which was showing the warning that it's missing from it, but it was intentional from my side.

I've seen another approach where just for security, and to avoid getting lost in which has been memoized, and which hasn't, we wrap everything in useCallback/useMemo, and writing every dependency into the dependency array.

Which approach is right, and why?

There are a lot of cases where this dilemma applies, for example an onSubmit coming from the parent, passed as prop to the child, and the child has a useEffect like:

```<code>const [count, setCount] = useState(0);

useEffect(() => {
  onSubmit(count);
}, [
  count,
  // should onSubmit be here, or not? - it may trigger this every time this rerenders
])
</code>```

But I wouldn't like to limit this question purely to the above example, it's a generic question.

Body:
My previous approach was to just skip functions from the dependency arrays, which was showing the warning that it's missing from it, but it was intentional from my side.

I've seen another approach where just for security, and to avoid getting lost in which has been memoized, and which hasn't, we wrap everything in useCallback/useMemo, and writing every dependency into the dependency array.

Which approach is right, and why?

There are a lot of cases where this dilemma applies, for example an onSubmit coming from the parent, passed as prop to the child, and the child has a useEffect like:

const [count, setCount] = useState(0);

useEffect(() => {
  onSubmit(count);
}, [
  count,
  // should onSubmit be here, or not? - it may trigger this every time this rerenders
])

But I wouldn't like to limit this question purely to the above example, it's a generic question.


问:
How to perform REST operations through a controller and JSP page?
This is a spring boot application, with JPA, JSP and MVC.

If I click the link in the below JSP, it is redirecting to the controller and then the controller is directing to the getAllItem method which goes to the Service. But, I get the below error:

There was an unexpected error (type=Internal Server Error, status=500).
Cannot invoke "com.sportyshoes.basepackage.service.ShoeService.findAll()" because "this.shoeService" is null

but the REST is performing and the data is showing up in an application called Advanced REST client like Postman, but I am not able to retrieve the data through the controller. Please could anyone give your feedback on how to retrieve the data from database.

my JSP is:

View all items

My controller code as below:

```<code>@Controller
public class WareHouseController {

    private ShoeService shoeService;

    @RequestMapping(value="/getallitem", method=RequestMethod.GET)
    public String getAllItem() {
        List allShoes =  shoeService.findAll();
        System.out.println(allShoes);
        return "warehouse";
    }
}
</code>```

my Service is:

```<code>public interface ShoeService {

    public List<ShoeData> findAll();
//  public ShoeData findByItemName(String shoename);
    public ShoeData insertData(ShoeData shoeData);
    public ShoeData deleteById(long theId);
    public ShoeData findById(long theId);
}
</code>```

Body:
This is a spring boot application, with JPA, JSP and MVC.

If I click the link in the below JSP, it is redirecting to the controller and then the controller is directing to the getAllItem method which goes to the Service. But, I get the below error:

There was an unexpected error (type=Internal Server Error, status=500).
Cannot invoke "com.sportyshoes.basepackage.service.ShoeService.findAll()" because "this.shoeService" is null

but the REST is performing and the data is showing up in an application called Advanced REST client like Postman, but I am not able to retrieve the data through the controller. Please could anyone give your feedback on how to retrieve the data from database.

my JSP is:

View all items

My controller code as below:

@Controller
public class WareHouseController {

    private ShoeService shoeService;

    @RequestMapping(value="/getallitem", method=RequestMethod.GET)
    public String getAllItem() {
        List allShoes =  shoeService.findAll();
        System.out.println(allShoes);
        return "warehouse";
    }
}

my Service is:

public interface ShoeService {

    public List<ShoeData> findAll();
//  public ShoeData findByItemName(String shoename);
    public ShoeData insertData(ShoeData shoeData);
    public ShoeData deleteById(long theId);
    public ShoeData findById(long theId);
}


问:
java.lang.NoSuchFieldError: ENDPOINT_PROVIDER at software.amazon.awssdk.services.iottwinmaker.DefaultIoTTwinMakerBaseClientBuilde
I am trying to create a TwimMakerCleint in java, I am using the maven dependency as follows

```<code><!-- https://mvnrepository.com/artifact/software.amazon.awssdk/iottwinmaker -->
    <dependency>
        <groupId>software.amazon.awssdk</groupId>
        <artifactId>iottwinmaker</artifactId>
        <version>2.18.39</version>
    </dependency>
</code>```

and the snippet to create the connection is

```<code>IoTTwinMakerClient awsIoTTwinMaker = IoTTwinMakerClient.create();
</code>```

while executing the above line getting the following exception

Body:
I am trying to create a TwimMakerCleint in java, I am using the maven dependency as follows

    <dependency>
        <groupId>software.amazon.awssdk</groupId>
        <artifactId>iottwinmaker</artifactId>
        <version>2.18.39</version>
    </dependency>

and the snippet to create the connection is

IoTTwinMakerClient awsIoTTwinMaker = IoTTwinMakerClient.create();

while executing the above line getting the following exception


问:
Http failure response Spring Boot Angular
i  ran into the problem while making the crud application. i can add the records and view the records and delete the records while i update the records records not updated i got the problem on  ** Failed to load resource: net::ERR_FAILED** ** 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.**

what i tried so i attached below.on the update part of the application

CustomerController

```<code>`@RestController
@CrossOrigin("http://localhost:4200/")

@RequestMapping("api/v1/customer")
public class CustomerController
{
    @Autowired
    private CustomerService customerService;

@PostMapping(path = "/update")
public String updateCustomer(@RequestBody CustomerUpdateDTO customerUpdateDTO)
{
    String id = customerService.updateCustomers(customerUpdateDTO);
    return id;
}

}}`

</code>```

CustomerService

String updateCustomers(CustomerUpdateDTO customerUpdateDTO);
`

CustomerServiceIMPL

```<code>`@Override
public String updateCustomers(CustomerUpdateDTO customerUpdateDTO)
{
    if (customerRepo.existsById(customerUpdateDTO.getCustomerid())) {
        Customer customer = customerRepo.getById(customerUpdateDTO.getCustomerid());

        customer.setCustomername(customerUpdateDTO.getCustomername());
        customer.setCustomeraddress(customerUpdateDTO.getCustomeraddress());
        customer.setMobile(customerUpdateDTO.getMobile());
        customerRepo.save(customer);
    }
        else
        {
            System.out.println("Customer ID do not Exist");
        }

            return null;
    }

</code>```

CustomerRepo

```<code>`@EnableJpaRepositories
@Repository
public interface CustomerRepo extends JpaRepository<Customer,Integer> {
}
</code>```

Customer

```<code>``@Entity
@Table(name = "customer")
public class Customer {
    @Id
    @Column(name = "customer_id", length = 50)
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int customerid;

    @Column(name = "customer_name", length = 50)
    private String customername;

    @Column(name = "customer_address", length = 60)
    private String customeraddress;

    @Column(name = "mobile", length = 12)
    private int mobile;

    public Customer(int customerid, String customername, String customeraddress, int mobile) {
        this.customerid = customerid;
        this.customername = customername;
        this.customeraddress = customeraddress;
        this.mobile = mobile;
    }

    public Customer() {
    }

    public Customer(String customername, String customeraddress, int mobile) {
        this.customername = customername;
        this.customeraddress = customeraddress;
        this.mobile = mobile;
    }

    public int getCustomerid() {
        return customerid;
    }

    public void setCustomerid(int customerid) {
        this.customerid = customerid;
    }

    public String getCustomername() {
        return customername;
    }

    public void setCustomername(String customername) {
        this.customername = customername;
    }

    public String getCustomeraddress() {
        return customeraddress;
    }

    public void setCustomeraddress(String customeraddress) {
        this.customeraddress = customeraddress;
    }

    public int getMobile() {
        return mobile;
    }

    public void setMobile(int mobile) {
        this.mobile = mobile;
    }

    @Override
    public String toString() {
        return "Customer{" +
                "customerid=" + customerid +
                ", customername='" + customername + '\'' +
                ", customeraddress='" + customeraddress + '\'' +
                ", mobile=" + mobile +
                '}';
    }
</code>```

CustomerUpdateDTO

```<code>``package com.Project.SpringAngular.DTO;

public class CustomerUpdateDTO {
    private int customerid;
    private String customername;
    private String customeraddress;
    private int mobile;

    public CustomerUpdateDTO(int customerid, String customername, String customeraddress, int mobile) {
        this.customerid = customerid;
        this.customername = customername;
        this.customeraddress = customeraddress;
        this.mobile = mobile;
    }

    public CustomerUpdateDTO() {
    }

    public int getCustomerid() {
        return customerid;
    }

    public void setCustomerid(int customerid) {
        this.customerid = customerid;
    }

    public String getCustomername() {
        return customername;
    }

    public void setCustomername(String customername) {
        this.customername = customername;
    }

    public String getCustomeraddress() {
        return customeraddress;
    }

    public void setCustomeraddress(String customeraddress) {
        this.customeraddress = customeraddress;
    }

    public int getMobile() {
        return mobile;
    }

    public void setMobile(int mobile) {
        this.mobile = mobile;
    }

    @Override
    public String toString() {
        return "CustomerDTO{" +
                "customerid=" + customerid +
                ", customername='" + customername + '\'' +
                ", customeraddress='" + customeraddress + '\'' +
                ", mobile=" + mobile +
                '}';
    }
}`
`
</code>```

Angular

```<code>setUpdate(data: any)
  {
   this.customername = data.customername;
   this.customeraddress = data.customeraddress;
   this.mobile = data.mobile;
   this.currentCustomerID = data.customerid;
  }

  UpdateRecords()
  {
    let bodyData = {
      "customername" : this.customername,
      "customeraddress" : this.customeraddress,
      "mobile" : this.mobile
    };

    this.http.post("http://localhost:8084/api/v1/customer/update"+ "/"+ this.currentCustomerID,bodyData,{responseType: 'text'}).subscribe((resultData: any)=>
    {
        console.log(resultData);
        alert("Employee Registered Updateddd")
        this.getAllCustomer();
        this.customername = '';
        this.customeraddress = '';
        this.mobile  = 0;

    });
  }
</code>```

Body:
i  ran into the problem while making the crud application. i can add the records and view the records and delete the records while i update the records records not updated i got the problem on  ** Failed to load resource: net::ERR_FAILED** ** 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.**

what i tried so i attached below.on the update part of the application

CustomerController

`@RestController
@CrossOrigin("http://localhost:4200/")

@RequestMapping("api/v1/customer")
public class CustomerController
{
    @Autowired
    private CustomerService customerService;

@PostMapping(path = "/update")
public String updateCustomer(@RequestBody CustomerUpdateDTO customerUpdateDTO)
{
    String id = customerService.updateCustomers(customerUpdateDTO);
    return id;
}

}}`

CustomerService

String updateCustomers(CustomerUpdateDTO customerUpdateDTO);
`

CustomerServiceIMPL

`@Override
public String updateCustomers(CustomerUpdateDTO customerUpdateDTO)
{
    if (customerRepo.existsById(customerUpdateDTO.getCustomerid())) {
        Customer customer = customerRepo.getById(customerUpdateDTO.getCustomerid());

        customer.setCustomername(customerUpdateDTO.getCustomername());
        customer.setCustomeraddress(customerUpdateDTO.getCustomeraddress());
        customer.setMobile(customerUpdateDTO.getMobile());
        customerRepo.save(customer);
    }
        else
        {
            System.out.println("Customer ID do not Exist");
        }

            return null;
    }

CustomerRepo

`@EnableJpaRepositories
@Repository
public interface CustomerRepo extends JpaRepository<Customer,Integer> {
}

Customer

``@Entity
@Table(name = "customer")
public class Customer {
    @Id
    @Column(name = "customer_id", length = 50)
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int customerid;

    @Column(name = "customer_name", length = 50)
    private String customername;

    @Column(name = "customer_address", length = 60)
    private String customeraddress;

    @Column(name = "mobile", length = 12)
    private int mobile;

    public Customer(int customerid, String customername, String customeraddress, int mobile) {
        this.customerid = customerid;
        this.customername = customername;
        this.customeraddress = customeraddress;
        this.mobile = mobile;
    }

    public Customer() {
    }

    public Customer(String customername, String customeraddress, int mobile) {
        this.customername = customername;
        this.customeraddress = customeraddress;
        this.mobile = mobile;
    }

    public int getCustomerid() {
        return customerid;
    }

    public void setCustomerid(int customerid) {
        this.customerid = customerid;
    }

    public String getCustomername() {
        return customername;
    }

    public void setCustomername(String customername) {
        this.customername = customername;
    }

    public String getCustomeraddress() {
        return customeraddress;
    }

    public void setCustomeraddress(String customeraddress) {
        this.customeraddress = customeraddress;
    }

    public int getMobile() {
        return mobile;
    }

    public void setMobile(int mobile) {
        this.mobile = mobile;
    }

    @Override
    public String toString() {
        return "Customer{" +
                "customerid=" + customerid +
                ", customername='" + customername + '\'' +
                ", customeraddress='" + customeraddress + '\'' +
                ", mobile=" + mobile +
                '}';
    }

CustomerUpdateDTO

``package com.Project.SpringAngular.DTO;

public class CustomerUpdateDTO {
    private int customerid;
    private String customername;
    private String customeraddress;
    private int mobile;

    public CustomerUpdateDTO(int customerid, String customername, String customeraddress, int mobile) {
        this.customerid = customerid;
        this.customername = customername;
        this.customeraddress = customeraddress;
        this.mobile = mobile;
    }

    public CustomerUpdateDTO() {
    }

    public int getCustomerid() {
        return customerid;
    }

    public void setCustomerid(int customerid) {
        this.customerid = customerid;
    }

    public String getCustomername() {
        return customername;
    }

    public void setCustomername(String customername) {
        this.customername = customername;
    }

    public String getCustomeraddress() {
        return customeraddress;
    }

    public void setCustomeraddress(String customeraddress) {
        this.customeraddress = customeraddress;
    }

    public int getMobile() {
        return mobile;
    }

    public void setMobile(int mobile) {
        this.mobile = mobile;
    }

    @Override
    public String toString() {
        return "CustomerDTO{" +
                "customerid=" + customerid +
                ", customername='" + customername + '\'' +
                ", customeraddress='" + customeraddress + '\'' +
                ", mobile=" + mobile +
                '}';
    }
}`
`

Angular

setUpdate(data: any)
  {
   this.customername = data.customername;
   this.customeraddress = data.customeraddress;
   this.mobile = data.mobile;
   this.currentCustomerID = data.customerid;
  }

  UpdateRecords()
  {
    let bodyData = {
      "customername" : this.customername,
      "customeraddress" : this.customeraddress,
      "mobile" : this.mobile
    };

    this.http.post("http://localhost:8084/api/v1/customer/update"+ "/"+ this.currentCustomerID,bodyData,{responseType: 'text'}).subscribe((resultData: any)=>
    {
        console.log(resultData);
        alert("Employee Registered Updateddd")
        this.getAllCustomer();
        this.customername = '';
        this.customeraddress = '';
        this.mobile  = 0;

    });
  }


问:
Is there a way to test Aspnet's data contract validation when calling the endpoint, without making it an integration test?
I'd like to write the data contract validation tests in the same test surroundings as the endpoint test. Is it even possible?

The way I do it now, is to validate my DataContracts in one set of tests,

and then rely on these tests being complete when testing the Endpoint.

Doing it like this is arguably correct, but editor wise the tests are in different projects and hence harder to discover.

I know how to navigate the solution; but what about the ones following me?

Test:

```<code>[TestData(differenct_kinds_of_MyDataContract_data)]
public void MyEndpoint_Should_validate_input(input){
   var sut = new MyController();

   // Act.
   // A clean unit test. No Invoke, no startup of Aspnet.
   // But I still want the aspnet validation to trigger...
    var res = await sut.MyEndpoint(input);

   // Assert
   res.Should.BeOfType<400BadRequest>()
}
</code>```

Data contract:

```<code>[DataContract]
public class MyDataContract
{
  [DataMember]
  [Required]
  public string MyProp{ get; set; }
}
</code>```

Endpoint:

```<code>public class MyController  : ControllerBase
{
  public async Task<IActionResult> MyEndpoint(MyDataContract myDataContract)
  {
   ...
  }
}
</code>```

Body:
I'd like to write the data contract validation tests in the same test surroundings as the endpoint test. Is it even possible?

The way I do it now, is to validate my DataContracts in one set of tests,

and then rely on these tests being complete when testing the Endpoint.

Doing it like this is arguably correct, but editor wise the tests are in different projects and hence harder to discover.

I know how to navigate the solution; but what about the ones following me?

Test:

[TestData(differenct_kinds_of_MyDataContract_data)]
public void MyEndpoint_Should_validate_input(input){
   var sut = new MyController();

   // Act.
   // A clean unit test. No Invoke, no startup of Aspnet.
   // But I still want the aspnet validation to trigger...
    var res = await sut.MyEndpoint(input);

   // Assert
   res.Should.BeOfType<400BadRequest>()
}

Data contract:

[DataContract]
public class MyDataContract
{
  [DataMember]
  [Required]
  public string MyProp{ get; set; }
}

Endpoint:

public class MyController  : ControllerBase
{
  public async Task<IActionResult> MyEndpoint(MyDataContract myDataContract)
  {
   ...
  }
}


问:
Turn Based Random ActorNumber ID
Good day!

I have a chess game with PUN. My question is that whenever the one who creates the room first usually is the first to move (white player). And the one to join is the black player.

I was hoping that creating a room and joining would randomize who is white and black and not by the one who creates and joins.

`

```<code>myClientID = PhotonNetwork.LocalPlayer.ActorNumber;
myPlayer = PhotonNetwork.Instantiate("Player", Vector3.zero, Quaternion.identity);
myPlayer.GetComponent<Player>().myId = myClientID;
</code>```

`

that is the code above being used. It might not be the best practice. please help on how to have a randomize player id. Or if there is another best practice approach please let me know. Thank you in advance.

Title: Turn Based Random ActorNumber ID

Body:
Good day!

I have a chess game with PUN. My question is that whenever the one who creates the room first usually is the first to move (white player). And the one to join is the black player.

I was hoping that creating a room and joining would randomize who is white and black and not by the one who creates and joins.

`

myClientID = PhotonNetwork.LocalPlayer.ActorNumber;
myPlayer = PhotonNetwork.Instantiate("Player", Vector3.zero, Quaternion.identity);
myPlayer.GetComponent<Player>().myId = myClientID;

`

that is the code above being used. It might not be the best practice. please help on how to have a randomize player id. Or if there is another best practice approach please let me know. Thank you in advance.


问:
How to select columns that built on each other in SQL?
how can I read entries in SQL where the column entries build on each other.
In the first column is the material number. These again consist of different materials, with their own material number in the first column.

How can I find out e.g. from material 123 the quantity of all sub-materials.

I have loaded the data from an Exeltabbele into a Panda database and then loaded this into a SQL database.

Should  I use loops in python, to iterate over the table? Or is there a smarter way?


问:
How to use REST API with SSRS 2012?
How to use REST API with SSRS 2012 ?

Is it even possible ? I had dataset where I called a webservice with SOAP but I don't know how I could modify this for a new REST api.

With SOAP I had this:

```<code><Query>
    <Method Namespace="http://foo.fr/webservices/" Name= "getContractXml">
         <Parameters>
             <Parameter Name="codeContract">
                 <DefaultValue>752125</DefaultValue>
             </Parameter>
         </Parameters>
    </Method>
  <SoapAction>http://foo.fr/webservices/getContractXml</SoapAction></Query>
</code>```

How to change this to call a REST webservice, in https, with the same name and parameters?

Title: How to use REST API with SSRS 2012?

Body:
How to use REST API with SSRS 2012 ?

Is it even possible ? I had dataset where I called a webservice with SOAP but I don't know how I could modify this for a new REST api.

With SOAP I had this:

<Query>
    <Method Namespace="http://foo.fr/webservices/" Name= "getContractXml">
         <Parameters>
             <Parameter Name="codeContract">
                 <DefaultValue>752125</DefaultValue>
             </Parameter>
         </Parameters>
    </Method>
  <SoapAction>http://foo.fr/webservices/getContractXml</SoapAction></Query>

How to change this to call a REST webservice, in https, with the same name and parameters?


问:
Calculate proportion of users in a moving seven day window based on daily event counts
I have data reflecting the daily count of events related to users - it's structured roughly as
date, user, count.

The data is somewhat sparse in that some users have no events on a given day, some days have no events from any user, etc.

I'd like to generate data that reflects on a given day which users have had events on at least three days in the previous seven days.

I was thinking of creating a date range, using a window function of some sort, but find myself going around in circles a bit.


问:
How to set Padding for text in StaticLayout Android?
I want to set padding for text created using StaticLayout in Android

I can't set padding for text and text is cut off when using font and using alignment

example


问:
how to fix a double substring call?
in my homework I need to extract the server name from the url

at the same time, I need to take into account that there may not be a slash after the server name

I'm not allowed to use a loop

At the same time, I am once again trying to redo a remark from my teacher:

"Now substring can be done twice (if it goes into if). You need to make sure that only one substring is made for any variant of the function execution"

how can this be fixed? I've tried everything

```<code>public class Url {
    public static String getServerName(String url) {
        int index1 = url.indexOf("://") + 3;

        String serverName = url.substring(index1);

        int index2 = serverName.indexOf("/");

        if (index2 >= 0) {
            return url.substring(index1, index1 + index2);
        }

        return serverName;
    }

    public static void main(String[] args) {
        String url = "https://SomeServerName";

        System.out.println(getServerName(url));
    }
}
</code>```

Title: how to fix a double substring call?

Body:
in my homework I need to extract the server name from the url

at the same time, I need to take into account that there may not be a slash after the server name

I'm not allowed to use a loop

At the same time, I am once again trying to redo a remark from my teacher:

"Now substring can be done twice (if it goes into if). You need to make sure that only one substring is made for any variant of the function execution"

how can this be fixed? I've tried everything

public class Url {
    public static String getServerName(String url) {
        int index1 = url.indexOf("://") + 3;

        String serverName = url.substring(index1);

        int index2 = serverName.indexOf("/");

        if (index2 >= 0) {
            return url.substring(index1, index1 + index2);
        }

        return serverName;
    }

    public static void main(String[] args) {
        String url = "https://SomeServerName";

        System.out.println(getServerName(url));
    }
}


问:
venn diagram in javascript
```<code>    **here is the function of the union**

    function unionFunction(getarray = false) {
      // first we get the values
     var set1 = document.getElementById("myseta").value;
     var set2 = document.getElementById("mysetb").value;
     var set3 = document.getElementById("mysetc").value;
      // then we can simply make a new Set
      let union = new Set()
      // we get 3 arrays of each set by
      let arr1 = set1.split(',')
      let arr2 = set2.split(',')
      let arr3 = set3.split(',')

      // when we push same values in the set they won't work
      arr1.forEach((elem) => union.add(elem))
      arr2.forEach((elem) => union.add(elem))
      arr3.forEach((elem) => union.add(elem))

      // we print it
      if (getarray) {
        return Array.from(union);
      } else {
      document.getElementById("res").innerHTML =     Array.from(union).join(' , ');
    }
    }
</code>```

i want a function for venn diagram, where the results of union sets will display in the venn, i have no idea how..

Title: venn diagram in javascript

Body:
    **here is the function of the union**

    function unionFunction(getarray = false) {
      // first we get the values
     var set1 = document.getElementById("myseta").value;
     var set2 = document.getElementById("mysetb").value;
     var set3 = document.getElementById("mysetc").value;
      // then we can simply make a new Set
      let union = new Set()
      // we get 3 arrays of each set by
      let arr1 = set1.split(',')
      let arr2 = set2.split(',')
      let arr3 = set3.split(',')

      // when we push same values in the set they won't work
      arr1.forEach((elem) => union.add(elem))
      arr2.forEach((elem) => union.add(elem))
      arr3.forEach((elem) => union.add(elem))

      // we print it
      if (getarray) {
        return Array.from(union);
      } else {
      document.getElementById("res").innerHTML =     Array.from(union).join(' , ');
    }
    }

i want a function for venn diagram, where the results of union sets will display in the venn, i have no idea how..