text:
Q: How to say two dates are the same? I have a prompt that allows the user to input a date used to generate a report. The date is used to find records.

*

*date is on MM/DD/YY

*date is before MM/DD/YY

*date is after MM/DD/YY

*date is between MM/DD/YY and MM/DD/YY

My question is for the first prompt. The word on doesn't seem correct to me, and using the phrase is equal to sounds to technical.
What would be the best way to write "date is on MM/DD/YY".
NOTE: I can not remove the third word. So "date is MM/DD/YY" is not an option, because "on/before/after" are part of a drop down selection. See sample image below.

A: Forget about prepositions and use an adverb. "The date is exactly MM/DD/YY", for example.
As you say yourself, the best thing would be to just drop the word completely. "The date is X." GUIs should follow the rules of the language, not the other way round.
Oh, and also, the GUI doesn't actually say, "The date is...". It only says "is", and "published when" in the title. Meaning that you could also drop the is. Especially since it's poor practice to have all items of a list begin with the same word.

Published when

*

*[on/before/after] X

*between Y and Z

A: When is the report?
It's on July 1st 2013
In my opinion the preposition, on, works just fine.
EDIT: All too happy that Reg Dwight answered your question. I am not a "computer" expert.


text:
Q: visualization with pandas in python I have the following problem
I want to plot following table:

I want to compare the new_cases from germany and france per week how can i visualise this?
I already tried multiple plots but I'm not happy with the results:
for example:
pivot_df['France'].plot(kind='bar')
plt.figure(figsize=(15,5))
pivot_df['France'].plot(kind='bar')
plt.figure(figsize=(15,5))`

But it only shows me france

A: Here you go:
sample df:
   Country  week  new_cases
0   FRANCE     9        210
1  GERMANY     9        300
2   FRANCE    10        410
3  GERMANY    10        200
4   FRANCE    11        910
5  GERMANY     9        500

Code:
df.groupby(['week','Country'])['new_cases'].sum().unstack().plot.bar()
plt.ylabel('New cases')

Output:

A: I think you're trying to get a timeseries plot. For that you'll need to convert year_week to a datetime object. Subsequently you can groupby the country, and unstack and plot the timeseries:
import datetime
import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_csv('https://opendata.ecdc.europa.eu/covid19/testing/csv/data.csv')

df = df[df['country'].isin(['France', 'Germany'])]
df = df[df['level'] == 'national'].reset_index()

df['datetime'] = df['year_week'].apply(lambda x: datetime.datetime.strptime(x + '-1', '%G-W%V-%u')) #https://stackoverflow.com/a/54033252/11380795
df.set_index('datetime', inplace=True)

grouped_df = df.groupby('country').resample('1W').sum()['new_cases']
ax = grouped_df.unstack().T.plot(figsize=(10,5))
ax.ticklabel_format(style='plain', axis='y')

result:

redpajama_set_name: RedPajamaStackExchange


text:
Q: Do there exist Markov partitions with (nearly) uniform Riemannian measures? This question complements this one; the difference is in considering Riemannian versus SRB measures.
Let $M$ be a compact, finite-dimensional Riemannian manifold, let $T: M \rightarrow M$ be an Anosov diffeomorphism, and let $v$ be the normalized Riemannian measure. Write $\mathcal{R} = \{ R_1,\dots,R_n \}$ for a Markov partition; write $v_j^{(\mathcal{R})} := v(R_j)$.

Question:
Does there ever/always exist
  $\mathcal{R}$ s.t. $v^{(\mathcal{R})}$
  is a nontrivial uniform measure on
  $\{1,\dots,n\}$? If not, does there
  ever/always exist a sequence of
  partitions $\mathcal{R}_m$ s.t.
  $v^{(\mathcal{R}_m)}$ converges to a
  uniform measure in some nontrivial
  sense?

Of course, for hyperbolic toral automorphisms the two questions are equivalent. However I would guess that this question might be easier in general, since the classical construction of Markov partitions uses an open cover of $M$ by balls of fixed radius to form an initial (typically non-Markovian) partition that is subsequently perturbed iteratively into a Markov partition.


text:
Q: Getting AH02032 using TLSv1.2 despite identical SNI server name and Hostname, but SNI has the port number attached. No error in test env. with TLSv1.3 Getting the the error message below despite identical Hostnames. What I don't understand, why the Hostname provided via SNI has the port number attached even though, according to Hostname specification, the colon and port number is not listed as part of the Hostname definition and the OpenSSL SNI extension treats the server name as Hostname. Is this a parsing error in Apache (and Wireshark)?
A tcp dump from a Debian client viewed with Wireshark lists during client hello and TLSv1.2 under SNI extension:
Server Name Type: Host_Name (0) and
Server Name: MyHostname:443
While the client would allow TLSv1.3, TLSv1.2 seems to be mandated by the server during Client Hello.
The request is made using OpenSSL 3.07 cmp
Error Message:
AH02032: Hostname MyHostname:443 provided via SNI and Hostname MyHostname provided via HTTP have no compatible SSL setup uri="path"
I would expect that when the package is parsed by Apache/SNI, the server name is taken without port and compared with the host name in the http header and be recognized as identical.
In a similar, but not identical to production environment, when TLSv1.3 is used, the error is not occurring with otherwise identical client settings.
(I don't have access to the Apache server which is part of a web application firewall.)
Amendment:
cmd:
bin/openssl cmp -config etc/openssl.cnf -cmd ir -section cmp-init -ref [ref] -secret pass:[pass]-certout ssl/PKIstore/[store.pem] -newkey ssl/PKIstore/[new.key] -subject [SUBJECT DN] -implicit_confirm
openssl.cnf
[default]
[cmp]
[cmp-init]
prompt = no
recipient = [ca-dn]
path = [path]
tls_host = MyHostname
tls_used = yes
server = MyHostname:443
path = [default path]
trusted = [trusted.pem]
cacertsout = [capubs.pem]
Note: The values for server, tls_host, and tls_used are defined in a opensssl.cfg file.
After further investigating the packet:
Whatever is given as server = [value]
value ends up as Server Name in the server_name extension. And the length value includes the length of prefix https:// prefix or the port :443 if given as server value.  [prefix][server_value][:port]
If either prefix or suffix are used, the server name does not matches the server name in the host header. If only server is given, the request is send to the default port 80, even if tls_used is set to yes.
Since the SNI server Name Type is host_name, I would expect, that it should not contains the protocol prefix nor the port.

A: This looks like a bug in OpenSSL to me and I've filed it as such: https://github.com/openssl/openssl/issues/20031


text:
Q: Storing JSON as TEXT instead of JSONB in YugabyteDB [Question posted by a user on YugabyteDB Community Slack]
I have a column whose value is JSON string/json. What should be the preferred type of column JSONB or TEXT?
Does one or the other impact performance/ column size/ read-write time etc?
The value will always be retrieved as full and passed as a param without any computation.

A: In this exact case, you can store it as TEXT. This would save a little bit of CPU on INSERT because the string would have to be analyzed as valid JSON and converted to JSONB, which underneath is stored in BINARY format.
For all other cases where you may want to select a subset of the JSON object, or do computations over it, or have secondary indexes, you'll need to store it as JSONB.


text:
Q: Is there another way to connect JS to HTML? I want to make a collapsible directory list in HTML/CSS/JS, but it seems like it doesn't work (the collapsible part). Everything else is totally fine. Can you help me, please?
The code follows:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Title</title>

assets

css

typography.css

layout.css

modules.css

states.css

theme.css

A: You need to add a reference to jquery. Your own javascript seems to be referencing it.
you can add this link in your header tag

Or you can make the collapsible function with vanilla (plain) javascript:
https://codepen.io/sheelah/pen/EPEOBb
Or even CSS:
https://alligator.io/css/collapsible/


text:
Q: Прокрутка активности вниз На активности в TextView передается довольно большой объем текста. Когда его становится слишком много он уходит "вниз", но активность прокрутить вниз нельзя. Как сделать так, что бы можно было прокручивать вниз?

A: Вот так, как вариант:
<ScrollView
    android:id="@+id/ScrollView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:scrollbars="vertical"
    android:fillViewport="true">

    <TextView
        android:id="@+id/TextView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1.0"/>
</ScrollView>


text:
Q: Why is this non-static variable retaining its value through function calls? void testFunc(int);

int main(int argc, char** argv) {

    testFunc(1);
    testFunc(2);
    testFunc(3);

    return (EXIT_SUCCESS);
}

void testFunc(int another)
{
    int num;
    printf("num: %i\n", num);
    num = another;
}

output:
num: 127383283
num: 1
num: 2
If I am printing the variable before I assign it to something each time, shouldn't I always get garbage values without a static keyword?

A: You are getting garbage values - it just so happens that in this case those garbage values happen to be the value that you assigned in the previous invocation of the function.
If you call another function in between the calls to testFunc(), or compile with higher optimisation settings, or with a different compiler, you'll probably see something completely different.

A: Because it ends up using the same memory each time for that variable, which hasn't changed.
This behavior is considered undefined. Although it may work reliably in your particular case it is not to be relied on in all cases.
And why don't you start accepting some answers for hell's sake?

A: The value of num without initialization is Indeterminate.
It can be anything. You cannot rely on it to be anything specific.
Note that using this indeterminate value results in Undefined Behavior, So this program has Undefined behavior.

A: In C/C++, your automatic variables are not guaranteed to have any particular value unless you initialize them to value you want. So this is by design

A: It's an accident.  Add another function:
int use_stack(void)
{
    int a[4] = { rand(), rand(), rand(), rand() };
    int j = 0;
    for (int i = 0; i < 4; i++)
        j += a[i];
    return j;
}

Call it after the first two testFunc() calls.  You're likely to see a random value as the 'saved value' in testFunc().
Formally, the behaviour you are seeing is undefined behaviour and anything may happen.

A: Static just means that it can't change after compile time. Once you declare the value, it will remain that through the life of the code. It works the second and thirds times through since you are setting the value at the end of the function.
If you set it to static, you would not be able to assign the value to is in the function.


text:
Q: How to use 192.168.0.102 Virtual ip to connect remote mysql by cpanel this my php code
$con = mysqli_connect("212.1.212.1","******t","*****","bigcattl_formal") or die(mysql_error());
But have a problem . Access denied for mysql user 'bigcattl'
I can not connect mysql .
Thanks a lot.


text:
Q: Trying to use HttpWebRequest to load a page in a file I have a ASP.NET MVC app that works fine in the browser.
I am using the following code to be able to write the
html of a retrieved page to a file. (This is to use in a PDF conversion  component)
But this code errors out continually but not in the browser.
I get timeout errors sometimes asn 500 errors.
Public Function GetPage(ByVal url As String, ByVal filename As String) As Boolean

        Dim request As HttpWebRequest
        Dim username As String
        Dim password As String
        Dim docid As String
        Dim poststring As String
        Dim bytedata() As Byte
        Dim requestStream As Stream

        Try
            username = "pdfuser"
            password = "pdfuser"
            docid = "docid=inv12154"
            poststring = String.Format("username={0}&password={1}&{2}", username, password, docid)
            bytedata = Encoding.UTF8.GetBytes(poststring)

            request = WebRequest.Create(url)
            request.Method = "Post"
            request.ContentLength = bytedata.Length
            request.ContentType = "application/x-www-form-urlencoded"
            requestStream = request.GetRequestStream()
            requestStream.Write(bytedata, 0, bytedata.Length)
            requestStream.Close()
            request.Timeout = 60000

            Dim response As HttpWebResponse
            Dim responseStream As Stream
            Dim reader As StreamReader
            Dim sb As New StringBuilder()
            Dim line As String = String.Empty

            response = request.GetResponse()
            responseStream = response.GetResponseStream()

            reader = New StreamReader(responseStream, System.Text.Encoding.ASCII)

            line = reader.ReadLine()
            While (Not line Is Nothing)
                sb.Append(line)
                line = reader.ReadLine()
            End While

            File.WriteAllText(filename, sb.ToString())

        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
        Return True

    End Function

A: I would recommend you simplifying your code and disposing disposable resources such as streams and stream readers. You could also use WebClient:
Using client = New WebClient()
    Dim values = New NameValueCollection()
    values.Add("username", "pdfuser")
    values.Add("password", "pdfuser")
    values.Add("docid", "inv12154")
    Dim result = client.UploadValues(url, values)
    File.WriteAllBytes(filename, result)
End Using


text:
Q: In AngularJS, what's the difference between ng-pristine and ng-dirty? What are the differences between ng-pristine and ng-dirty? It seems you can have both to be true:
$scope.myForm.$pristine = true; // after editing the form

A: pristine tells us if a field is still virgin, and dirty tells us if the user has already typed anything in the related field:

<form ng-app="" name="myForm">
  <input name="email" ng-model="data.email">

    Email is virgine.

    E-mail is dirty

</form>

A field that has registred a single keydown event is no more virgin (no more  pristine) and is therefore dirty for ever.

A: Both directives obviously serve the same purpose, and though it seems that the decision of the angular team to include both interfere with the DRY principle and adds to the payload of the page, it still is rather practical to have them both around. It is easier to style your input elements as you have both .ng-pristine and .ng-dirty available for styling in your css files. I guess this was the primary reason for adding both directives.

A: The ng-dirty class tells you that the form has been modified by the user, whereas the ng-pristine class tells you that the form has not been modified by the user. So ng-dirty and ng-pristine are two sides of the same story.
The classes are set on any field, while the form has two properties, $dirty and $pristine.
You can use the $scope.form.$setPristine() function to reset a form to pristine state (please note that this is an AngularJS 1.1.x feature).
If you want a $scope.form.$setPristine()-ish behavior even in 1.0.x branch of AngularJS, you need to roll your own solution (some pretty good ones can be found here). Basically, this means iterating over all form fields and setting their $dirty flag to false.

A: As already stated in earlier answers, ng-pristine is for indicating that the field has not been modified, whereas ng-dirty is for telling it has been modified. Why need both?
Let's say we've got a form with phone and e-mail address among the fields. Either phone or e-mail is required, and you also have to notify the user when they've got invalid data in each field. This can be accomplished by using ng-dirty and ng-pristine together:
<form name="myForm">
    <input name="email" ng-model="data.email" ng-required="!data.phone">

Phone or e-mail required

        E-mail is invalid

    <input name="phone" ng-model="data.phone" ng-required="!data.email">

Phone or e-mail required

        Phone is invalid

</form>

A: ng-pristine ($pristine)
Boolean True if the form/input has not been used yet (not modified by the user)
ng-dirty ($dirty)
Boolean True if the form/input has been used (modified by the user)

$setDirty();
Sets the form to a dirty state.
This method can be called to add the 'ng-dirty' class and set the form to a dirty state (ng-dirty class). This method will propagate current state to parent forms.
$setPristine();
Sets the form to its pristine state.
This method sets the form's $pristine state to true, the $dirty state to false, removes the ng-dirty class and adds the ng-pristine class. Additionally, it sets the $submitted state to false.
This method will also propagate to all the controls contained in this form.
Setting a form back to a pristine state is often useful when we want to 'reuse' a form after saving or resetting it.


text:
Q: Turn Off SCSS Auto-Completion I want SCSS syntax highlighting but with normal Sublime Text 2 completion rules. I.e. Sublime only auto-completes things I've already typed.
Annoyingly, not only does the SCSS plug-in auto-complete to things I haven't typed, it doesn't auto-complete to things I have typed.
As an example, you can see it excluding the previously typed include from the auto-completion list:

A: You can fix this by removing scss_completions.py and scss_completions.pyc from the SCSS package folder.


text:
Q: Spark: Different results of different uses of map for the same purpose I want to test the order in which the data is executed in RRD, so I write two versions of the code as below.
def main(args: Array[String]): Unit = {
    val sparkConf: SparkConf = new SparkConf().setMaster("local[*]").setAppName("OperatorPara")
    val sc = new SparkContext(sparkConf)

    val rdd: RDD[Int] = sc.makeRDD(List(1, 2, 3, 4, 5, 6, 7, 8, 9), 4)

    // version 1
    val rdd2: RDD[Int] = rdd.map { x: Int =>
      println(s">>> $x")
      x
    }
    val rdd3: RDD[Int] = rdd2.map { x: Int =>
      println(s"### $x")
      x
    }
    rdd3.collect()

    // version 2
    rdd.map((x: Int) => {println(s"+++ $x");x}).map((x:Int) => {println(s"--- $x"); x}).collect()
    sc.stop()
  }

And the result is like:
(version 1)
>>> 7
>>> 5
### 7
>>> 1
>>> 3
### 1
>>> 8
### 5
### 8
>>> 2
### 2
### 3
>>> 9
>>> 6
### 9
>>> 4
### 6
### 4

(version 2)
+++ 7
+++ 3
--- 3
+++ 4
--- 4
--- 7
+++ 8
--- 8
+++ 9
--- 9
+++ 5
--- 5
+++ 1
--- 1
+++ 2
--- 2
+++ 6
--- 6

According to the results, I found that the code of version 1 preferred to execute two maps separately, while the code of version 2 preferred to execute two maps continuously.
I tried several times and the results didn't make much difference.
My environment configuration is scala 2.11.12, spark 2.3.2 and hadoop-3.2.2.
I wonder if there is any potential difference in the execution of the two versions of code, or is it just a coincidence. Thanks a lot!

A: You have to consider that Spark distributes the operation across your cores. When you create a RDD from a collection using makeRDD function or parallelize without specifying the number of partitions, Spark will create a DAG to process the RDD, and depending on the number of cores several tasks will be executed in parallel. So, the output  that you obtain is not determinist. If you set:
setMaster("local[1]")

You will see the data in order because only one partition is created. Check it out to see the difference.


text:
Q: Adding datalabels - matplotlib barchart I have a pandas DataFrameGroupBy object that I am ploting like so...
grouped.sum().plot(kind='bar')

which gives...

but I would like something more like this...

I just want to know how to add data labels to each column and possibly a table as well?

A: To add value labels on top of the bar plot, you can loop through the columns in each index and use text to show the values, something like this:
df = DataFrame(rand(3,2), columns=['A', 'B'])
ax = df.plot(table=True, kind='bar', title='Random')
for i, each in enumerate(df.index):
    for col in df.columns:
        y = df.ix[each][col]
        ax.text(i, y, y)

You may want to adjust the text labels coords to have a better alignment etc.

To show the grid table, pandas has table support from 0.14+.
You can read more about Plotting table HERE

Plotting with matplotlib table is now supported in DataFrame.plot()
  and Series.plot() with a table keyword. The table keyword can accept
  bool, DataFrame or Series. The simple way to draw a table is to
  specify table=True. Data will be transposed to meet matplotlib's
  default layout.

fig, ax = plt.subplots(1, 1)
df = DataFrame(rand(5, 3), columns=['a', 'b', 'c'])
ax.get_xaxis().set_visible(False)   # Hide Ticks
df.plot(table=True, ax=ax)

Also, you can pass different DataFrame or Series for table keyword.
  The data will be drawn as displayed in print method (not transposed
  automatically). If required, it should be transposed manually as below
  example.

fig, ax = plt.subplots(1, 1)
ax.get_xaxis().set_visible(False)   # Hide Ticks
df.plot(table=np.round(df.T, 2), ax=ax)


text:
Q: C++ Custom class inhereting Eigen initializer list I am trying to make a custom Vector3 inheriting from Eigen's vector 3 like so.

using Vector3 = Eigen::Vector3d;

enum class CustomEnum
{
    E1, E2 E3, E4,
};

class CustomVector3 : public Vector3
{
public:
    // Taken from here: https://eigen.tuxfamily.org/dox/TopicCustomizing_InheritingMatrix.html
    CustomVector3():Vector3(){}

    template<typename OtherDerived>
    CustomVector3(const Eigen::MatrixBase<OtherDerived>& other) : Vector3(other) {}

    // Initializer Constructor
    template<typename OtherDerived>
    CustomVector3(const std::initializer_list<OtherDerived>& other) : Vector3(other) {}

    template<typename OtherDerived>
    CustomVector3& operator=(const Eigen::MatrixBase<OtherDerived>& other){
        this->Vector3::operator=(other);
        return *this;
    }

    CustomEnum e = CustomEnum::E1;
};

And the goal is to do the following:

TEST_CASE("Initalizer List Test")
{
    CustomVector3 vec = {1.1, 2.2, 3.3};
    CHECK(vec.x() == 1.1);
    CHECK(vec.y() == 2.2);
    CHECK(vec.z() == 3.3);
    assert(vec.frame == CustomEnum::E1);
}

Without the initializer constructor, I am able to do the following, but not my goal mentioned above:
Vector3 data = {1.1, 2.2, 3.3};
CustomVector3 framedData = data;

With the initializer constructor, I get the following compile error message (I called it FramedVector3 in my code, but for clarity I called it CustomVector3 in this post):
/usr/include/eigen3/Eigen/src/Core/Matrix.h: In instantiation of 'Eigen::Matrix<_Scalar, _Rows, _Cols, _Options, _MaxRows, _MaxCols>::Matrix(const T&) [with T = std::initializer_list<double>; _Scalar = double; int _Rows = 3; int _Cols = 1; int _Options = 0; int _MaxRows = 3; int _MaxCols = 1]':
/home/seedship/uavAP/include/uavAP/Core/FramedVector3.h:23:81:   required from 'FramedVector3::FramedVector3(const std::initializer_list<_Tp>&) [with OtherDerived = double]'
/home/seedship/uavAP/include/uavAP/Core/SensorData.h:128:38:   required from here
/usr/include/eigen3/Eigen/src/Core/Matrix.h:294:31: error: no matching function for call to 'Eigen::Matrix<double, 3, 1>::_init1<std::initializer_list<double> >(const std::initializer_list<double>&)'
  294 |       Base::template _init1<T>(x);
      |       ~~~~~~~~~~~~~~~~~~~~~~~~^~~
In file included from /usr/include/eigen3/Eigen/Core:462,
                 from /usr/include/eigen3/Eigen/Dense:1,
                 from /usr/local/include/cpsCore/Utilities/LinearAlgebra.h:13,
                 from /home/seedship/uavAP/include/uavAP/Core/FramedVector3.h:9,
                 from /home/seedship/uavAP/include/uavAP/Core/SensorData.h:11,
                 from /home/seedship/uavAP/include/uavAP/Core/Orientation/ENU.h:8,
                 from /home/seedship/uavAP/src/Core/Orientation/ENU.cpp:5:
/usr/include/eigen3/Eigen/src/Core/PlainObjectBase.h:774:30: note: candidate: 'void Eigen::PlainObjectBase<Derived>::_init1(Eigen::Index, typename Eigen::internal::enable_if<(((typename Eigen::internal::dense_xpr_base<Derived>::type::SizeAtCompileTime != 1) || (! Eigen::internal::is_convertible<T, typename Eigen::internal::traits<T>::Scalar>::value)) && ((! Eigen::internal::is_same<typename Eigen::internal::traits<T>::XprKind, Eigen::ArrayXpr>::value) || (typename Eigen::internal::dense_xpr_base<Derived>::type::SizeAtCompileTime == Eigen::Dynamic))), T>::type*) [with T = std::initializer_list<double>; Derived = Eigen::Matrix<double, 3, 1>; Eigen::Index = long int; typename Eigen::internal::enable_if<(((typename Eigen::internal::dense_xpr_base<Derived>::type::SizeAtCompileTime != 1) || (! Eigen::internal::is_convertible<T, typename Eigen::internal::traits<T>::Scalar>::value)) && ((! Eigen::internal::is_same<typename Eigen::internal::traits<T>::XprKind, Eigen::ArrayXpr>::value) || (typename Eigen::internal::dense_xpr_base<Derived>::type::SizeAtCompileTime == Eigen::Dynamic))), T>::type = std::initializer_list<double>]'
  774 |     EIGEN_STRONG_INLINE void _init1(Index size, typename internal::enable_if<    (Base::SizeAtCompileTime!=1 || !internal::is_convertible<T, Scalar>::value)
      |                              ^~~~~~
/usr/include/eigen3/Eigen/src/Core/PlainObjectBase.h:774:43: note:   no known conversion for argument 1 from 'const std::initializer_list<double>' to 'Eigen::Index' {aka 'long int'}
  774 |     EIGEN_STRONG_INLINE void _init1(Index size, typename internal::enable_if<    (Base::SizeAtCompileTime!=1 || !internal::is_convertible<T, Scalar>::value)
      |                                     ~~~~~~^~~~
/usr/include/eigen3/Eigen/src/Core/PlainObjectBase.h:788:30: note: candidate: 'template<class T> void Eigen::PlainObjectBase<Derived>::_init1(const Scalar&, typename Eigen::internal::enable_if<((typename Eigen::internal::dense_xpr_base<Derived>::type::SizeAtCompileTime == 1) && Eigen::internal::is_convertible<T, typename Eigen::internal::traits<T>::Scalar>::value), T>::type*) [with T = T; Derived = Eigen::Matrix<double, 3, 1>]'
  788 |     EIGEN_STRONG_INLINE void _init1(const Scalar& val0, typename internal::enable_if<Base::SizeAtCompileTime==1 && internal::is_convertible<T, Scalar>::value,T>::type* = 0)
      |                              ^~~~~~
/usr/include/eigen3/Eigen/src/Core/PlainObjectBase.h:788:30: note:   template argument deduction/substitution failed:
/usr/include/eigen3/Eigen/src/Core/PlainObjectBase.h: In substitution of 'template<class T> void Eigen::PlainObjectBase<Eigen::Matrix<double, 3, 1> >::_init1<T>(const Scalar&, typename Eigen::internal::enable_if<((Eigen::MatrixBase<Eigen::Matrix<double, 3, 1> >::SizeAtCompileTime == 1) && Eigen::internal::is_convertible<T, double>::value), T>::type*) [with T = std::initializer_list<double>]':
/usr/include/eigen3/Eigen/src/Core/Matrix.h:294:31:   required from 'Eigen::Matrix<_Scalar, _Rows, _Cols, _Options, _MaxRows, _MaxCols>::Matrix(const T&) [with T = std::initializer_list<double>; _Scalar = double; int _Rows = 3; int _Cols = 1; int _Options = 0; int _MaxRows = 3; int _MaxCols = 1]'
/home/seedship/uavAP/include/uavAP/Core/FramedVector3.h:23:81:   required from 'FramedVector3::FramedVector3(const std::initializer_list<_Tp>&) [with OtherDerived = double]'
/home/seedship/uavAP/include/uavAP/Core/SensorData.h:128:38:   required from here
/usr/include/eigen3/Eigen/src/Core/PlainObjectBase.h:788:30: error: invalid use of incomplete type 'struct Eigen::internal::enable_if<false, std::initializer_list<double> >'
[Truncated for brevity]

Can anyone explain what I am missing? I'm confused why the assignment operator works, but not the constructor. This happens on both Eigen 3.3.9-1 and eigen-git.
Update: maybe this question is very library specific, so I asked on the Eigen gitlab project (https://gitlab.com/libeigen/eigen/-/issues/2192)

A: You need to use an extra pair of parenthesis. Also there is no point in templating this constructor since the template argument type needs to match the scalar type of the Eigen vector and if you'd like the scalar type to be configurable you'd need to template the whole class.
In summary
CustomVector3(const std::initializer_list<double>& other) : Vector3({other}) {}

is the correct way to do this. The reason is that Eigen::Vector3d is a typedef for Eigen::Matrix<double, 3, 1>. The initializer list constructor for matrices needs to handle multiple rows and columns however and has thus the signature
explicit PlainObjectBase(const std::initializer_list<std::initializer_list<Scalar>>& list);

If you always want to use 3D vectors the (easier) alternative is to use Eigen's 3D constructor and aggregate initialization:
CustomVector3(double x, double y, double z) : Vector3(x, y, z) {}


text:
Q: repaint() not being called when two separate windows are open When I have just one window open, everything works fine. When I have two windows open, I notice that the repaint method is not called when I want it to. I checked using breakpoints.
public static void main(String[] args) {

    //this creates a first window, allowing user to choose ai/human and colour
    //then GameInterface calls startGame with those parameters
    GameInterface gui = new GameInterface();
    gui.setVisible(true);

    //startGame("ai", "white");
}

When I try calling just startGame without making the GameInterface first, it works all fine! Here is reduced code for GameInterface:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class GameInterface extends JFrame implements ActionListener {

    private JButton startGameButton;

    private JPanel panel = new JPanel();

    public test() {
        initUI();
    }

    private void initUI() {

        getContentPane().add(panel);

        panel.setLayout(null);

        /*
         * Make a start of game button
         */
        startGameButton = new JButton("Start game!");
        startGameButton.setBounds(50, 160, 200, 30);
        startGameButton.setEnabled(false);
        startGameButton.setActionCommand("startGame");
        startGameButton.addActionListener(this);

        panel.add(startGameButton);

        setTitle("Game");
        setSize(300, 400);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    };

    @Override
    public void actionPerformed(ActionEvent e) {
        if ("startGame".equals(e.getActionCommand())) {

            dispose();

            StartGame.startGame("ai", "white");
        }
    }

}

And here's the full StartGame class:
import java.util.ArrayList;

public class StartGame {

    static ArrayList<Piece> blackPieces = new ArrayList<Piece>();
    static ArrayList<Piece> whitePieces = new ArrayList<Piece>();

    public static void main(String[] args) {

            GameInterface gui = new GameInterface();
            gui.setVisible(true);

    //  startGame("ai", "white");
}

public static void startGame(String opponent, String colour) {

    //not using method parameters in this example

    //create a game instance
    ChessGame game = ChessGame.getInstance();

    //create players
    Player player1 = new ChessGui("white");
    Player player2 = new AI ("black");

    player1.setGame(game);
    player2.setGame(game);

    //AND HERE IS THE PROBLEM
    whitePieces = player1.choosePieces();

    blackPieces = player2.choosePieces();

    // at this point, players should add their own pieces
    player1.setOwnPieces(whitePieces);
    player1.setOpponentPieces(blackPieces);
    player2.setOwnPieces(blackPieces);
    player2.setOpponentPieces(whitePieces);

    // add pieces to the game based on players' choices
    game.initialisePiecesFromPlayers();

    new Thread(game).start();

}

And the ChessGui's important methods are:
public class ChessGui extends JComponent implements Player {

    @Override
    public void paintComponent(Graphics g) {

        // draw background
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, WINDOW_SIZE_X, WINDOW_SIZE_Y);

        g.drawImage(imgBackground, 0, 0, null);
    }

    public ChessGui(String colour) {

        this.colour = colour;

        // create graphical board
        try {
            imgBackground = createTileMap(ROWS, COLUMNS);
        } catch (IOException e) {
            e.printStackTrace();
        }

        // create application frame and set visible
        JFrame frame = new JFrame("Chess");
        frame.setSize(WINDOW_SIZE_X, WINDOW_SIZE_Y);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(this);
        frame.setResizable(false);
    }

    @Override
    public ArrayList<Piece> choosePieces() {

        //some code here

        //NOW THIS METHOD IS REACHED, BUT NEVER SEEMS TO CALL THE ABOVE PAINT COMPONENT METHOD
        this.repaint();

        //some more code here

    }

}

Now when I don't create the initial window for option choosing, all seems to work fine...So I'm guessing it's some kind of conflict between ChessGui and GameInterface. I've spend quite a bit of time now in debugging mode in Eclipse setting breakpoints and trying to track the issue down, but without success. Please help!

A: you must call validate(); before  repaint();:
 @Override
    public ArrayList<Piece> choosePieces() {

        //some code here

        this.validate();
        this.repaint();

        //some more code here

    }


text:
Q: Lazy evaluation with ostream C++ operators I am looking for a portable way to implement lazy evaluation in C++ for logging class.
Let's say that I have a simple logging function like
void syslog(int priority, const char *format, ...);

then in syslog() function we can do:
if (priority < current_priority)
  return;

so we never actually call the formatting function (sprintf).
On the other hand, if we use logging stream like
log << LOG_NOTICE << "test " << 123;

all the formating is always executed, which may take a lot of time.
Is there any possibility to actually use all the goodies of ostream (like custom << operator for classes, type safety, elegant syntax...) in a way that the formating is executed AFTER the logging level is checked ?

A: This looks like something that could be handled with expression templates. Beware, however, that expression templates can be decidedly non-trivial to implement.
The general idea of how they work is that the operators just build up a temporary object, and you pass that temporary object to your logging object. The logging object would look at the logging level and decide whether to carry out the actions embodied in the temporary object, or just discard it.

A: What I've done in our apps is to return a boost::iostreams::null_stream in the case where the logging level filters that statement. That works reasonably well, but will still call all << operators.
If the log level is set at compile time, you could switch to an object with a null << operator.
Otherwise, it's expression templates as Jerry said.

A: The easiest and most straight-forward way is to simply move the check outside of the formatting:
MyLogger log;  // Probably a global variable or similar.

if (log.notice())
  log << "notified!\n" << some_function("which takes forever to compute"
    " and which it is impossible to elide if the check is inside log's"
    " op<< or similar");

if (log.warn()) {
  log << "warned!\n";
  T x;
  longer_code_computing(value_for, x);  // easily separate out this logic
  log << x;
}

If you really wanted to shorten the common case, you could use a macro:
#define LOG_NOTICE(logger) if (logger.notice()) logger <<

LOG_NOTICE(log) << "foo\n";
// instead of:
if (log.notice()) log << "foo\n";

But the savings is marginal.
One possible MyLogger:
struct MyLogger {
  int priority_threshold;

  bool notice()  const { return notice_priority  < current_priority; }
  bool warn()    const { return warn_priority    < current_priority; }
  bool etc()     const { return etc_priority     < current_priority; }

  template<class T>
  MyLogger& operator<<(T const &x) {
    do_something_with(x);
    return *this;
  }
};

The problem here is mixing iostream-style operator overloading with a printf-like logging function – specifically translating manipulators and formatting flags/fields from iostreams into a format string.  You could write to a stringstream and then chunk that to your syslog function, or try something fancier.  The above MyLogger works easiest if it also contains an ostream reference to which it can forward, but you'll need a few more op<< overloads for iomanips (e.g. endl) if you do that.

A: For mine I made a debug_ostream class which has templated << operators. These operators check the debug level before calling the real operator.
You will need to define non-template overrides for const char* and std::ostream& (*x)(std::ostream&) because otherwise those don't work. I'm not sure why.
With inlining and high enough optimization levels the compiler will turn the whole output line into a single check of the debug level instead of one per output item.
I should add to this that this doesn't solve the original problem. For example if part of the debug line is to call an expensive function to get a value for output, that function will still be called. My solution only skips the formatting overhead.


text:
Q: Implementation Advice: Binding a button (Click event) to a function, and to another Control too I am  developing a small C#-winforms program, that has a feature allowing users to add buttons and different controls at run-time.
The scenario i am facing is as follows:

*
1) User adds a button and sets its properties (through a Dialog).
2) User adds a another control (also sets its properties).
3) User chooses the button and chooses bind from a Menu-strip item.
4) a new dialog will show , a DropDown menu will show all "other controls" ,  another DropDown will show (pre-coded) functions ,  users have to choose 1 of the controls and a function to bind them to the button's click event.
5) When the user chooses to release his design,  an EXE file will be generated that will have the simple program the user designed (still thinking this step over )

My current implementation idea:
A dictionary will hold all the buttons and their corresponding bound functions and controls.. (Key = buttonID ,  Value = object or dictionary holding function name and Control ID)..
When the user chooses to "Release" his design , the code will construct the form and all controls as TEXT and use  the dictionary to generate the appropriate code button to connect each button's click event to the appropriate Function.
The TEXT will also have another Dictionaries Inserted to it that will map each Button to its bound control (a Dictionary for each function), this will be used when a function gets called to Distinguish between buttons different bound controls.
The TEXT will be inserted into a .cs file that will be compiled to generate the EXE (still still thinking of ways to automate this step ).
I feel like this solution is way too complex and that there might be other simpler solutions.
TIA
EDIT:
This is a simple project , that aims to help non-programmers create their own simple programs , like supermarket inventory , or DVD-store library.
For now it will do simple calculator jobs ( 1 textbox, a couple of buttons and functions like ADD,Subtract and such).

A: i think Compiling the "Program" that will be designed by the user would be a terrible idea.
What you could do is Serialize the Objects created, and write them to a file that can be deserialised and loaded into your program to display the users created "program".
if all the functions will be predefined, you could use a unique Key stored in a new class extended from the Button Class to point to which function you would like linked to the button.
you might want to store arrays of objects the user can use that can be "Customized" with all the their Visible properties set to false to start with.
Im not sure if the Compilation of the users created program is required, or if using your program as a customizable program by plugging serialized objects into it is possible too.
What is the desired goal of the program exactly?
I hope i help in some way to bring new ideas to your design.
If you can give me more information i could try and make some example code for you to look at.


text:
Q: CI3 - Remove the image tags I have a database of blogs.  In the body field, I have html.  Essentially, it is the body of the blog post with all the markup, including  tags that references the path to various images.  In the admin area, I have a list of posts but in the list I don't want to to display any of the images.
Here is an example of the 'body' field:

This is some text.  This is a pict.

There could be more than one image and in various formats.
Also, how can I get the value of 'body' without it rendering the html?  Whenever I say, $item['body'] the html is rendered but I would like to see the html instead.

A: In your CSS, you may target images in the admin area where the post is displayed to hide them.
.admin-area .post-body img {
    display:none;
}

But there would be no need to do the above if you choose to use either of the below functions.
If you would like to display the post body without rendering the HTML:

*

*To show text only: strip_tags($item['body']);

*To show HTML as text: htmlspecialchars($item['body']);


text:
Q: MySQL REGEXP string not followed by another In MySQL, I need to select all registers from a table containing a certain string in a field but not followed by another string.
I have tried using:
select * from table where field REGEXP "(desired_string(?non_desired_follow_up))"

However, I get:
Got error 'repetition-operator operand invalid' from regexp

Can anyone help to get the right sentence for doing that?


text:
Q: in ruby in windows, executing the cmd prompt command 'move' gives error "The syntax of the command is incorrect." in ruby in windows, executing the cmd prompt  command 'move' gives error "The syntax of the command is incorrect."
But it works outside of ruby
C:\rubytest>echo asdf>c:\techprogs\azzz.azz

C:\rubytest>del c:\techprogs\azzz.azz

C:\rubytest>echo asdf>c:\techprogs\azzz.azz

C:\rubytest>move /y c:\techprogs\azzz.azz c:\techprogs\autorun.bat
        1 file(s) moved.

C:\rubytest>move /y c:\techprogs\azzz.azz c:\techprogs\autorun.bat
The system cannot find the file specified.

C:\rubytest>

All of that above is fine and expected.
Notice I never get an error that says "The syntax of the command is incorrect."
Then  try in ruby
I have a simple file with one line
C:\rubytest>type syntaxcommandincorrect.rb
`move /y c:\techprogs\azzz.azz c:\techprogs\autorun.bat`

C:\rubytest>

But it gives that error about the syntax
C:\rubytest>del c:\techprogs\azzz.azz

C:\rubytest>ruby syntaxcommandincorrect.rb
The syntax of the command is incorrect.

C:\rubytest>echo asdf>c:\techprogs\azzz.azz

C:\rubytest>ruby syntaxcommandincorrect.rb
The syntax of the command is incorrect.

C:\rubytest>

A: The problem here is probably the backslashes which have significant meaning inside of interpolated Ruby strings, double-quoted but also backtick-style shell commands.
As such your command is being interpreted as:
move /y c:^Iechprogs^Gzzz.azz c:^Iechprogs^Gutorun.bat

Where ^I is "\t" which is a tab character, and ^G is "\a" which is a bell character.
Instead:
`move /y c:\\techprogs\\azzz.azz c:\\techprogs\\autorun.bat`

Now remember that Ruby has a very comprehensive library of functions you can use to address this directly. Don't treat it like a fancy shell scripting language:
require 'fileutils'

FileUtils.mv('c:\techprogs\azzz.azz', 'c:\techprogs\autorun.bat', force: true)

Where here I'm using single quotes to avoid the double backslashes and force: true is the equivalent of /y. This uses FileUtils.mv, part of a whole package of useful file and directory manipulation utilities.
As a plus you also get proper exceptions if something goes wrong, or an error code if the move failed.
Added by barlop
Confirming the above.  Double backslash fixes it, and i see via doing puts `echo copy /y c:\techprogs...` what happens with single backslash, I see the t of techprogs removed, as c:\techprogs became c:<ascii-9>echprogs.  And \autorun became <ascii-7>utorun
C:\rubytest>cmdoutoutwithoutinitbat.rb | xxd
0000000: 6162 6364 6566 670d 0a63 6f70 7920 2f79  abcdefg..copy /y
0000010: 2063 3a09 6563 6870 726f 6773 0775 746f   c:.echprogs.uto
0000020: 7275 6e2e 6261 7420 633a 0965 6368 7072  run.bat c:.echpr
0000030: 6f67 7307 7a7a 7a2e 617a 7a0d 0a61 6263  ogs.zzz.azz..abc
0000040: 6465 6667 0d0a 6d6f 7665 202f 7920 633a  defg..move /y c:
0000050: 0965 6368 7072 6f67 7307 7a7a 7a2e 617a  .echprogs.zzz.az
0000060: 7a20 633a 0965 6368 7072 6f67 7307 7574  z c:.echprogs.ut
0000070: 6f72 756e 2e62 6174 0d0a                 orun.bat..

C:\rubytest>


text:
Q: Crash using Xcode 6 Beta 4 with AFNetworking on iPhone running iOS 7.1 I've created a simple project in Xcode 6 Beta 4 using Swift and AFNetworking (2.3.1) (using CocoaPods). I'm using the Master-Detail Application template and I'm using a bridge.h file only containing #import <AFNetworking/AFNetworking.h>. I've also added the Foundation framework to the project.
When building for an iPhone (works on iPad) using iOS 7.1 (works on iOS 8) I get an error that looks like this:

If I do it using another template instead of Master-Detail Application it works fine.


text:
Q: Run flutter app from iphone launcher itself I'm new to flutter, I developed apps in Android Studio for ios devices, and they run perfectly when I run them from Android Studio onto the real device. However, if I try to run the app from the iphone itself (from the launcher icon), the app imediately closes and doesn't run.
Why would this be? Is there anything I can do in the code to enable the app to run from the phone itself, not just through running it in Android Studio?
Thanks for any help!


text:
Q: Reactive Form, disable form control after ngOnChanges don't changes the template I am working with reactive forms on an Angular 7 project.
In some component I have a form built with a FormBuilder, and I need some controls to be disabled or enabled depending on an input property.
This input property is obtained in the parent component from an asynchronous request, and when its value changes, I change the "disabled" status, but the template is not changed as expected: the disabled attribute is not set on the corresponding <input>.
Here is my code:
@Input() myInputProperty;
form: FormGroup;

constructor(private fb: FormBuilder) { }

ngOnChanges(changes: SimpleChanges) {
  if (changes['myInputProperty']) {
    this.buildForm();
  }
}

private buildForm() {
  this.form = this.fb.group({
    myControl: {value: myInputProperty && myInputPropery.stuff, disabled: !!myInputProperty}
  });
}

We go twice in the method buildForm(), one time when myInputProperty is not set and one time when myInputProperty has been requested ; after the second time the control is disabled but the template is not updated, the disabled attribute is set on the <input>.
I tried with this.form.get('myControl').disable() but it doesn't work better.
If I add some code like
  if (this.myInputProperty) {
    setTimeout(() => {
      this.form.get('myControl').disable();
    });
  }

at the end of buildForm(), it works but it is not a satisfying workaround.
EDIT: example on stackblitz:
https://stackblitz.com/edit/angular-rkurxt?file=src%2Fapp%2Fhello.component.ts


text:
Q: Awesomium 1.7.5 load local asset CSS file I can load local asset javascript files using this method, but I can't get it to actually bring in the CSS file. The JS file works fine this way.
Is there another way to do this without a resource interceptor, just using the built in embedded resource datasource as asset://  on an element?
I execute some javascript that appends an element into a page with:
    var customjs= document.createElement('script');
    customjs.type = 'text/javascript';
    customjs.src = "asset://local/Scripts/mycustom.js";

But when i try something similar with :
    var customCss = document.createElement('link');
    customCss.setAttribute("rel", "stylesheet")
    customCss.setAttribute("type", "text/css")
    customCss.setAttribute("href", "asset://local/CSS/mycustom.css");

and appending this into the page, it does not work.
Both files are build types of embedded resource.


text:
Q: Wolfram Alpha can't find an explicit form (or even an explicit form of an approximation of) this innocuous series? I suppose my question could be restated as "why?" to the above statement.
I'll rephrase my question if this breaks any rules asking it this way, but the expression is simply:
$$\sum_{m=2}^\infty \frac{1}{m^{2n}(m^2-1)} = ??$$
with the partial sum being:
$$\sum_{m=2}^a \frac{1}{m^{2n}(m^2-1)} = ??$$
$m, n \in \mathbb N$
Are the above two somehow more insidious than they look?

A: Yes, your series is innocuous if $n$ is a non-negative integer: by partial fraction decomposition
$$\frac{1}{m^{2n}(m^2-1)}=-\sum_{k=1}^n\frac{1}{m^{2k}}+\frac{1/2}{m-1}-\frac{1/2}{m+1}.$$
Hence
$$\sum_{m=2}^{\infty} \frac{1}{m^{2n}(m^2-1)} =
-\sum_{k=1}^n\zeta(2k)+n+\frac{3}{4}$$
where $\zeta(2k)=\frac{|B_{2k}|(2\pi)^{2k}}{2(2k)!}$ (see wiki).
However, I guess that wolframalpha considers $n$ as a complex argument (not as a non negative integer). On the other hand, given an explicit non negative integer $n$, wolframalpha will give you the result.

A: $$
\begin{align}
\sum_{m=2}^\infty\frac1{m^{2n}(m^2-1)}
&=\sum_{m=2}^\infty\sum_{k=n+1}^\infty m^{2k}\\
&=\sum_{k=n+1}^\infty\sum_{m=2}^\infty m^{2k}\\
&=\sum_{k=n+1}^\infty(\zeta(2k)-1)\\
&=\bbox[5px,border:2px solid #C0A000]{\frac34-\sum_{k=1}^n(\zeta(2k)-1)}\tag1
\end{align}
$$
since
$$
\begin{align}
\sum_{k=1}^\infty(\zeta(2k)-1)
&=\sum_{k=1}^\infty\sum_{n=2}^\infty\frac1{n^{2k}}\\
&=\sum_{n=2}^\infty\sum_{k=1}^\infty\frac1{n^{2k}}\\
&=\sum_{n=2}^\infty\frac1{n^2-1}\\
&=\frac12\sum_{n=2}^\infty\left(\frac1{n-1}-\frac1{n+1}\right)\\[3pt]
&=\frac34\tag2
\end{align}
$$
In $(1)$, $\zeta(2k)$ is a rational multiple of $\pi^{2k}$, as shown in this answer.
Here are the first several sums:
$$
\begin{array}{c|l}
n&\frac34-\sum\limits_{k=1}^n(\zeta(2k)-1)\\\hline
1&\frac74-\frac{\pi^2}6\\
2&\frac{11}4-\frac{\pi^2}6-\frac{\pi^4}{90}\\
3&\frac{15}4-\frac{\pi^2}6-\frac{\pi^4}{90}-\frac{\pi^6}{945}\\
4&\frac{19}4-\frac{\pi^2}6-\frac{\pi^4}{90}-\frac{\pi^6}{945}-\frac{\pi^8}{9450}\\
5&\frac{23}4-\frac{\pi^2}6-\frac{\pi^4}{90}-\frac{\pi^6}{945}-\frac{\pi^8}{9450}-\frac{\pi^{10}}{93555}\\
6&\frac{27}4-\frac{\pi^2}6-\frac{\pi^4}{90}-\frac{\pi^6}{945}-\frac{\pi^8}{9450}-\frac{\pi^{10}}{93555}-\frac{691\pi^{12}}{638512875}
\end{array}\tag3
$$


text:
Q: moment.isBetween() is not working as expected I am using moment (version "^2.25.3") library to check if the date is in between two dates.
I have to check, if araDate is in between two dates(startdate and endDate) or araDateMinusOne is in between the dates(startDate and endDate), but the condition here is startdate should be equal to araDateMinusOne(ie if a startdate is sep/03 and enddate is sep/04, it should not match).
Can somebody tell me what I am doing wrong or why exactly is this happening?

const obj = {
  _id: '614c2b941e06b7003024e1df',
  promotedtitles: [{ title: '1' }, { title: '2' }],
  startdate: '2021-09-04T00:00:00.000Z',
  enddate: '2021-09-04T00:00:00.000Z'
};

const camStartDate = moment(obj.startdate).format('YYYY-MM-DD'); // 2021-09-04
const camEndDate = moment(obj.enddate).format('YYYY-MM-DD'); // 2021-09-04
const araDate = moment('2021-09-05T00:00:00.000Z').format('YYYY-MM-DD'); // 2021-09-05
const araDateMinusOne = moment('2021-09-05T00:00:00.000Z').subtract(1, 'day').format('YYYY-MM-DD'); // 2021-09-04

console.log('check', moment(araDate).isBetween(camStartDate, camEndDate, undefined, '[]')); // false which is fine.
console.log('another check', moment(araDateMinusOne).isBetween(camStartDate, camEndDate, undefined, '[)')); // this is consoling false, which is incorrect

//I also have tried this as well and all the variations.

console.log('another check', moment(araDateMinusOne).isBetween(camStartDate, camEndDate, 'day', '[)'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.25.3/moment.min.js" ></script>

A: The reason why it is returning false for checking the equal range and giving '[)', as a parameter is the enddate is taking priority here. And when it is checking endDate we are giving exclusion operator for that.
moment('2021-09-04').isBetween('2021-09-04', '2021-09-04', 'day', '[)'

The solution to this problem is to check the date is between two dates and if the startdate is equal to that araMinusOne date.
moment(araDateMinusOne).isBetween(camStartDate, camEndDate, 'day', '[]') && moment(araDateMinusOne).isSame(camStartDate)

A: the inclusion parameters should be []

const obj = {
  _id: '614c2b941e06b7003024e1df',
  promotedtitles: [{ title: '1' }, { title: '2' }],
  startdate: '2021-09-04T00:00:00.000Z',
  enddate: '2021-09-04T00:00:00.000Z'
};

const camStartDate = moment(obj.startdate).format('YYYY-MM-DD'); // 2021-09-04
const camEndDate = moment(obj.enddate).format('YYYY-MM-DD'); // 2021-09-04
const araDate = moment('2021-09-05T00:00:00.000Z').format('YYYY-MM-DD'); // 2021-09-05
const araDateMinusOne = moment('2021-09-05T00:00:00.000Z').subtract(1, 'day').format('YYYY-MM-DD'); // 2021-09-04

console.log('check', moment(araDate).isBetween(camStartDate, camEndDate, undefined, '[]')); // false which is fine.
console.log({araDateMinusOne,camStartDate, camEndDate})
console.log('another check', moment(araDateMinusOne).isBetween(camStartDate, camEndDate, undefined, '[]')); // this is consoling false, which is incorrect
//I also have tried this as well and all the variations.

console.log('another check 1', moment(araDateMinusOne).isBetween(camStartDate, camEndDate, 'day', '[)'));

console.log('default check ', moment('2016-10-30').isBetween('2016-10-30', '2016-10-30', undefined, '[]'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.25.3/moment.min.js" ></script>


text:
Q: How to merge two sequences in single sequence in an alternate manner without using arrays? for eg if sequence 1 : <1,3,5> and sequence 2 : <2,6,8,11,12>
than the result should be <1,2,3,6,5,8,11,12>

I tried to solve it using loops but what I am getting is a repeated structure

A: I'd be surprised if there isn't a better way to do it, but one way to do it would be like this:
from itertools import zip_longest

seq_1 = [1,3,5]
seq_2 = [2,6,8,11,12]
seq_3 = []
for a, b in zip_longest(seq_1, seq_2): # -> (1, 2) (3, 6) (5, 8) (None, 11) (None, 12)
    if a:
        seq_3.append(a)
    if b:
        seq_3.append(b)

A: i=0
j=0
N=len(L1)
M=len(L2)
L=[]
turn=True
while(i<N and j<M):
    if turn:
        L.append(L1[i])
        i+=1
    else:
        L.append(L2[j])
        j+=1
    turn=!turn
while(i<N):
    L.append(L1[i])
    i+=1
while(j<M):
    L.append(L2[j])
    j+=1
print(L)

THis can do the trick for you What Is being done is That I am keeping a boolean Turn to Alternate turns to select from the two arrays If You have any doubt regarding the loop logic I can elaborate a little. simple turn= !turn => ALternates turns on each iteration

A: This should do the trick.
Explanation:
a = [1,3,5]
b = [2,4]
zip_longest(a,b) -> (1,2), (3,4), (5, None)
chain.from_iterable(l) -> 1,2,3,4,5,None
Followed by list comprehension.
from itertools import chain, zip_longest

l = [i for i in chain.from_iterable(zip_longest(a,b)) if i]

A: This code gives you a list of sorted numbers based on input.
x1,x2=[1,3,5],[2,6,8,11,12]

print(sorted(x1+x2))


text:
Q: How to call a modal from a different HTML File I realise there are similar questions on stackoverflow, however they either seem outdated(bootstrap3) or are not working for me. If possible I want to just stick to html css and javascript. I would prefer not using jquery or php.
I'll keep my code very general. I have my mainscreen which has a button I need that button to call a modal from ModalPage. ModalPage only has that modal with no other code. I'm using flask-python as my backend.
Mainscreen
<button type="button" class="btn btn-primary btn-lg">This should call modal/button>

ModalPage

Modal title

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          ×
        </button>

Modal body text goes here.

        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>

I have tried using url_for and rendering it using  but that doesn't seem to be working

A: You might have to store the entire modal HTML in a variable within your Python Flask code. One way (out of quite a few number of ways) would be to read the text and store the html in a variable using:
modaltext=[]
with open('ModalPage.html', 'r') as f:
    content = f.read()
    modaltext.append(content)

Put this above code in your views.py preferably. That filename depends on where you have stored the ModalPage.html. Here I assumed, it is in the same folder as views.py (which might not be the case. It could be in templates, but I dunno your folder structure).
And modify your return render statement to also return the modaltext list.
Then, call it to your Mainpage HTML using jinja2 syntax wherever necessary. Typically it could be like:

{{ modal }}

A: I'm honestly not sure about the python/flask portion, but I do what you are attempting using only html/js. You could add an ID to the button, i.e 'modal-form-button'. Then make an event listener in JS for the element with that ID being clicked.
document.getElementById("test-btn").addEventListener("click", showModal);

The showModal() function can contain the necessary code to toggle the display of the modal between 'display:bloack' and 'display:none'


text:
Q: find a date range from min and max date field I am trying to find the earliest instance of a date for a unique ID (unique ID has multiple rows of data with different dates) and then filter that result to find the data between years 2005 and 2010 using a subquery. I keep getting 'Incorrect syntax near the keyword 'group'':
Select *
from (select custnum, YEAR(min(Date_field)) as field1, Field2, field3, field4, field5
        from table1
        group by custnum, field2, field3, field4, field5)
    having YEAR(min(Date_field)) between 2005 and 2010

Any Ideas?
Thanks for your help-

A: If I understood you correctly, you can use:
WITH CTE AS
(
    SELECT  custnum,
            Field2,
            Field3,
            Field4,
            Field5,
            Field1 = MIN(Date_Field) OVER(PARTITION BY custnum)
    FROM dbo.table1
)
SELECT *
FROM CTE
WHERE Field1 BETWEEN '20050101' AND '20101231';


text:
Q: Ввод с кливиатуры и exeption Привет всем! Пишу консольное приложение. В  switch  я поставил ввод с клавиатуры,но если юзер введет не число - летит exeption и программа закрывается. как сделать что-бы "на лету" проверялся тип данных?Я пробывал в catch рукурсию засунуть.Не работает:))
@Override
public int startMenu() { //переделать в свитч // закинуть на стакоф
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

    System.out.println("Добрый день! \nСделайте выбор:\n1)Cоздать список.\n2)Выход");
    int choice = 0;
    int result = 0;
    try {
        while (true) {
            choice = Integer.parseInt(reader.readLine());

            switch (choice){
                case 1 : result = 1;
                break;
                case 2 : result = 2;
                break;
                default:
                    System.out.println("Ошибка выбора операции.Сделайте выбор и введите номер операции!");
            }
        }
    } catch (Exception e) {
        System.out.println("Ошибка выбора операции.Сделайте выбор и введите номер операции!");

    }

    return result;
}

A: @Override
public int startMenu() {
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

    System.out.println("Добрый день! \nСделайте выбор:\n1)Cоздать список.\n2)Выход");
    int choice = 0;
    int result = 0;
    boolean bool = false;
    while (!bool) {
        try {
            choice = Integer.parseInt(reader.readLine());

            switch (choice) {
            case 1 :
                result = 1;
                bool = true;
                break;
            case 2 :
                result = 2;
                bool = true;
                break;
            default:
                System.out.println("Ошибка выбора операции. Сделайте выбор и введите номер операции!");
            }
        } catch (Exception e) {
            System.out.println("Ошибка выбора операции. Введите целое число!");
        }
    }
    return result;
}

A: public int startMenu() { //переделать в свитч // закинуть на стакоф
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    System.out.println("Добрый день! \nСделайте выбор:\n1)Cоздать список.\n2)Выход");
    while (true) {
        try {
            int result = Integer.valueOf(reader.readLine());
            if (result == 1 || result == 2) return result;
            else throw new IOException();
        } catch (IOException | NumberFormatException ex) {
            System.out.println("Ошибка выбора операции.Сделайте выбор и введите номер операции!");
        }
    }
}


text:
Q: Paging With Repeater I want to do paging in repeater control. I am using xml as a database with linq. So please give me suggestion how can do it.
I try this code but its not working
    public int RowCount
    {
        get
        {
            return (int)ViewState["RowCount"];
        }

        set
        {
            ViewState["RowCount"] = value;
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {

        if (!IsPostBack)
        {
            FetchData(5, 0);
        }
        else
        {
            PlaceHolder1.Controls.Clear();
            CreatePagingControl();
        }

    }

    private void FetchData(int take,int pagesize)
    {
        var doc = XDocument.Load(Server.MapPath("~/BlogContent.xml"));
        var result = doc.Descendants("post").Where(x => x.Element("id") != null).Take(take).Skip(pageSize)
        .Select(x => new
        {
            id = x.Element("id").Value,
            title = x.Element("title").Value,
            Description = x.Element("Discription").Value,
            dt = x.Element("dt").Value,
            mnt = x.Element("mnt").Value,
            yr = x.Element("yr").Value,
            postdate = x.Element("PostDate").Value
        }).OrderByDescending(x => x.id);

        PagedDataSource page = new PagedDataSource();
        page.AllowPaging = true;
        page.AllowCustomPaging = true;
        page.DataSource = result;
        page.PageSize = 10;
        if (!IsPostBack)
        {
            RowCount = result.Count();

        }

    }
    private void CreatePagingControl()
    {
        for (int i = 0; i < (RowCount / 10) + 1; i++)
        {
            LinkButton lnk = new LinkButton();
            lnk.Click += new EventHandler(lbl_click);
            lnk.ID = "lnkPage" + (i + 1).ToString();
            lnk.Text = (i + 1).ToString();
            PlaceHolder1.Controls.Add(lnk);
            Label spacer = new Label();
            spacer.Text = " ";
            PlaceHolder1.Controls.Add(spacer);
        }

    }
    void lbl_click(object sender, EventArgs e)
    {
        LinkButton lnk = sender as LinkButton;
        int currentPage = int.Parse(lnk.Text);
        int take = currentPage * 10;
        int skip = currentPage == 1 ? 0 : take - 10;
        FetchData(take, skip);

    }

When i am using this code the previous and next buttons are working but data on repeater is not changing

A: Have a look at :
void lbl_click(object sender, EventArgs e)
{
    LinkButton lnk = sender as LinkButton;
    int currentPage = int.Parse(lnk.Text);
    int take = currentPage * 10;
    int skip = currentPage == 1 ? 0 : take - 10;
    FetchData(take, skip);
}

What you are saying is that you will display 10 times the number of the currentpage in rows. For instance if you are in page 4 you are going to display 40 rows, whereas in page 5 you will display 50 rows.
Then you dictate how many rows to skip, so in first page you will skip none, but in page 4 you will skip 40 - 10 = 30 rows. What you should do is take always a predefined set of rows, ie 10 and then the skip to be a variable.
For instance you should have your code as:
void lbl_click(object sender, EventArgs e)
{
    LinkButton lnk = sender as LinkButton;
    int currentPage = int.Parse(lnk.Text);
    int take = 10;
    int skip = (currentPage - 1) * 10;
    FetchData(take, skip);
}

In page 1 you will skip 0 rows, in page 2 10 rows etc.
You could even take under consideration on having the take number in a user defined variable...
Edit
You should also check your Page_Load
protected void Page_Load(object sender, EventArgs e)
{

    if (!IsPostBack)
    {
        FetchData(5, 0);
    }
    else
    {
        PlaceHolder1.Controls.Clear();
        CreatePagingControl();
    }

}

In the initial load of data you take the five first rows and skip 0. If you change that to
FetchData(10, 0);

you should be ok.
Giannis


text:
Q: Laravel 5.1 GMAIL SMTP in mail.php I am putting gmail smtp in mail.php file but after setting up this in mail.php, website front end and backend images stops showing. i really do not know what is the connection between this to mail.php.
Plz suggest me something on this.

return [
/*
|--------------------------------------------------------------------------
| Mail Driver
|--------------------------------------------------------------------------
|
| Laravel supports both SMTP and PHP's "mail" function as drivers for the
| sending of e-mail. You may specify which one you're using throughout
| your application here. By default, Laravel is setup for SMTP mail.
|
| Supported: "smtp", "mail", "sendmail", "mailgun", "mandrill", "ses", "log"
|
*/

'driver' => 'smtp',

/*
|--------------------------------------------------------------------------
| SMTP Host Address
|--------------------------------------------------------------------------
|
| Here you may provide the host address of the SMTP server used by your
| applications. A default option is provided that is compatible with
| the Mailgun mail service which will provide reliable deliveries.
|
*/

'host' => 'smtp.gmail.com',

/*
|--------------------------------------------------------------------------
| SMTP Host Port
|--------------------------------------------------------------------------
|
| This is the SMTP port used by your application to deliver e-mails to
| users of the application. Like the host we have set this value to
| stay compatible with the Mailgun e-mail application by default.
|
*/

'port' => '587',

/*
|--------------------------------------------------------------------------
| Global "From" Address
|--------------------------------------------------------------------------
|
| You may wish for all e-mails sent by your application to be sent from
| the same address. Here, you may specify a name and address that is
| used globally for all e-mails that are sent by your application.
|
*/

'from' => ['address' => 'c***@gmail.com', 'name' => 'Bigfyda'],

/*
|--------------------------------------------------------------------------
| E-Mail Encryption Protocol
|--------------------------------------------------------------------------
|
| Here you may specify the encryption protocol that should be used when
| the application send e-mail messages. A sensible default using the
| transport layer security protocol should provide great security.
|
*/

'encryption' => env('MAIL_ENCRYPTION', ''),

/*
|--------------------------------------------------------------------------
| SMTP Server Username
|--------------------------------------------------------------------------
|
| If your SMTP server requires a username for authentication, you should
| set it here. This will get used to authenticate with your server on
| connection. You may also set the "password" value below this one.
|
*/

'username' => 'c****@gmail.com',

/*
|--------------------------------------------------------------------------
| SMTP Server Password
|--------------------------------------------------------------------------
|
| Here you may set the password required by your SMTP server to send out
| messages from your application. This will be given to the server on
| connection so that the application will be able to send messages.
|
*/

'password' => '*****',

/*
|--------------------------------------------------------------------------
| Sendmail System Path
|--------------------------------------------------------------------------
|
| When using the "sendmail" driver to send e-mails, we will need to know
| the path to where Sendmail lives on this server. A default path has
| been provided here, which will work well on most of your systems.
|
*/

'sendmail' => '/usr/sbin/sendmail -bs',

/*
|--------------------------------------------------------------------------
| Mail "Pretend"
|--------------------------------------------------------------------------
|
| When this option is enabled, e-mail will not actually be sent over the
| web and will instead be written to your application's logs files so
| you may inspect the message. This is great for local development.
|
*/

'pretend' => false,

];

A: What is the error message? Check the Requests with your developer console in the Network Tab. And check your laravel.log in storage/logs/laravel.log. What would help a lot.

A: Gmail's SMTP port is 465.
Try this one and maybe it will work.

A: Remove the last comma:
'pretend' => false,

become
'pretend' => false

A: Thanx all for your time.
I found my answer here....https://support.google.com/a/answer/3299041
I had to setup Image Proxy URL.


text:
Q: Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'portal.Models.SubProjectViewRecord' I've got this simple code that will consume api json array from a url.
public ActionResult ViewRecord()
        {

            ViewBag.Title = "- Geotagging Sub Project Record.";
            var webClient = new WebClient();
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls
                                     | SecurityProtocolType.Tls11
                                     | SecurityProtocolType.Tls12;
            webClient.Headers.Add(HttpRequestHeader.Cookie, "cookievalue");
            string objJson = webClient.DownloadString(@"https://test.com/api/lib_region");

             //here we will map the Json to C# class
            Models.SubProjectViewRecord oop = JsonConvert.DeserializeObject<Models.SubProjectViewRecord>(objJson);
            return View(oop);

    }

my model
namespace portal.Models
{
    public class SubProjectViewRecord
    {
        public string Name { get; set; }
        public int Id { get; set; }
    }
}

The error of the code above is:
'Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'portal.Models.SubProjectViewRecord' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
Path '', line 1, position 1.'

then these are the fixes I apply to model as some reply being posted.
public class SubProjectViewRecord
        {
            public List<string> Name { get; set; }
            public List<int> Id { get; set; }
        }

to this line:
Models.SubProjectViewRecord oop = JsonConvert.DeserializeObject<List<Models.SubProjectViewRecord>>(objJson);

but the error raised:
Cannot implicitly convert type 'System.Collections.Generic.List<portal.Models.SubProjectViewRecord>' to 'portal.Models.SubProjectViewRecord'

A: Apparently looks like from the error that there are multiple items in the array that is why there is any array returned from the api reponse. you can use a List<T> for it and the code for it would be like :
List<Models.SubProjectViewRecord> oop = JsonConvert.DeserializeObject<List<Models.SubProjectViewRecord>>(objJson);

While your model would be below assuming that the json array elements are of json object with Id and Name members in it:
public class SubProjectViewRecord
{
    public string Name { get; set; }
    public int Id { get; set; }
}

A: First of all, you'll need to know how is your data returned by your JSON. So, if you have something like that:
[
  {
    "name": "",
    "id": ""
  }
]

What you'll need is a list of a class that implements a structure like that (like SubProjectViewRecord). So, you'll have something like that:
List<SubProjectViewRecord> oop = JsonConvert.DeserializeObject<List<SubProjectViewRecord>>(objJson);

And if you see, that is exactly what your error says. It says: "I cannot assign a List to a SubProjectViewRecord variable".
So, just be sure of:

*

*Your class matches exactly with your JSON structure.

*The class that you provide for the deserialization (the generic that you pass on DeserializeObject) is the same as the variable that will receive the deserialization.


text:
Q: Only one usage of each socket address is normally permitted (but I need to use the same ports...) I'm making a (NAT traversal) script and I get the error below.
Here on stackoverflow I have read that it's because SO_REUSEADDR only discards the TIME_WAIT on ports on which a socket has run. And it does NOT help, when you try to connect on the reused port to a same address (ip+port).
    (For NAT traversal you need to use the same port to know, which external port a NAT gives you).
Is there any way to connect to the same ip+port on the same port again and again?
Unfortunately, I cannot use UDP as I only have access to our apache school server running on TCP (maybe even the server is behind NAT, only has its 80 port forwarded).
simplified code (me, I don't connect to google, but to my school server):
>>> sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
>>> sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
>>> sock.bind(('',6000))
>>> sock.connect(('google.com',80))
>>> sock.shutdown(socket.SHUT_RDWR)
>>> sock.close()
>>> sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
>>> sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
>>> sock.bind(('',6000))
>>> sock.connect(('google.com',80))

Traceback (most recent call last):
  File "<pyshell#64>", line 1, in <module>
    sock.connect(('google.com',80))
  File "C:\Python27\lib\socket.py", line 224, in meth
    return getattr(self._sock,name)(*args)
error: [Errno 10048] Only one usage of each socket address (protocol/network address/port) is normally permitted
>>>

Thanks for responses!

A: The idea of the socket.SO_REUSEADDR  to reuse the local port is good but the protection of TIME_WAIT to get unconsistent message from the previous source is there, kernel do not allow you to connect to the previous source.
Take a look to this article bind address

A: There is a solution for you. It's called socket.SO_LINGER and it does a force close of the connection by sending RST (reset) packet to the destination. It may not be delivered but nobody cares 'bout the school server. It can have some issues like the server can send things (that were delayed or the server did not receive the RST packet) and my computer would think it's from the now pending connection. But I guess it wouldn't send anything as I did a POST so I don't expect anything.
There is some material on internet on this theme e.g. http://www.serverframework.com/asynchronousevents/2011/01/time-wait-and-its-design-implications-for-protocols-and-scalable-servers.html
If I'm anywhere wrong, please, you may correct me.
Merry Christmas!


text:
Q: Properly Encoding Static Image Data for NextJS I'm trying a purely static approach on a new project Next v12 project, building up 5-6 data files to feed into getStaticProps. Here's one of the shapes of the data file (but they're all similar):
import SqAshland1 from '../../public/best-places-imagery/square-ashland.jpg'

const bestPlacesList = [
   {
    "cityName": "Ashland",
    "state": "WI",
    "country": "US",
    "imageSquare": SqAshland1,
    "slug": "ashland-wi"
   },
   ...
]

const encodeBestPlacesList = JSON.stringify(bestPlacesList)
export default bestPlacesList

This is what it looks like when I inject this file in my /pages/best-places/[slug].js:
export async function getStaticProps({ params, preview = false, previewData }) {

  const parsedBestPlacesList = JSON.parse(bestPlacesList)
  const cityData = parsedBestPlacesList.find( city => city.slug === params.slug )

  return {
    props: {
      preview,
      cityData: cityData,
    },
    revalidate: 60,
  };
}

export async function getStaticPaths() {
  const cities = JSON.parse(bestPlacesList);

  return {
    paths: cities?.map( (city) => ({
      params: { slug: city.slug }
    })),
    fallback: false,
  };
}

It's working well, but the images keep breaking when I deploy. This makes me think I need to do base64 encoding for the images but where do I do this so I don't break Next's image fetching? Curious if anyone has tried this approach and knows how to balance Next and Node just right.

A: *

*Personally, I think base64 would be right to use here. It would be best to use bease64 encoding together with the data URI scheme (https://en.wikipedia.org/wiki/Data_URI_scheme).

You could use the following helper function to get an image base 64 encode with the URI scheme
// Helper function
function base64EncodeJpg(file) {
    return "data:image/jpg;base64," + fs.readFileSync(file, 'base64');
}

*Use the helper function when you create the bestPlacesList
const bestPlacesList = [
   {
    "cityName": "Ashland",
    "state": "WI",
    "country": "US",
    "imageSquare": base64EncodeJpg('../../public/best-places-imagery/square-ashland.jpg'),
    "slug": "ashland-wi"
   },
   ...
]

*to make sure the paths will work both in production and development you could make use of a .env file where you define a base path for the image assets and use this instead of the relative paths.
https://nextjs.org/docs/basic-features/environment-variables


text:
Q: How can I update/rebind variable without changing the value? I have a RESTful server which have several images.
I am using below URL to get an user's profile image.
https://example.com/users/jake/profile_image

My Typescript:
...
export class SomePage {

    // this variable is binded to img tag in html
    profile_image: string = 'https://example.com/users/jake/profile_image';

    changeProfileImageInServer() {
        // this method changes profile image in the server.
        // But, the new image has the same URL.
    }
}

The value of variable 'profile_image' doesn't need to change because the new image in the server has the same URL. but I want to change image in html because the profile image has changed. What should I do from now?
Thanks in advance.

A: I answer my own question, thinking someone will have the same question with mine.
I also uploaded this question in the forum of the ionic framework.
One of the moderators of Ionic framework answered my question.

this will not work because of the image cache of the browser/webview.
  You should store the timestamp/date, when the image was changed --> so
  you can add this timestamp to the image url:
'https://example.com/users/jake/profile_image?' + TIMESTAMP

from https://forum.ionicframework.com/t/how-can-i-update-rebind-variable-without-changing-the-value/73436/2?u=jeongmincha


text:
Q: differentiable mapping between surfaces Let $M$ and $N$ be surfaces, and $f: M\rightarrow N$ a differentiable and bijective map
(a) Can you ensure that f is a diffeomorphism?
(b) Suppose further that the map $T_{p}f:T_{M}\rightarrow T_{f(p)}N$ is an isomorphism for each $p\in M$, can you ensure that a diffeomorphism?
in (a) i think that is false, but I try to make a example, but the differentiability of the inverse is always hard

A: For (a) let $M = N = \mathbb{R}^2$ with standard coordinates $(x,y)$ for $M$ and $(u,v)$ for $N$. Let $f$ be:
$$ f(x,y) = (x^3,y) $$
Clearly $f$ is bijective and differentiable. But the inverse map
$$ g(u,v) = (\sqrt[3]{u},v) $$
is not differentiable when $u = 0$.

For (b) by the inverse function theorem $f$ is a local diffeomorphism. Then since it is bijective it is a diffeomorphism.


text:
Q: Laravel: In which cases does the tokenmismatchexception come? The users of my Website told me that they got the tokenmismatchexception when the sent the formular.
If I try I didn't got it.
So, in which cases does the tokenmismatchexception come? How can I catch it?
Thank you in advanced.

A: This error appears when:

*

*The user leaves the page opened for a long time of period, The default time is 2 hours and can be configured in config/session - lifetime

*When you submit a form without including the _token field or without excluding the url on app/Http/Middleware/VerifyCsrfToken
To put the _token field on any form you can use {!! csrf_field() !!}
You can check the docs for more information


text:
Q: Making a single number per line pyramid using nested loop and trying to center it I have to create a number pyramid using nested loops for homework. I am very new to nested loops and am still not quite clear on how they work completely. My objective is to make this pyramid using nested loops:
-----1-----
----333----
---55555---
--7777777--
-999999999-

however I have only been able to get this:
----------1
--------333--
------55555----
----7777777------
--999999999--------

I think I am on the right track but I am not sure where to go from here.
Here is the code I currently have:
public class NumberPyramid

{
    public static void main(String [] args)
    {
        for(int i=1; i<=9; i+=2)
        {
            for (int j = 11; j > i; j--)
            {
                System.out.print("-");
            }
            for(int j=1; j<=i; j++)
            {
                System.out.print(i);
            }
            for (int j = 1; j < i; j++)
            {
                System.out.print("-");
            }
            System.out.println();
        }
    }
}

A: The part of printing the numbers in the center is correct.
Printing the - before and after the numbers is incorrect.
Notice that for any row, the number of - before and after the numbers should be the same. How many - to print for a number?

*

*For 1, print 5 - before and after.

*For 3, print 4 - before and after.

*For 5, print 3 - before and after.

That's (11 - i) / 2. Put this loop before and after the center line and you're done.
for (int j = 0; j < (11 - i) / 2; j++) {
    System.out.print("-");
}

A: You should remove two - on every second line
int index = 5;
for (int i=1; i<=9; i+=2) {
    for (int j=0; j<index; j++) {
        System.out.print("-");
    }
    for (int k=0; k<i; k++) {
        System.out.print(i);
    }
    for (int j=0; j<index; j++) {
        System.out.print("-");
    }
    System.out.println();
    index--;
}


text:
Q: How to get latest frame in raspberry pi camera using OpenCV video capture in qt5? I am using opencv4.5.0 in raspberry pi with qt5 c++ by using OpenCV video capture to read a frame from the raspberry pi camera, it gives a buffer image but by using usb2 web camera (Logitech) works fine with the latest frame with the same code by setting buffer size 1 it gives the first 2 buffer frame images and the third image is the latest frame.
Please refer to the following code,
QScopedPointer<cv::VideoCapture> videoCapture_;

  videoCapture_.reset(new cv::VideoCapture(0));
  if (videoCapture_->isOpened())
  {
   videoCapture_->read(CaptureImage);
  }


text:
Q: map as div background - Google Maps API I'm using for a while following javascript code to load google map as DIV background.
// When the window has finished loading create our google map below
            google.maps.event.addDomListener(window, 'load', init);

            function init() {
                // Basic options for a simple Google Map
                // For more options see: https://developers.google.com/maps/documentation/javascript/reference#MapOptions
                var mapOptions = {
                    // How zoomed in you want the map to start at (always required)
                    zoom: 15,

                    // The latitude and longitude to center the map (always required)
                    center: new google.maps.LatLng(54.549047, 18.443433), // New York

                    // How you would like to style the map.
                    // This is where you would paste any style found on Snazzy Maps.
                    styles: [   {       featureType:"all",      elementType:"all",      stylers:[       {           invert_lightness:true       },      {           saturation:10       },      {           lightness:30        },      {           gamma:0.5       },      {           hue:"#1C705B"       }       ]   }   ]
                };

                // Get the HTML DOM element that will contain your map
                // We are using a div with id="map" seen below in the <body>
                var mapElement = document.getElementById('map');

                // Create the Google Map using out element and options defined above
                var map = new google.maps.Map(mapElement, mapOptions);
            }

works perfectly. But when I've tried to load there a marker which will point to my location, it crashes. Any ideas what will be the proper placement of such? I assume this is the proper code (which doesn't work..):
var myLatlng = new google.maps.LatLng(54.549047, 18.443433);
var marker = new google.maps.Marker({
      position: myLatlng,
      map: map,
      title: 'Hello World!'
  });

thanks for the help!


text:
Q: virsh error: domain is already quiesced My VM backup script fails while creating the snapshot.
virsh snapshot-create-as --domain machine_1 snap --diskspec vda,file=/srv/test/test-snap.qcow2 --disk-only --atomic --no-metadata --quiesce
error: Requested operation is not valid: domain is already quiesced

Even after a VM reboot, the system is still quiesced and I get the same error.
I thought quiesce means FS freeze, but this makes no sense since I can still write to the FS when logged in the faulty VMs. And this would not survive a reboot, right?
Could it be a communication issue that makes the host think the GA says the machine is quiesced while it is not?
In any case, is there a command to enquire the quiesce state (apart from attempting a snapshot and see if I get an error)?
Assuming the faulty VMs went quiesced after a unreproducible error, I could fix that by exiting quiesced state, whatever that means. Is there a virsh command to unquiesce the VM?
The whole backup procedure used to work and now it fails on 2 VMs but still works on 2 others and I can't think of any relevant difference between them.
Software versions:

*

*Host is Debian Jessie with qemu-kvm 2.8+dfsg-3~bop8+1 from backports.

*Guests are Debian Stretch with qemu-guest-agent 2.8+dfsg-6+deb9u4.

(For the record, the backup script is here on GitHub. Basically, what it does is 1/ create snapshot, 2/ copy, 3/ commit snapshot.)
If I remove the quiesce option from the snapshot command line, things work smooth. But obviously, this is not ideal.

A: The root cause is a bug that was fixed in libvirt 1.2.11.

Fixed upstream by:
commit 6085d917d5c5839b7ed351e99fadbbb56f5178fe
Author: Michal Privoznik <mprivozn@redhat.com>
Date: Thu Nov 27 11:43:56 2014 +0100

qemu: Don't track quiesced state of FSs

https://bugzilla.redhat.com/show_bug.cgi?id=1160084

As of b6d4dad11b (1.2.5) we are trying to keep the status of FSFreeze
in the guest. Even though I've tried to fixed couple of corner cases
(6ea54769ba18), it occurred to me just recently, that the approach is
broken by design. Firstly, there are many other ways to talk to
qemu-ga (even through libvirt) that filesystems can be thawed (e.g.
qemu-agent-command) without libvirt noticing. Moreover, there are
plenty of ways to thaw filesystems without even qemu-ga noticing (yes,
qemu-ga keeps internal track of FSFreeze status). So, instead of
keeping the track ourselves, or asking qemu-ga for stale state, it's
the best to let qemu-ga deal with that (and possibly let guest kernel
propagate an error).

Moreover, there's one bug with the following approach, if fsfreeze
command failed, we've executed fsthaw subsequently. So issuing
domfsfreeze in virsh gave the following result:

virsh # domfsfreeze gentoo
Froze 1 filesystem(s)

virsh # domfsfreeze gentoo
error: Unable to freeze filesystems
error: internal error: unable to execute QEMU agent command 'guest-fsfreeze-freeze': The command guest-fsfreeze-freeze has been disabled for this instance

virsh # domfsfreeze gentoo
Froze 1 filesystem(s)

virsh # domfsfreeze gentoo
error: Unable to freeze filesystems
error: internal error: unable to execute QEMU agent command 'guest-fsfreeze-freeze': The command guest-fsfreeze-freeze has been disabled for this instance

Upgrading to a newer version fixes this.


text:
Q: How to limit upper bound of enum classes? I have an interface look like this.
interface MyEnum<E extends Enum<E> & MyEnum<E>> {

    static <E extends Enum<E> & MyEnum<E, T>, T> E valueOfAttribute(
            Class<E> enumClass, T attributeValue) {
        for (final E enumConstant : enumClass.getEnumConstants()) {
            if (Objects.equals(enumConstant.attribute(), attributeValue)) {
                return enumConstant;
            }
        }
        throw new IllegalArgumentException(
                "no enum constant, from " + enumClass
                + ", for " + attributeValue);
    }

    T attribute();
}

And let us all say that I have the following classes.
interface YourEnum<E extends YourEnum<E> & YourEnum<E>>
        extends MyEnum<E, String> {

    @Override public String attribute() { return ((Enum<?>) this).name(); }
}

enum HisEnum implements YourEnum<HisEnum> {
    HIS
}

enum HerEnum implements YourEnum<HerEnum> {
    HER
}

And I want to add another utility class for finding the enum constant matches to specific attribute value among one or more enum classes implements same subtype of MyEnum.
// should find HisEnum#HIS
MyEnum.<YourEnum>valueOfAttribute("HIS", HisEnum.class, HerEnum.class);

How can I add a static utility method which finds the first enum constant whose attribute() matches to specified value, from one or more enum classes extends a specific sub-interface of MyEnum?
I'm, so far, trying with this.
    // TODO: Scream!
    static <T extends MyEnum<? extends Enum<?>, U>, U> T valueOfAttribute(
            U attributeValue, Class<? extends T> enumClass,
            Class<? extends T>... otherEnumClasses) {
        return Stream.concat(Stream.of(enumClass), Stream.of(otherEnumClasses))
                .map(t -> {
                    try {
                        return valueOfAttribute(t, attributeValue); // won't compile
                    } catch (IllegalArgumentException iae) {
                        return null;
                    }
                })
                .filter(Objects::nonNull)
                .findFirst()
                .orElseThrow(() -> new IllegalArgumentException(
                        "no enum constant, from " + enumClass + "
                        + and " + Arrays.toString(otherEnumClasses)
                        + ", for " + attributeValue));
    }


text:
Q: System.IO.IOException: The file exists When Moving File I've recently taken over some code from a colleague that has left the company. I plan to rewrite the code from scratch, but in the meantime I'm wondering about the following crash the program had when running automatically overnight:
System.IO.IOException: The file exists.

at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.__Error.WinIOError()
at System.IO.FileInfo.MoveTo(String destFileName)
at Rexel_XML_Generator.Program.ProcessFiles(List`1 pdfFiles, List`1 files, CsvForXml csv, Dictionary`2 csvDictionary)
at Rexel_XML_Generator.Program.Main()

Obviously the program seems to have crashed because the file seems to already exist, but i dont see how it can do.
I've read about this error when windows exceeds the amount of temporary files it can have, but i dont think any temp files are being created. I've narrowed it down and found the code where the crash is.
The folder it is moving to is a dated folder for each run, so i dont think it was already there.
foreach (var pdFfile in pdfFiles)
        {
            var filename = pdFfile;

            // Copy to processing folder
            filename.CopyTo(ProcessingFolder + filename, true);

            //Copy to the Aroura server
            if (!Testing)
            {
                filename.CopyTo(@"\\89.1.1.233\AURINPUT\PDF_Archive\" + filename, true);
            }

            //Move to processed

            filename.MoveTo(TodaysFolder + @"\Data Processed\" + filename);
        }

If there was an error with this code, i'd expect it to crash most days? But this is the first occurrence of such a crash to my knowledge. Does anyone see how this crash could come to be?

Update 10/09/19
This hasn't reoccured which makes me think the issue lies outside of the code?
I've done a bit more digging and found this log file
[2019-08-21 04:17:52] system crashed error is System.IO.IOException: The file exists.

at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.__Error.WinIOError()
at System.IO.FileInfo.MoveTo(String destFileName)
at Rexel_XML_Generator.Program.ProcessFiles(List`1 pdfFiles, List`1 files, CsvForXml csv, Dictionary`2 csvDictionary)
at Rexel_XML_Generator.Program.Main()

Which seems to be the same error as above from the event viewer
the ENTIRE program is in a try catch loop, and when it finds an error it does this:
 LogDataToFile.LogData($"system crashed error is {e}");
 LogDataToFile.CloseConnection();

which does
 public static void LogData(string message)
    {
        _writer.WriteLine($"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] " + message);
        Console.WriteLine(message);
    }

    public static void CloseConnection()
    {
        _writer.Close();
    }