问:
Xceed -> Arithmetic operation resulted in an overflow
I have an application that uses some Xceed libraries and we are starting to deploy it on Windows 7.  The problem is with the WinComboBox object: if I use the scroll wheel on the mouse and scroll down/"past" the bottom of the list REALLY FAST (it has to be fast, going slow or using the keyboard will not trigger this) then I get this error.

```<code>Unhandled exception occured in ->Arithmetic operation resulted in an overflow.>>>
at Xceed.Editors.ComboBoxTextBoxArea.WndProc(Message& m)[0Dh][0Ah]
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)[0Dh][0Ah]
at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
</code>```

I know what the error means, but I can't figure out where it is occurring or how to pinpoint what is happening.

This only happens with the Windows 7 machines (never had a problem on any XP systems) and is easy to reproduce... it is even reproducible with the Xceed example/demo apps, so that's how I figure the problem is in their code.  Unfortunately I do not have the source for Xceed, and we are two versions behind, but I was hoping that maybe somebody else has already dealt with this or has an idea.  I've tried to override several methods where I thought the error might be, but no success.

Thanks in advance.

答:
I had the same problem using a System.Windows.Forms.ComboBox on my Windows 7 64bit OS.  By making the project run in 32bit mode instead of 64bit mode, the problem went away:

Using Visual Studio 2008

1. Right click on startup project and click Properties

2. Click on Build in the left side bar

3. Change the value in Platform target to x86

Body:
I have an application that uses some Xceed libraries and we are starting to deploy it on Windows 7.  The problem is with the WinComboBox object: if I use the scroll wheel on the mouse and scroll down/"past" the bottom of the list REALLY FAST (it has to be fast, going slow or using the keyboard will not trigger this) then I get this error.

Unhandled exception occured in ->Arithmetic operation resulted in an overflow.>>>
at Xceed.Editors.ComboBoxTextBoxArea.WndProc(Message& m)[0Dh][0Ah]
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)[0Dh][0Ah]
at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)

I know what the error means, but I can't figure out where it is occurring or how to pinpoint what is happening.

This only happens with the Windows 7 machines (never had a problem on any XP systems) and is easy to reproduce... it is even reproducible with the Xceed example/demo apps, so that's how I figure the problem is in their code.  Unfortunately I do not have the source for Xceed, and we are two versions behind, but I was hoping that maybe somebody else has already dealt with this or has an idea.  I've tried to override several methods where I thought the error might be, but no success.

Thanks in advance.


来源: stackexchange

问:
Lookup table for load cell calibration doesn't like negative numbers
I have a load cell connected to an HX711 which all works fine. I am attempting to create a calibration table with 10 points holding the raw sensor output and the calibrated value using a set of weights. The load cell is bi-directional so it works in any direction so the output is positive and negative counts but the zero is not necessarily 0 output.

This all works fine when the numbers are all positive or all negative in each lookup table but fails when there is negative & positive numbers in the captured points. Eg, the output from the HX711 is positive 28,000 with no load. Add a load of 1kg and get a reading of -56,000. The next reading for 1Kg is say, -83,000. These are stored as {28,000, -56000, 83,000} in an array with the the calibrated {0, 1, 2} in another array.

Normally I interpolate the result based on finding which 2 numbers the raw count falls between. Everything works when the numbers are less than -56,000 and I get readings of 1 to 2kg. When the reading is greater than -56,000, it fails to calculate the reading and I end up with NAN.

It can also be the other way around with negative and then positive. (-56,000, 28,000, 55,000} for example.

How to handle this situation?

答: I worked this out not long after I posted the question and thought that the answer would help anyone else with this same issue. By comparing the 2 values for negative or positive as I stepped through the table and then swapping them around in the calculation, it works. The difference between 28,000 and -56,000 comes out as 84,000 and using this to do the maths works. I confirmed operation by applying 1kg and 2kd test loads. It reads in both directions pos or neg. </p>

ContentLicense: CC BY-SA 4.0


问:
How to avoid Image Area showing Blue before Loading App
I am loading a rectangle logo saved as a .jpg into a CircleAvatar in my App.

When I am restarting my App, the area where the logo is loading appears blue for a few seconds. Then the real logo appears.

This Widget is found within a Stack.

This is how I transform my 1080x1073 image into a round logo within Flutter.

```<code> Container(
                width: size.width * 0.5,
                height: size.width * 0.5,
                child: CircleAvatar(
                  backgroundImage: AssetImage('assets/images/logo.jpg'),
                ),
              ),
</code>```

Does this happen because my image is too big? How should I handle this problem?

P.S. I am testing this on Visual Studio Code.

答:
This has more to do with the delay it takes to load an image. You can change the background color like Yudhishthir suggested if the color is the actual problem or you can pre-fetch the image so that the image loads before anything is built.

This answer describes how to do the image pre-fetch using the precacheImage function.

Body:
I am loading a rectangle logo saved as a .jpg into a CircleAvatar in my App.

When I am restarting my App, the area where the logo is loading appears blue for a few seconds. Then the real logo appears.

This Widget is found within a Stack.

This is how I transform my 1080x1073 image into a round logo within Flutter.

 Container(
                width: size.width * 0.5,
                height: size.width * 0.5,
                child: CircleAvatar(
                  backgroundImage: AssetImage('assets/images/logo.jpg'),
                ),
              ),

Does this happen because my image is too big? How should I handle this problem?

P.S. I am testing this on Visual Studio Code.


问:
Multiple threads with infinite loop and thread.sleep high CPU usage
In my console application I have some threads and each thread have an infinite loop with a Thread.Sleep.
Have many threads because each one is independent from others.
Each cycle is run every waitingTime time and I want that never stops.

```<code>static int waitingTime= 5 * 60 * 1000;

static void Main(string[] args)
{
    Thread thread1 = new Thread(() => Thread1());
    Thread thread2 = new Thread(() => Thread2());
    Thread thread3 = new Thread(() => Thread3());
    ...
    thread1.Start();
    thread2.Start();
    thread3.Start();
    ...
}

static void Thread1()
{
      do
      {
          // Connect to DB and do something...
          try
          {
              using (SqlConnection connection = MyDBClass.MyDBConnection())
              {
                  connection.Open();
                  SqlCommand command = connection.CreateCommand();
                  command.CommandText = "SELECT x, y FROM Table WITH (NOLOCK);";
                  SqlDataReader sdr = command.ExecuteReader();
                  while (sdr.Read())
                  {
                      MyObject obj = new MyObject(sdr[0] as string, ...);
                      MyStaticClass.SetMyObject(obj); // Open a new DB connection on different server and do an Update.
                  }
                  sdr.Close();
                  sdr.Dispose();
              }
          }
          catch
          {
          }

          Thread.Sleep(waitingTime);
      }
      while (true);
 }

static void Thread2()
{
     do
     {
        // Connect to DB and do something...
        Thread.Sleep(waitingTime);
     }
     while (true);
 }

...
</code>```

I have read that is not good use Thread.Sleep() in cases like this and is suposes use solutions like EventWaitHandle.
What is the best solution for this case and how to implement that.

答: A thread that is sleeping with Thread.Sleep() consumes zero CPU resources, so trying to improve on this using EventWaitHandle primitives or other means is pointless. You can't beat zero. What you could improve is the RAM consumed by the threads, which is 1 MB for their stack, plus the memory they allocate on the heap (which depends on what they do while working). So by using a single thread instead of three you could reduce the RAM consumption by 2 MB or more, which for a console app running on a modern PC is practically nothing. So I wouldn't be concerned about it in your place.

Body:
In my console application I have some threads and each thread have an infinite loop with a Thread.Sleep.
Have many threads because each one is independent from others.
Each cycle is run every waitingTime time and I want that never stops.

static int waitingTime= 5 * 60 * 1000;

static void Main(string[] args)
{
    Thread thread1 = new Thread(() => Thread1());
    Thread thread2 = new Thread(() => Thread2());
    Thread thread3 = new Thread(() => Thread3());
    ...
    thread1.Start();
    thread2.Start();
    thread3.Start();
    ...
}

static void Thread1()
{
      do
      {
          // Connect to DB and do something...
          try
          {
              using (SqlConnection connection = MyDBClass.MyDBConnection())
              {
                  connection.Open();
                  SqlCommand command = connection.CreateCommand();
                  command.CommandText = "SELECT x, y FROM Table WITH (NOLOCK);";
                  SqlDataReader sdr = command.ExecuteReader();
                  while (sdr.Read())
                  {
                      MyObject obj = new MyObject(sdr[0] as string, ...);
                      MyStaticClass.SetMyObject(obj); // Open a new DB connection on different server and do an Update.
                  }
                  sdr.Close();
                  sdr.Dispose();
              }
          }
          catch
          {
          }

          Thread.Sleep(waitingTime);
      }
      while (true);
 }

static void Thread2()
{
     do
     {
        // Connect to DB and do something...
        Thread.Sleep(waitingTime);
     }
     while (true);
 }

...

I have read that is not good use Thread.Sleep() in cases like this and is suposes use solutions like EventWaitHandle.
What is the best solution for this case and how to implement that.


问:
Tensorflow Keras: Training Holting on model.fit()
I am new to tensorflow and python, so I'm sure its just something stupid. But when I try to train my model with model.fit(), after a random number of training iterations it freezes. GPU usage goes to zero, and no error message is shown to indicate where the error is. The model I am trying to train is as follows:

```<code>SizeOfInput = 50
VocabSize = 8000
EmbeddingSize = 200

model = Sequential()
model.add(Embedding(input_dim=VocabSize, output_dim=EmbeddingSize, input_length=SizeOfInput))
model.add(LSTM(256, input_shape=(SizeOfInput, EmbeddingSize), return_sequences=True))
model.add(Dropout(0.1))
model.add(LSTM(256))
model.add(Dropout(0.1))
model.add(Dense(VocabSize, activation='softmax'))

optimizer = tf.keras.optimizers.RMSprop(lr=1e-3, decay=1e-5)
model.compile(loss='categorical_crossentropy', optimizer=optimizer)
</code>```

Tensorflow: 2.2.0

Python: 3.8

GPU: RTX2080Ti

I am training on 10000 randomly sampled sequences of 50 integers each epoch, from a larger dataset:

```<code>model.fit(x, y, batch_size=100, epochs=1)
</code>```

I really don't know what the issue is, let me know if you need more information

答:
1.Firstly please try your code in  Google Colab

2.Try to use another optimizer:

```<code>keras.layers.BatchNormalization._USE_V2_BEHAVIOR = False
</code>```

3.Maybe some ops running in cpu and some Ops are running in GPU.
In order to prevent it:

```<code>with tf.device("/device:GPU:0"):
    model.fit(x, y, batch_size=100, epochs=1)
</code>```

3.Update the latest version of

```<code>tf-nightly-gpu
tf-gpu 2.1 cudn 10.2
</code>```

4.Test this:

```<code>print(tf.version.VERSION, tf.executing_eagerly(), keras.layers.BatchNormalization._USE_V2_BEHAVIOR)

keras.layers.BatchNormalization._USE_V2_BEHAVIOR = False
</code>```

Body:
I am new to tensorflow and python, so I'm sure its just something stupid. But when I try to train my model with model.fit(), after a random number of training iterations it freezes. GPU usage goes to zero, and no error message is shown to indicate where the error is. The model I am trying to train is as follows:

SizeOfInput = 50
VocabSize = 8000
EmbeddingSize = 200

model = Sequential()
model.add(Embedding(input_dim=VocabSize, output_dim=EmbeddingSize, input_length=SizeOfInput))
model.add(LSTM(256, input_shape=(SizeOfInput, EmbeddingSize), return_sequences=True))
model.add(Dropout(0.1))
model.add(LSTM(256))
model.add(Dropout(0.1))
model.add(Dense(VocabSize, activation='softmax'))

optimizer = tf.keras.optimizers.RMSprop(lr=1e-3, decay=1e-5)
model.compile(loss='categorical_crossentropy', optimizer=optimizer)

Tensorflow: 2.2.0

Python: 3.8

GPU: RTX2080Ti

I am training on 10000 randomly sampled sequences of 50 integers each epoch, from a larger dataset:

model.fit(x, y, batch_size=100, epochs=1)

I really don't know what the issue is, let me know if you need more information

Body:
1.Firstly please try your code in  Google Colab

2.Try to use another optimizer:

keras.layers.BatchNormalization._USE_V2_BEHAVIOR = False

3.Maybe some ops running in cpu and some Ops are running in GPU.
In order to prevent it:

with tf.device("/device:GPU:0"):
    model.fit(x, y, batch_size=100, epochs=1)

3.Update the latest version of

tf-nightly-gpu
tf-gpu 2.1 cudn 10.2

4.Test this:

print(tf.version.VERSION, tf.executing_eagerly(), keras.layers.BatchNormalization._USE_V2_BEHAVIOR)

keras.layers.BatchNormalization._USE_V2_BEHAVIOR = False


问:
read with SAxParser
hi everyone I  try to read the information of this direction

http://finance.yahoo.com/d/quotes.csv?s=XOM+BBDb.TO+JNJ+MSFT&f=snd1l1yr

```<code>    SAXParserFactory factory= SAXParserFactory.newInstance();
    try {
        SAXParser parser= factory.newSAXParser();
        RssHandler handler= new RssHandler();
        parser.parse(this.getInputStream(), handler);
        return handler.getQuotes();

    } catch (Exception e) {
        throw new RuntimeException(e);
    }
</code>```

but I have this error

not well-formed (invalid token)

if I put this direction http://finance.yahoo.com/rss/headline?s=yhoo the application works well, but I need read the other direction.

any idea!!!
thanks in advance.

答:
The first URL contains something like this:

```<code>"XOM","Exxon Mobil Corpo","6/1/2011",82.03,2.14,11.89
"BBD-B.TO","BOMBARDIER INC., ","6/1/2011",6.95,1.11,16.07
"JNJ","Johnson & Johnson","6/1/2011",66.48,3.25,15.26
"MSFT","Microsoft Corpora","6/1/2011",24.43,2.44,9.94
</code>```

which is CSV (comma-separated values) formatted data.

CSV is not a valid RSS feed format. It's not even XML.

ContentLicense: CC BY-SA 3.0

Title: read with SAxParser

Body:
hi everyone I  try to read the information of this direction

http://finance.yahoo.com/d/quotes.csv?s=XOM+BBDb.TO+JNJ+MSFT&f=snd1l1yr

    SAXParserFactory factory= SAXParserFactory.newInstance();
    try {
        SAXParser parser= factory.newSAXParser();
        RssHandler handler= new RssHandler();
        parser.parse(this.getInputStream(), handler);
        return handler.getQuotes();

    } catch (Exception e) {
        throw new RuntimeException(e);
    }

but I have this error

not well-formed (invalid token)

if I put this direction http://finance.yahoo.com/rss/headline?s=yhoo the application works well, but I need read the other direction.

any idea!!!
thanks in advance.

Body:
The first URL contains something like this:

"XOM","Exxon Mobil Corpo","6/1/2011",82.03,2.14,11.89
"BBD-B.TO","BOMBARDIER INC., ","6/1/2011",6.95,1.11,16.07
"JNJ","Johnson & Johnson","6/1/2011",66.48,3.25,15.26
"MSFT","Microsoft Corpora","6/1/2011",24.43,2.44,9.94

which is CSV (comma-separated values) formatted data.

CSV is not a valid RSS feed format. It's not even XML.


问:
Not able to start the docker container for postfix
I am getting the below error when i try to run the docker container for postfix

```<code>2020-05-29 08:49:05,837 CRIT Supervisor is running as root.  Privileges were not dropped because no user is specified in the config file.  If you intend to run as root, you can set user=root in the config file to avoid this message.
2020-05-29 08:49:05,837 INFO Included extra file "/etc/supervisor/conf.d/supervisord.conf" during parsing
2020-05-29 08:49:05,844 INFO RPC interface 'supervisor' initialized
2020-05-29 08:49:05,844 CRIT Server 'unix_http_server' running without any HTTP authentication checking
2020-05-29 08:49:05,844 INFO supervisord started with pid 17
2020-05-29 08:49:06,852 INFO spawned: 'postfix' with pid 19
2020-05-29 08:49:06,856 INFO spawnerr: can't find command 'rsyslogd'
2020-05-29 08:49:07,167 INFO exited: postfix (exit status 1; not expected)
2020-05-29 08:49:08,172 INFO spawned: 'postfix' with pid 136
2020-05-29 08:49:08,174 INFO spawnerr: can't find command 'rsyslogd'
2020-05-29 08:49:08,219 INFO exited: postfix (exit status 1; not expected)
2020-05-29 08:49:10,230 INFO spawned: 'postfix' with pid 151
2020-05-29 08:49:10,233 INFO spawnerr: can't find command 'rsyslogd'
2020-05-29 08:49:10,274 INFO exited: postfix (exit status 1; not expected)
2020-05-29 08:49:13,283 INFO spawned: 'postfix' with pid 166
2020-05-29 08:49:13,286 INFO spawnerr: can't find command 'rsyslogd'
2020-05-29 08:49:13,286 INFO gave up: rsyslog entered FATAL state, too many start retries too quickly
2020-05-29 08:49:13,325 INFO exited: postfix (exit status 1; not expected)
2020-05-29 08:49:14,330 INFO gave up: postfix entered FATAL state, too many start retries too quickly
</code>```

The block corresponding to the above is

```<code>command=/usr/sbin/rsyslogd -n -c3
</code>```

Kindly help

Thanks,
Suv

答:
Please provide the container config you are using to run.

Coming to what I understood was, I guess rsyslog is not installed in the container, so please install it before using it. If you are on a Debian or ubuntu container use the below commands to install it in the container.

add-apt-repository ppa:adiscon/v8-stable
apt-get install rsyslog
```

<p>In dockerfile:</p>

<pre class="lang-sh prettyprint-override"><code>RUN add-apt-repository ppa:adiscon/v8-stable && \
apt-get -y install rsyslog
</code>```

Body:
I am getting the below error when i try to run the docker container for postfix

2020-05-29 08:49:05,837 CRIT Supervisor is running as root.  Privileges were not dropped because no user is specified in the config file.  If you intend to run as root, you can set user=root in the config file to avoid this message.
2020-05-29 08:49:05,837 INFO Included extra file "/etc/supervisor/conf.d/supervisord.conf" during parsing
2020-05-29 08:49:05,844 INFO RPC interface 'supervisor' initialized
2020-05-29 08:49:05,844 CRIT Server 'unix_http_server' running without any HTTP authentication checking
2020-05-29 08:49:05,844 INFO supervisord started with pid 17
2020-05-29 08:49:06,852 INFO spawned: 'postfix' with pid 19
2020-05-29 08:49:06,856 INFO spawnerr: can't find command 'rsyslogd'
2020-05-29 08:49:07,167 INFO exited: postfix (exit status 1; not expected)
2020-05-29 08:49:08,172 INFO spawned: 'postfix' with pid 136
2020-05-29 08:49:08,174 INFO spawnerr: can't find command 'rsyslogd'
2020-05-29 08:49:08,219 INFO exited: postfix (exit status 1; not expected)
2020-05-29 08:49:10,230 INFO spawned: 'postfix' with pid 151
2020-05-29 08:49:10,233 INFO spawnerr: can't find command 'rsyslogd'
2020-05-29 08:49:10,274 INFO exited: postfix (exit status 1; not expected)
2020-05-29 08:49:13,283 INFO spawned: 'postfix' with pid 166
2020-05-29 08:49:13,286 INFO spawnerr: can't find command 'rsyslogd'
2020-05-29 08:49:13,286 INFO gave up: rsyslog entered FATAL state, too many start retries too quickly
2020-05-29 08:49:13,325 INFO exited: postfix (exit status 1; not expected)
2020-05-29 08:49:14,330 INFO gave up: postfix entered FATAL state, too many start retries too quickly

The block corresponding to the above is

command=/usr/sbin/rsyslogd -n -c3

Kindly help

Thanks,
Suv

Body:
Please provide the container config you are using to run.

Coming to what I understood was, I guess rsyslog is not installed in the container, so please install it before using it. If you are on a Debian or ubuntu container use the below commands to install it in the container.

add-apt-repository ppa:adiscon/v8-stable
apt-get install rsyslog

In dockerfile:

RUN add-apt-repository ppa:adiscon/v8-stable && \
apt-get -y install rsyslog


问:
ggplot created in shiny app does not recognize column name
I am working on a shiny app that is supposed to enable the user to load data from an excel file and to create some graphs based on this data. To do this I use read.xlsx and ggplot. The user can select the x variable input$x and y variable input$y from a list. This list is created based on the column names of the data set. Based on the input a graph is created:

```<code>ggplot() +  geom_point(data=mydata, aes_string(x=input$x, y=input$y)
</code>```

However, when some of the columns of my example dataset are chosen, I get an error. For instance, when i select the y variable to be equal to the AB (m/s), I get the following error:

```<code>Error: could not find function "AB"
</code>```

The ggplot somehow does not recognize the special characters and only takes the first part of the column name. Is there a way to solve this?

答:
Thank you for the nice suggestion fra. Eventually i have solved it like this: </p>

```<code>x<-paste0("`",input$x,"`")
y<-paste0("`",input$y,"`")
ggplot() +  geom_point(data=mydata, aes_string(x=x, y=y)
</code>```

Body:
I am working on a shiny app that is supposed to enable the user to load data from an excel file and to create some graphs based on this data. To do this I use read.xlsx and ggplot. The user can select the x variable input$x and y variable input$y from a list. This list is created based on the column names of the data set. Based on the input a graph is created:

ggplot() +  geom_point(data=mydata, aes_string(x=input$x, y=input$y)

However, when some of the columns of my example dataset are chosen, I get an error. For instance, when i select the y variable to be equal to the AB (m/s), I get the following error:

Error: could not find function "AB"

The ggplot somehow does not recognize the special characters and only takes the first part of the column name. Is there a way to solve this?

Body:
Thank you for the nice suggestion fra. Eventually i have solved it like this:

x<-paste0("`",input$x,"`")
y<-paste0("`",input$y,"`")
ggplot() +  geom_point(data=mydata, aes_string(x=x, y=y)


问:
Gradle sync failed: Unable to find method after update to Gradle 4.0.0
I updated gradle to 4.0.0

```<code>classpath 'com.android.tools.build:gradle:4.0.0'
</code>```

and the distributionUrl to:

```<code>distributionUrl=https\://services.gradle.org/distributions/gradle-6.1.1-all.zip
</code>```

after sync the prject I got:

Unable to find method 'org.gradle.api.tasks.TaskInputs.property(Ljava/lang/String;Ljava/lang/Object;)Lorg/gradle/api/tasks/TaskInputs;'.

I know, if I downgrade the version the project will sync properly. but is there some incompatibility somewhere ? if it's true why there is some updates ?

答:
This may be because of any 3rd party Gradle plugin not supporting the new Tasks API. In my case it was because of greendao Gradle plugin.

If you are using greendao update it to the latest version 3.3.0:

```<code>classpath 'org.greenrobot:greendao-gradle-plugin:3.3.0'
</code>```

Or else you will have to find the plugin that is causing the issue.

Body:
I updated gradle to 4.0.0

classpath 'com.android.tools.build:gradle:4.0.0'

and the distributionUrl to:

distributionUrl=https\://services.gradle.org/distributions/gradle-6.1.1-all.zip

after sync the prject I got:

Unable to find method 'org.gradle.api.tasks.TaskInputs.property(Ljava/lang/String;Ljava/lang/Object;)Lorg/gradle/api/tasks/TaskInputs;'.

I know, if I downgrade the version the project will sync properly. but is there some incompatibility somewhere ? if it's true why there is some updates ?

Body:
This may be because of any 3rd party Gradle plugin not supporting the new Tasks API. In my case it was because of greendao Gradle plugin.

If you are using greendao update it to the latest version 3.3.0:

classpath 'org.greenrobot:greendao-gradle-plugin:3.3.0'

Or else you will have to find the plugin that is causing the issue.


问:
Send List<T> as an optional parameter in the post body in ASP.NET Core Web Api
I had this model which was taking optional params for a post request body:

```<code> public class ReportFilterModel
{

    public int? ReportStatusId { get; set; }
    public Guid? AreaID { get; set; }
}
</code>```

This would do a search in DB according to the filters given by user:

```<code> var report = _context.tbl_Reports.AsQueryable();

                if (model.ReportStatusId.IsNotNull())
                    report = report.Where(x => x.IsDeleted == false && x.ReportStatusId == (StatusEnum)model.ReportStatusId.Value);

                if (model.Area.IsNotNull())
                    report = report.Where(x => x.IsDeleted == false && x.Area.Id == model.AreaId);
</code>```

And then it'd finally return this:

```<code> finalReports = await report
                    .Where(x => x.IsDeleted == false)
                    .Select(x => new ReportsWithFiltersModel
                    {
                        Id = x.Id,

                        Area = Id,
                        UserId = x.UserId,
                        ReportStatus = x.ReportStatusId.GetEnumDescription(),

                    }).ToListAsync();
</code>```

All this working absolutely fine, but now I want to give a list of optional params like this:

```<code>public class ReportFilterModel
{

    public List<int>? ReportStatusId { get; set; }
    public List<Guid>? AreaID { get; set; }
}
</code>```

This is giving an exception

```<code>'List<int>' does not contain a definition for 'Value' and no accessible extension method 'Value' accepting a first argument of type 'List<int>' could be found (are you missing a using directive or an assembly reference?)
</code>```

How do I fix this?

答:
? Does not stand for optional. It means Nullable where T is value type (It applies to value types and makes them nullable).

Reference types, such as Lists are already nullable.

```<code>List<int> x = null; //valid version of what you are trying to achieve with List<int>?

int? or Nullable<int> //valid
List<int?> x or List<Nullable<int>> ; //valid
</code>```

Body:
I had this model which was taking optional params for a post request body:

 public class ReportFilterModel
{

    public int? ReportStatusId { get; set; }
    public Guid? AreaID { get; set; }
}

This would do a search in DB according to the filters given by user:

 var report = _context.tbl_Reports.AsQueryable();

                if (model.ReportStatusId.IsNotNull())
                    report = report.Where(x => x.IsDeleted == false && x.ReportStatusId == (StatusEnum)model.ReportStatusId.Value);

                if (model.Area.IsNotNull())
                    report = report.Where(x => x.IsDeleted == false && x.Area.Id == model.AreaId);

And then it'd finally return this:

 finalReports = await report
                    .Where(x => x.IsDeleted == false)
                    .Select(x => new ReportsWithFiltersModel
                    {
                        Id = x.Id,

                        Area = Id,
                        UserId = x.UserId,
                        ReportStatus = x.ReportStatusId.GetEnumDescription(),

                    }).ToListAsync();

All this working absolutely fine, but now I want to give a list of optional params like this:

public class ReportFilterModel
{

    public List<int>? ReportStatusId { get; set; }
    public List<Guid>? AreaID { get; set; }
}

This is giving an exception

'List<int>' does not contain a definition for 'Value' and no accessible extension method 'Value' accepting a first argument of type 'List<int>' could be found (are you missing a using directive or an assembly reference?)

How do I fix this?

Body:
? Does not stand for optional. It means Nullable where T is value type (It applies to value types and makes them nullable).

Reference types, such as Lists are already nullable.

List<int> x = null; //valid version of what you are trying to achieve with List<int>?

int? or Nullable<int> //valid
List<int?> x or List<Nullable<int>> ; //valid


问:
How can I show specific texts inside a div by the click of a button?
I have a small text translated in 3 languages. I am looking to show the first text in English, and above the text to show two buttons, one that says French and one that says Italian. And I want once you click on French, to display the text in French, and the same with Italian. This means that I will have three separate divs, one for English, one for French and one for Italian. I only want to show one of them on the page, depending on which button I click. How can I do that? Thanks</p>

答:
All you need to do is create a relation between button and your desired div, and then show the related div only on click and hide the others, in my code you can increase and decrease the div's, no need to touch the jQuery or CSS code, just add or remove div's from HTML

$(document).ready(function(){
        $('.btnWrapper button').click(function(){
            $('.btnWrapper button').removeClass('active');
            $(this).addClass('active');
            var realtion = $(this).data('relation');
            $('.translatedText>div').removeClass('active');
            $('.translatedText').find('#' + realtion).addClass('active');
        });

    });```
<pre class="snippet-code-css lang-css prettyprint-override"><code> .btnWrapper button.active {
            background-color: red;
            color: #fff;
        }
        .translatedText > div {
            display: none;
        }
        .translatedText > div.active {
            display: block;
        }</code>```

        <button class="active" data-relation="eng">English</button>
        <button data-relation="fre">French</button>
        <button data-relation="ita">Italian</button>

            I am English's Div

            I am French's Div

            I am Italian's Div

```

Body:
All you need to do is create a relation between button and your desired div, and then show the related div only on click and hide the others, in my code you can increase and decrease the div's, no need to touch the jQuery or CSS code, just add or remove div's from HTML

$(document).ready(function(){
        $('.btnWrapper button').click(function(){
            $('.btnWrapper button').removeClass('active');
            $(this).addClass('active');
            var realtion = $(this).data('relation');
            $('.translatedText>div').removeClass('active');
            $('.translatedText').find('#' + realtion).addClass('active');
        });

    });

 .btnWrapper button.active {
            background-color: red;
            color: #fff;
        }
        .translatedText > div {
            display: none;
        }
        .translatedText > div.active {
            display: block;
        }

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="btnWrapper">
        <button class="active" data-relation="eng">English</button>
        <button data-relation="fre">French</button>
        <button data-relation="ita">Italian</button>
    </div>
    <div class="translatedText">
        <div id="eng" class="active">
            I am English's Div
        </div>
        <div id="fre">
            I am French's Div
        </div>
        <div id="ita">
            I am Italian's Div
        </div>
    </div>


问:
CORS : No 'Access-Control-Allow-Origin' header is present on the requested resource
I am working on a D3 - grunt-cli application in which I am facing a CORS issue when sending post requests to a Fuseki Server.

```<code>function saveToFusekiFunc() {
    document.getElementById('fileid').click();
    document.getElementById('fileid').value = null;

    d3.select("#fileid").on("change", function() {
      var contents;
      var file = d3.select("#fileid").property("files")[0];
      console.log(file);
      var reader = new FileReader();
      reader.onload = function(e) {
      contents = e.target.result;
      console.log(contents);

    let xhr = new XMLHttpRequest();
    let url = "http://localhost:3030/Test/";

    xhr.open(
      "POST",
       url ,
      true
    );

    //xhr.setRequestHeader('Data-Type', 'jsonp');
    xhr.setRequestHeader('Content-Type', 'text/turtle;charset=utf-8');
    xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
    xhr.setRequestHeader('Access-Control-Allow-Methods', 'GET, POST, PATCH, PUT, DELETE, OPTIONS');
    xhr.setRequestHeader('Access-Control-Allow-Headers', 'Origin, Content-Type, X-Auth-Token');
    xhr.setRequestHeader('Access-Control-Allow-Origin', 'http://localhost:8000/');
    xhr.setRequestHeader('Access-Control-Max-Age', '86400');

    xhr.onreadystatechange = function()
    {
    if(xhr.readyState == 4 && xhr.status == 200) {
        alert(xhr.responseText);
    }
    }
    xhr.send(contents);
    };
    reader.readAsText(file);

    })

  }
</code>```

Above is my code with which I try to make the request. This only works if I enable the CORS plugin in my browser extension.

I have also tried to include the access by making changes to the gruntfile.js middlewares. But it did not help. From which I am almost sure that this is some issue at the server end.

My dependenices are as shown below:

```<code>"dependencies": {
    "d3": "^3.5.6",
    "grunt-cli": "^1.3.2",
    "lodash": "^4.1.0"
  }
</code>```

Have tried most of the solutions found online but nothing has worked other than directly blocking the CORS check in the browser. I am trying to make a request from 'http://localhost:8000/' to the Fuseki Server 'http://localhost:3030/'.

The error I am getting is:

```<code>Access to XMLHttpRequest at 'http://localhost:3030/Test/' from origin 'http://localhost:8000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
</code>```

Request headers:

Also checked the web.xml file of the Fuseki configuration which seems to have the CORS settings:

```<code><!-- CORS -->
  <filter>
    <filter-name>cross-origin</filter-name>
    <!-- Ported and standalone version of org.eclipse.jetty.servlets.CrossOriginFilter -->
    <filter-class>org.apache.jena.fuseki.servlets.CrossOriginFilter</filter-class>
    <!-- Defaults may be fine -->
    <init-param>
      <param-name>allowedOrigins</param-name>
      <param-value>*</param-value>
    </init-param>
    <init-param>
      <param-name>allowedMethods</param-name>
      <param-value>GET,POST,DELETE,PUT,HEAD,OPTIONS,PATCH</param-value>
    </init-param>
    <init-param>
      <param-name>allowedHeaders</param-name>
      <param-value>Accept, Origin, X-Requested-With, Content-Type, Last-Modified, Authorization</param-value>
    </init-param>
    <init-param>
      <param-name>exposedHeaders</param-name>
      <param-value>Access-Control-Allow-Origin,Access-Control-Allow-Credentials</param-value>
    </init-param>
  </filter>
</code>```

答:
For CORS to work, you have to enable it on the target server, so in this case, in your Fuseki server. From the Wikipedia doc on CORS:

Note that in the CORS architecture, the Access-Control-Allow-Origin header is being set by the external web service (service.example.com), not the original web application server (www.example.com). Here, service.example.com uses CORS to permit the browser to authorize www.example.com to make requests to service.example.com.

Here's a gist, although fair warning, I have not tried it on my server:
https://gist.github.com/danja/e8ecbf7e51f7a2616122

Body:
I am working on a D3 - grunt-cli application in which I am facing a CORS issue when sending post requests to a Fuseki Server.

function saveToFusekiFunc() {
    document.getElementById('fileid').click();
    document.getElementById('fileid').value = null;

    d3.select("#fileid").on("change", function() {
      var contents;
      var file = d3.select("#fileid").property("files")[0];
      console.log(file);
      var reader = new FileReader();
      reader.onload = function(e) {
      contents = e.target.result;
      console.log(contents);

    let xhr = new XMLHttpRequest();
    let url = "http://localhost:3030/Test/";

    xhr.open(
      "POST",
       url ,
      true
    );

    //xhr.setRequestHeader('Data-Type', 'jsonp');
    xhr.setRequestHeader('Content-Type', 'text/turtle;charset=utf-8');
    xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
    xhr.setRequestHeader('Access-Control-Allow-Methods', 'GET, POST, PATCH, PUT, DELETE, OPTIONS');
    xhr.setRequestHeader('Access-Control-Allow-Headers', 'Origin, Content-Type, X-Auth-Token');
    xhr.setRequestHeader('Access-Control-Allow-Origin', 'http://localhost:8000/');
    xhr.setRequestHeader('Access-Control-Max-Age', '86400');

    xhr.onreadystatechange = function()
    {
    if(xhr.readyState == 4 && xhr.status == 200) {
        alert(xhr.responseText);
    }
    }
    xhr.send(contents);
    };
    reader.readAsText(file);

    })

  }

Above is my code with which I try to make the request. This only works if I enable the CORS plugin in my browser extension.

I have also tried to include the access by making changes to the gruntfile.js middlewares. But it did not help. From which I am almost sure that this is some issue at the server end.

My dependenices are as shown below:

"dependencies": {
    "d3": "^3.5.6",
    "grunt-cli": "^1.3.2",
    "lodash": "^4.1.0"
  }

Have tried most of the solutions found online but nothing has worked other than directly blocking the CORS check in the browser. I am trying to make a request from 'http://localhost:8000/' to the Fuseki Server 'http://localhost:3030/'.

The error I am getting is:

Access to XMLHttpRequest at 'http://localhost:3030/Test/' from origin 'http://localhost:8000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Request headers:

Also checked the web.xml file of the Fuseki configuration which seems to have the CORS settings:

  <filter>
    <filter-name>cross-origin</filter-name>

    <filter-class>org.apache.jena.fuseki.servlets.CrossOriginFilter</filter-class>

    <init-param>
      <param-name>allowedOrigins</param-name>
      <param-value>*</param-value>
    </init-param>
    <init-param>
      <param-name>allowedMethods</param-name>
      <param-value>GET,POST,DELETE,PUT,HEAD,OPTIONS,PATCH</param-value>
    </init-param>
    <init-param>
      <param-name>allowedHeaders</param-name>
      <param-value>Accept, Origin, X-Requested-With, Content-Type, Last-Modified, Authorization</param-value>
    </init-param>
    <init-param>
      <param-name>exposedHeaders</param-name>
      <param-value>Access-Control-Allow-Origin,Access-Control-Allow-Credentials</param-value>
    </init-param>
  </filter>


问:
Wix installer refresh page after custom action
I am looking for way to refresh current page after custom action.

My code

```<code><Control Id="Config" Type="PushButton" .../>
    <Publish Event="DoAction" Value="SetConfiguration"></Publish>
</Control>
</code>```

It can be after custom action, but I don't see that Session has such an opportunity, or just adding some Event to Control that will work.

Edit:

Ok I have somethink like this:

```<code><Control Id="Config" Type="PushButton" X="120" Y="243" Width="56" Height="17" Default="yes" Text="Config" >
   <Publish Event="DoAction" Value="SetConfiguration" Order="1"></Publish>
   <Condition Action="disable">EndConfig = "true"</Condition>
   <Condition Action="enable">EndConfig = "false"</Condition>
   <Publish Event="NewDialog" Value="IISconfiguration2">EndConfig="true</Publish>
</Control>
</code>```

But how to create NewDialog after return result custom acion. Because it now do it in this same time. Set order on 1 and 2 dont work.

答:
Try this</p>

```<code><Control Id="Config" Type="PushButton" X="120" Y="243" Width="56" Height="17" Default="yes" Text="Config" >
    <Publish Event="DoAction" Value="SetConfiguration">1</Publish>
    <Condition Action="disable">EndConfig = "true"</Condition>
    <Condition Action="enable">EndConfig = "false"</Condition>
    <Publish Event="NewDialog" Value="IISconfiguration2">2</Publish>
</Control>
</code>```

Body:
I am looking for way to refresh current page after custom action.

My code

<Control Id="Config" Type="PushButton" .../>
    <Publish Event="DoAction" Value="SetConfiguration"></Publish>
</Control>

It can be after custom action, but I don't see that Session has such an opportunity, or just adding some Event to Control that will work.

Edit:

Ok I have somethink like this:

<Control Id="Config" Type="PushButton" X="120" Y="243" Width="56" Height="17" Default="yes" Text="Config" >
   <Publish Event="DoAction" Value="SetConfiguration" Order="1"></Publish>
   <Condition Action="disable">EndConfig = "true"</Condition>
   <Condition Action="enable">EndConfig = "false"</Condition>
   <Publish Event="NewDialog" Value="IISconfiguration2">EndConfig="true</Publish>
</Control>

But how to create NewDialog after return result custom acion. Because it now do it in this same time. Set order on 1 and 2 dont work.

Body:
Try this

<Control Id="Config" Type="PushButton" X="120" Y="243" Width="56" Height="17" Default="yes" Text="Config" >
    <Publish Event="DoAction" Value="SetConfiguration">1</Publish>
    <Condition Action="disable">EndConfig = "true"</Condition>
    <Condition Action="enable">EndConfig = "false"</Condition>
    <Publish Event="NewDialog" Value="IISconfiguration2">2</Publish>
</Control>


问:
Android(Kotlin) Toast using Elvis Operator to use a Default String value when value from intent/arguments is Null
I have this kind of implementation

```<code>Toast.makeText(activity,arguments?.get("message") as String, Toast.LENGTH_SHORT).show()
</code>```

So, the thing is I want to make the use of Elvis Operator(?:) here, so as to use some default String, when the value to show inside toast is Null.
I could not implement it properly. So, How do I implement it in the same line of code ??.
Also, what will be the better way to do it ??
Thanks.

答:
Probably something like this

```<code>Toast.makeText(activity,arguments!!.get("message") ?: "default", Toast.LENGTH_SHORT).show()
</code>```

When ? is used it just ignores the null, but on !! one has to handle the fallback.

Body:
I have this kind of implementation

Toast.makeText(activity,arguments?.get("message") as String, Toast.LENGTH_SHORT).show()

So, the thing is I want to make the use of Elvis Operator(?:) here, so as to use some default String, when the value to show inside toast is Null.
I could not implement it properly. So, How do I implement it in the same line of code ??.
Also, what will be the better way to do it ??
Thanks.

Body:
Probably something like this

Toast.makeText(activity,arguments!!.get("message") ?: "default", Toast.LENGTH_SHORT).show()

When ? is used it just ignores the null, but on !! one has to handle the fallback.


问:
javascript draw image into html from buffer (nodejs/socket.io)
(sorry for my english)
Hi, i have an appplication created with nodejs to push image data into a webpage.

the data from nodejs server is pushed into webpage using socket.io

This data is the complete image, i try to write to disc to see the image and is good.
The data is put into a buffer to encode in base64 then send to the webpage and i try to show using
'data:image/png;base64,'+data
but nothing happend... The data seems to be "complete" including the headers of the PNG image.

The server use thrift to communicate with another client (this in C++), this client create the images and send to the nodejs-thrift server, when a image is receive, the nodejs-socket.io server push into webpage.

some code:
serverside

```<code>var http = require('http'),
url = require('url'),
fs  = require('fs'),
sys = require('sys');
var hserver = http.createServer(function(request,response){
var path = url.parse(request.url).pathname;
switch(path){
   case '/':

        fs.readFile(__dirname + '/index.html',function(err,data){
           if(err) return send404(res);
           response.writeHead(200,{'Content-Type':'text/html'});
           response.write(data,'utf8');
           response.end();
        });
    break;
    default: send404(response);
}
   }),
send404 = function(res){
 res.writeHead(404);
 res.write('404');
 res.end();
};

hserver.listen(8080);
var io = require('socket.io');
var socket = io.listen(hserver);
//this is the function in the Thrift part to send the image data to webpage using socket.io
var receiveImage = function(image,success){
buff= new Buffer(image.data.toString('base64'),'base64');
socket.broadcast({
    data: buff.toString('base64'),
    width: image.width,
    height: image.height
});
success(true);
}
</code>```

In the webpage i try to load the image using the on.message callback of socket.io

```<code><script>
var socket = new io.Socket(null,{port:8080});
socket.connect();
socket.on('message',function(obj){
        document.getElementById('imagenes').src='data:image/png;base64,'+obj.data.toString();
});
socket.on('connect',function(){
    document.getElementById('stream').innerHTML = "Conectado!"
});
</script>
</code>```

But i can't see the image..
The obj.data.toString('base64') create a string like this:

```<code> PNGIHDRKIDATxYw5L1LlFMM/migzWUadOadLUd+43PIfPU9VU5AJAg3dIWUmHAMajS8GUuq ............
 .............
 /NIlWDHUDmIPdHIEND
</code>```

is the all data of the image..

how can i show the image?? (maybe using img tag or into canvas)

Thanks in advance.

EDIT: Some changes to code, but nothing change.. my guess.. the image don't show because the data (PNGIHDRKIDATxYw......PdHIENDB) isn't the correct data.. i search about this and the png data used to show images inline is diferent (without the header PNGIHDRKIDAT and the tail ENDB), i remove the header and tail and don't show .. maybe the data i receive isn't correct, but if i try to write to filesystem in the server side using nodejs (fs) i get the correct images (with fs.writeFileSync("imagen.png",image.data.toString('binary'),'binary') ) using binary encode, but with base64 encode theres no image.

答:
It has been my experience that a base64 string of an image should be loaded with a data url like so:</p>

```<code><img alt="some image" src="data(PNGIHDRKIDATxYw5L1LlFMM/migzWUadOadLUd+43PIfPU9VU5AJAg3dIWUmHAMajS8GUuq .........)" />
</code>```

Body:
(sorry for my english)
Hi, i have an appplication created with nodejs to push image data into a webpage.

the data from nodejs server is pushed into webpage using socket.io

This data is the complete image, i try to write to disc to see the image and is good.
The data is put into a buffer to encode in base64 then send to the webpage and i try to show using
'data:image/png;base64,'+data
but nothing happend... The data seems to be "complete" including the headers of the PNG image.

The server use thrift to communicate with another client (this in C++), this client create the images and send to the nodejs-thrift server, when a image is receive, the nodejs-socket.io server push into webpage.

some code:
serverside

var http = require('http'),
url = require('url'),
fs  = require('fs'),
sys = require('sys');
var hserver = http.createServer(function(request,response){
var path = url.parse(request.url).pathname;
switch(path){
   case '/':

        fs.readFile(__dirname + '/index.html',function(err,data){
           if(err) return send404(res);
           response.writeHead(200,{'Content-Type':'text/html'});
           response.write(data,'utf8');
           response.end();
        });
    break;
    default: send404(response);
}
   }),
send404 = function(res){
 res.writeHead(404);
 res.write('404');
 res.end();
};

hserver.listen(8080);
var io = require('socket.io');
var socket = io.listen(hserver);
//this is the function in the Thrift part to send the image data to webpage using socket.io
var receiveImage = function(image,success){
buff= new Buffer(image.data.toString('base64'),'base64');
socket.broadcast({
    data: buff.toString('base64'),
    width: image.width,
    height: image.height
});
success(true);
}

In the webpage i try to load the image using the on.message callback of socket.io

But i can't see the image..
The obj.data.toString('base64') create a string like this:

 PNGIHDRKIDATxYw5L1LlFMM/migzWUadOadLUd+43PIfPU9VU5AJAg3dIWUmHAMajS8GUuq ............
 .............
 /NIlWDHUDmIPdHIEND

is the all data of the image..

how can i show the image?? (maybe using img tag or into canvas)

Thanks in advance.

EDIT: Some changes to code, but nothing change.. my guess.. the image don't show because the data (PNGIHDRKIDATxYw......PdHIENDB) isn't the correct data.. i search about this and the png data used to show images inline is diferent (without the header PNGIHDRKIDAT and the tail ENDB), i remove the header and tail and don't show .. maybe the data i receive isn't correct, but if i try to write to filesystem in the server side using nodejs (fs) i get the correct images (with fs.writeFileSync("imagen.png",image.data.toString('binary'),'binary') ) using binary encode, but with base64 encode theres no image.

Body:
It has been my experience that a base64 string of an image should be loaded with a data url like so:

<img alt="some image" src="data(PNGIHDRKIDATxYw5L1LlFMM/migzWUadOadLUd+43PIfPU9VU5AJAg3dIWUmHAMajS8GUuq .........)" />


答:
You can do it this way:</p>

```<code>Toast.makeText(activity, arguments?.get("message") ?: "default message", Toast.LENGTH_SHORT).show()
</code>```

Title: Android(Kotlin) Toast using Elvis Operator to use a Default String value when value from intent/arguments is Null

Body:
You can do it this way:

Toast.makeText(activity, arguments?.get("message") ?: "default message", Toast.LENGTH_SHORT).show()


问:
Masking inputted text using canvas on android kotlin
I'm currently doing a custom pin code and doing it with a canvas and paint, Unfortunately I cant seems to copy what the iputType="numberPassword" is doing with my custom design, I want to show the number momentarily before masking it and proceed to the next pin.

Here is my customEditText

```<code>class CustomEditTextPinViewMask : AppCompatEditText {
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
    init(context, attrs!!)
}

constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
    context,
    attrs,
    defStyleAttr
) {
    init(context, attrs!!)
}

@TargetApi(Build.VERSION_CODES.LOLLIPOP)
constructor(
    context: Context?,
    attrs: AttributeSet?,
    defStyleAttr: Int,
    defStyleRes: Int
) : super(context, attrs, defStyleAttr)

val XML_NAMESPACE_ANDROID = "http://schemas.android.com/apk/res/android"

private var mSpace = 24f//24 dp by default, space between the lines
private var mCharSize = 0f
private var mNumChars = 6f
private var mLineSpacing = 8f //8dp by default, height of the text from our lines
private var mMaxLength = 6
private var mClickListener: View.OnClickListener? = null
private var mLineStroke = 1f//1dp by default
private var mLineStrokeSelected = 2f//2dp by default
private var mLinesPaint: Paint? = null
private var mLinesGone: Paint? = null
private var mPaint: Paint? = null
val mStates = arrayOf(
    intArrayOf(R.attr.state_selected),
    intArrayOf(R.attr.state_focused),
    intArrayOf(-R.attr.state_focused)
)

val mColors = intArrayOf(
    -0x493800,//Green color = 0xFFB6C800
    -0x333334,//Gray color = 0xFFCCCCCC
    -0x333334
)

val mColorStates = ColorStateList(mStates, mColors)

private fun init(context: Context, attrs: AttributeSet) {
    val multi = context.resources.displayMetrics.density
    mLineStroke *= multi
    mLineStrokeSelected *= multi
    mLinesPaint = Paint(paint)
    mLinesPaint!!.strokeWidth = mLineStroke
    mLinesPaint!!.color = Color.parseColor("#969696")
    mLinesGone = Paint(paint)
    mLinesGone!!.strokeWidth = mLineStroke
    mLinesGone!!.color = Color.parseColor("#FFFFFF")
    mPaint = Paint(paint)
    setBackgroundResource(0)
    mSpace *= multi //convert to pixels for our density
    mLineSpacing *= multi //convert to pixels for our density
    mMaxLength = attrs.getAttributeIntValue(XML_NAMESPACE_ANDROID, "maxLength", 6)
    mNumChars = mMaxLength.toFloat()

    //Disable copy paste
    super.setCustomSelectionActionModeCallback(object : ActionMode.Callback {
        override fun onPrepareActionMode(mode: ActionMode, menu: Menu): Boolean {
            return false
        }

        override fun onDestroyActionMode(mode: ActionMode) {}
        override fun onCreateActionMode(mode: ActionMode, menu: Menu): Boolean {
            return false
        }

        override fun onActionItemClicked(mode: ActionMode, item: MenuItem): Boolean {
            return false
        }
    })
    // When tapped, move cursor to end of text.
    super.setOnClickListener(View.OnClickListener { v ->
        setSelection(text!!.length)
        if (mClickListener != null) {
            mClickListener!!.onClick(v)
        }
    })
}

override fun setOnClickListener(l: View.OnClickListener?) {
    mClickListener = l
}

override fun setCustomSelectionActionModeCallback(actionModeCallback: ActionMode.Callback?) {
    throw RuntimeException("setCustomSelectionActionModeCallback() not supported.")
}

private fun getColorForState(vararg states: Int): Int {
    return mColorStates.getColorForState(states, Color.GRAY)
}

private fun updateColorForLines(next: Boolean) {
    if (isFocused) {
        mLinesPaint!!.strokeWidth = mLineStrokeSelected
        mLinesPaint!!.color = getColorForState(R.attr.state_focused)
        mLinesPaint!!.color = getColorForState(R.attr.state_window_focused)
        if (next) {
            mLinesPaint!!.color = getColorForState(R.attr.state_selected)
        }
    } else {
        mLinesPaint!!.strokeWidth = mLineStroke
        mLinesPaint!!.color = getColorForState(-R.attr.state_focused)
    }
}

override fun onDraw(canvas: Canvas) {
   // super.onDraw(canvas)
    val availableWidth = width - paddingRight - paddingLeft
    if (mSpace < 0) {
        mCharSize = availableWidth / (mNumChars * 2 - 1)
    } else {
        mCharSize = (availableWidth - mSpace * (mNumChars - 1)) / mNumChars
    }
    var startX = paddingLeft
    val bottom = height - paddingBottom

    //Text Width
    val text: Editable? = text
    val textLength = text?.length
    val textWidths = FloatArray(textLength!!)
    paint.getTextWidths(getText(), 0, textLength, textWidths)

    //If Wanted to change text Color
    var i = 0
    while (i < mNumChars) {
        updateColorForLines(i == textLength)
        canvas.drawLine(
            startX.toFloat(), bottom.toFloat(), (startX + mCharSize) + letterSpacing,
            bottom.toFloat(), mLinesPaint!!
        )

        if (getText()!!.length > i) {
            val middle = startX + mCharSize / 2

            canvas.drawText(text, i, i + 1, middle - textWidths[0] / 2,
                bottom - mLineSpacing, paint)

            mLinesGone!!.strokeWidth = mLineStrokeSelected

            canvas.drawLine(
                startX.toFloat(), bottom.toFloat(),
                startX + mCharSize, bottom.toFloat(), mLinesGone!!
            )
            canvas.drawLine(
                startX.toFloat(), bottom.toFloat(),
                startX + mCharSize, bottom.toFloat(), mLinesGone!!
            )
            canvas.drawLine(
                startX.toFloat(), bottom.toFloat(),
                startX + mCharSize, bottom.toFloat(), mLinesGone!!
            )
        }
        if (mSpace < 0) {
            var mCharSizeMult = mCharSize * 2
            startX = (startX + mCharSizeMult).toInt()
        } else {
            var mCharSizeMspace = mCharSize + mSpace.toInt()
            startX = (startX + mCharSizeMspace).toInt()
        }
        i++
    }
}
</code>```

}

This is how i implement it on my xml

```<code> <com.sample.ui.widget.CustomEditTextPinViewMask
        android:id="@+id/pv_pincode"
        android:layout_width="260dp"
        android:layout_height="wrap_content"
        android:cursorVisible="false"
        android:inputType="numberPassword"
        android:letterSpacing="1"
        android:maxLength="6"
        android:textColor="@color/text_label_black"
        android:textIsSelectable="false"
        android:textSize="28sp"/>
</code>```

This is how it will look like when shown on the phone

How can i mask it? I'm also open for any sugestions thank you.

答:
Just use setTransformationMethod() for masking it.

You can use this to mask the edittext .

```<code>//by default
edittext.setTransformationMethod(new PasswordTransformationMethod());
//You can make it custom
edittext.setTransformationMethod(new AsterPasswordTransformationMethod());
</code>```

here is the AsterPasswordTransformationMethod class

```<code>public class AsterPasswordTransformationMethod extends PasswordTransformationMethod {
    @Override
    public CharSequence getTransformation(CharSequence source, View view) {
        return new PasswordCharSequence(source);
    }

    private class PasswordCharSequence implements CharSequence {
        private CharSequence mSource;
        public PasswordCharSequence(CharSequence source) {
            mSource = source; // Store char sequence
        }
        public char charAt(int index) {
            return '*'; // This is the important part
        }
        public int length() {
            return mSource.length(); // Return default
        }
        public CharSequence subSequence(int start, int end) {
            return mSource.subSequence(start, end); // Return default
        }
    }
    };
</code>```

Body:
I'm currently doing a custom pin code and doing it with a canvas and paint, Unfortunately I cant seems to copy what the iputType="numberPassword" is doing with my custom design, I want to show the number momentarily before masking it and proceed to the next pin.

Here is my customEditText

class CustomEditTextPinViewMask : AppCompatEditText {
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
    init(context, attrs!!)
}

constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
    context,
    attrs,
    defStyleAttr
) {
    init(context, attrs!!)
}

@TargetApi(Build.VERSION_CODES.LOLLIPOP)
constructor(
    context: Context?,
    attrs: AttributeSet?,
    defStyleAttr: Int,
    defStyleRes: Int
) : super(context, attrs, defStyleAttr)

val XML_NAMESPACE_ANDROID = "http://schemas.android.com/apk/res/android"

private var mSpace = 24f//24 dp by default, space between the lines
private var mCharSize = 0f
private var mNumChars = 6f
private var mLineSpacing = 8f //8dp by default, height of the text from our lines
private var mMaxLength = 6
private var mClickListener: View.OnClickListener? = null
private var mLineStroke = 1f//1dp by default
private var mLineStrokeSelected = 2f//2dp by default
private var mLinesPaint: Paint? = null
private var mLinesGone: Paint? = null
private var mPaint: Paint? = null
val mStates = arrayOf(
    intArrayOf(R.attr.state_selected),
    intArrayOf(R.attr.state_focused),
    intArrayOf(-R.attr.state_focused)
)

val mColors = intArrayOf(
    -0x493800,//Green color = 0xFFB6C800
    -0x333334,//Gray color = 0xFFCCCCCC
    -0x333334
)

val mColorStates = ColorStateList(mStates, mColors)

private fun init(context: Context, attrs: AttributeSet) {
    val multi = context.resources.displayMetrics.density
    mLineStroke *= multi
    mLineStrokeSelected *= multi
    mLinesPaint = Paint(paint)
    mLinesPaint!!.strokeWidth = mLineStroke
    mLinesPaint!!.color = Color.parseColor("#969696")
    mLinesGone = Paint(paint)
    mLinesGone!!.strokeWidth = mLineStroke
    mLinesGone!!.color = Color.parseColor("#FFFFFF")
    mPaint = Paint(paint)
    setBackgroundResource(0)
    mSpace *= multi //convert to pixels for our density
    mLineSpacing *= multi //convert to pixels for our density
    mMaxLength = attrs.getAttributeIntValue(XML_NAMESPACE_ANDROID, "maxLength", 6)
    mNumChars = mMaxLength.toFloat()

    //Disable copy paste
    super.setCustomSelectionActionModeCallback(object : ActionMode.Callback {
        override fun onPrepareActionMode(mode: ActionMode, menu: Menu): Boolean {
            return false
        }

        override fun onDestroyActionMode(mode: ActionMode) {}
        override fun onCreateActionMode(mode: ActionMode, menu: Menu): Boolean {
            return false
        }

        override fun onActionItemClicked(mode: ActionMode, item: MenuItem): Boolean {
            return false
        }
    })
    // When tapped, move cursor to end of text.
    super.setOnClickListener(View.OnClickListener { v ->
        setSelection(text!!.length)
        if (mClickListener != null) {
            mClickListener!!.onClick(v)
        }
    })
}

override fun setOnClickListener(l: View.OnClickListener?) {
    mClickListener = l
}

override fun setCustomSelectionActionModeCallback(actionModeCallback: ActionMode.Callback?) {
    throw RuntimeException("setCustomSelectionActionModeCallback() not supported.")
}

private fun getColorForState(vararg states: Int): Int {
    return mColorStates.getColorForState(states, Color.GRAY)
}

private fun updateColorForLines(next: Boolean) {
    if (isFocused) {
        mLinesPaint!!.strokeWidth = mLineStrokeSelected
        mLinesPaint!!.color = getColorForState(R.attr.state_focused)
        mLinesPaint!!.color = getColorForState(R.attr.state_window_focused)
        if (next) {
            mLinesPaint!!.color = getColorForState(R.attr.state_selected)
        }
    } else {
        mLinesPaint!!.strokeWidth = mLineStroke
        mLinesPaint!!.color = getColorForState(-R.attr.state_focused)
    }
}

override fun onDraw(canvas: Canvas) {
   // super.onDraw(canvas)
    val availableWidth = width - paddingRight - paddingLeft
    if (mSpace < 0) {
        mCharSize = availableWidth / (mNumChars * 2 - 1)
    } else {
        mCharSize = (availableWidth - mSpace * (mNumChars - 1)) / mNumChars
    }
    var startX = paddingLeft
    val bottom = height - paddingBottom

    //Text Width
    val text: Editable? = text
    val textLength = text?.length
    val textWidths = FloatArray(textLength!!)
    paint.getTextWidths(getText(), 0, textLength, textWidths)

    //If Wanted to change text Color
    var i = 0
    while (i < mNumChars) {
        updateColorForLines(i == textLength)
        canvas.drawLine(
            startX.toFloat(), bottom.toFloat(), (startX + mCharSize) + letterSpacing,
            bottom.toFloat(), mLinesPaint!!
        )

        if (getText()!!.length > i) {
            val middle = startX + mCharSize / 2

            canvas.drawText(text, i, i + 1, middle - textWidths[0] / 2,
                bottom - mLineSpacing, paint)

            mLinesGone!!.strokeWidth = mLineStrokeSelected

            canvas.drawLine(
                startX.toFloat(), bottom.toFloat(),
                startX + mCharSize, bottom.toFloat(), mLinesGone!!
            )
            canvas.drawLine(
                startX.toFloat(), bottom.toFloat(),
                startX + mCharSize, bottom.toFloat(), mLinesGone!!
            )
            canvas.drawLine(
                startX.toFloat(), bottom.toFloat(),
                startX + mCharSize, bottom.toFloat(), mLinesGone!!
            )
        }
        if (mSpace < 0) {
            var mCharSizeMult = mCharSize * 2
            startX = (startX + mCharSizeMult).toInt()
        } else {
            var mCharSizeMspace = mCharSize + mSpace.toInt()
            startX = (startX + mCharSizeMspace).toInt()
        }
        i++
    }
}

}

This is how i implement it on my xml

 <com.sample.ui.widget.CustomEditTextPinViewMask
        android:id="@+id/pv_pincode"
        android:layout_width="260dp"
        android:layout_height="wrap_content"
        android:cursorVisible="false"
        android:inputType="numberPassword"
        android:letterSpacing="1"
        android:maxLength="6"
        android:textColor="@color/text_label_black"
        android:textIsSelectable="false"
        android:textSize="28sp"/>

This is how it will look like when shown on the phone

How can i mask it? I'm also open for any sugestions thank you.

Body:
Just use setTransformationMethod() for masking it.

You can use this to mask the edittext .

//by default
edittext.setTransformationMethod(new PasswordTransformationMethod());
//You can make it custom
edittext.setTransformationMethod(new AsterPasswordTransformationMethod());

here is the AsterPasswordTransformationMethod class

public class AsterPasswordTransformationMethod extends PasswordTransformationMethod {
    @Override
    public CharSequence getTransformation(CharSequence source, View view) {
        return new PasswordCharSequence(source);
    }

    private class PasswordCharSequence implements CharSequence {
        private CharSequence mSource;
        public PasswordCharSequence(CharSequence source) {
            mSource = source; // Store char sequence
        }
        public char charAt(int index) {
            return '*'; // This is the important part
        }
        public int length() {
            return mSource.length(); // Return default
        }
        public CharSequence subSequence(int start, int end) {
            return mSource.subSequence(start, end); // Return default
        }
    }
    };


问:
Git push from fork master into remote upstream branch
I have a rather simple problem, but I can't figure out a solution. I have forked a repository <repo> and introduced new features to the code. All these features are kept in the master branch of my fork. Now I would like to contribute my changes to the original upstream repository. I would like to push them into a separate new branch on the upstream. I'm trying to achieve it with the following command:

```<code>git push origin upstream:<branch>
</code>```

The relevant parts of my Git configuration file are:

```<code>[remote "origin"]
    url = git@<...>:mabalenk/<repo>.git

[branch "master"]
    remote = origin
    merge  = refs/heads/master

[remote "upstream"]
    url = git@<...>:jsmith/<repo>.git
</code>```

I receive the following error message:

```<code>error: src refspec upstream does not match any
error: failed to push some refs to 'git@<...>:mabalenk/<repo>.git'
</code>```

答:
As underscore_d says, first you are choosing the wrong repository in your git push. You need git push upstream as opposed to git push origin in order to push content to the upstream repository.

The second problem is your refspec. Refspecs for different branch names are given as src:dest. So in your case you need master:BRANCH_NAME where BRANCH_NAME is the desired name of the branch you would like on upstream.

In all, the command would be: git push upstream master:BRANCH_NAME. You may also need to use the --set-upstream flag, though git will make that clear on the first call of the aforementioned command.

Body:
I have a rather simple problem, but I can't figure out a solution. I have forked a repository <repo> and introduced new features to the code. All these features are kept in the master branch of my fork. Now I would like to contribute my changes to the original upstream repository. I would like to push them into a separate new branch on the upstream. I'm trying to achieve it with the following command:

git push origin upstream:<branch>

The relevant parts of my Git configuration file are:

[remote "origin"]
    url = git@<...>:mabalenk/<repo>.git

[branch "master"]
    remote = origin
    merge  = refs/heads/master

[remote "upstream"]
    url = git@<...>:jsmith/<repo>.git

I receive the following error message:

error: src refspec upstream does not match any
error: failed to push some refs to 'git@<...>:mabalenk/<repo>.git'


答:
Simply put elvis operator after the nullable get call:

Toast.makeText(activity, arguments?.get("message") ?: "Default value", Toast.LENGTH_SHORT).show()
```

Here's some observations:

null ?: "default" evaluates to default

"valid str" ?: "default" evaluates to valid str

Body:
Simply put elvis operator after the nullable get call:

Toast.makeText(activity, arguments?.get("message") ?: "Default value", Toast.LENGTH_SHORT).show()

Here's some observations:

null ?: "default" evaluates to default

"valid str" ?: "default" evaluates to valid str


问:
How to count years in the text in R?
I want to count years found between the opening and closing brackets in the following text named txt.

```<code>library(stringr)
txt <- "Text Mining exercise (2020) Mining, p. 628508; Computer Science text analysis (1998) Computer Science, p.345-355; Introduction to data mining (2015) J. Data Science, pp. 31-33"
</code>```

lengths(strsplit(txt,"\\(\\d{4}\\)")) gives me 4 which is wrong. Any help, please?

答:
If you prefer Base-R

```<code>regmatches(txt, gregexpr("[^0-9]\\d{4}[^0-9]", txt))
</code>```

gives

```<code>[[1]]
[1] "(2020)" "(1998)" "(2015)"
</code>```

and if we wrap it in lengths( ... ) We will get the correct answer

Edit: or if you really only want the count we can shorten to

```<code>lengths(gregexpr("[^0-9]\\d{4}[^0-9]", txt))
</code>```

Title: How to count years in the text in R?

Body:
I want to count years found between the opening and closing brackets in the following text named txt.

library(stringr)
txt <- "Text Mining exercise (2020) Mining, p. 628508; Computer Science text analysis (1998) Computer Science, p.345-355; Introduction to data mining (2015) J. Data Science, pp. 31-33"

lengths(strsplit(txt,"\\(\\d{4}\\)")) gives me 4 which is wrong. Any help, please?

Body:
If you prefer Base-R

regmatches(txt, gregexpr("[^0-9]\\d{4}[^0-9]", txt))

gives

[[1]]
[1] "(2020)" "(1998)" "(2015)"

and if we wrap it in lengths( ... ) We will get the correct answer

Edit: or if you really only want the count we can shorten to

lengths(gregexpr("[^0-9]\\d{4}[^0-9]", txt))


问:
Overriding the value of a global variable
I just created two variables $isCompany and $isLoggedIn in my main.js.

```<code>import Vue from "vue";
import App from "./App.vue";
import "./registerServiceWorker";
import router from "./router";

Vue.config.productionTip = false;
Vue.prototype.$isCompany = true;
Vue.prototype.$isLoggedIn = true;

new Vue({
  router,
  render: h => h(App)
}).$mount("#app");
</code>```

My Question:
How can I access these variables in my <Button> component in Navigation.vue?
v-ifs are working but I'm not able to toggle the value of the variable, so I think there is an issue with overriding the value.

```<code><div v-if="this.$isLoggedIn" class="header-left">
  <User v-if="this.$isCompany" name="Company" img="..."></User>
  <User v-if="!this.$isCompany" name="Not Company" img="..."></User>
  <Button @onclick="this.$isCompany = !this.$isCompany" :color="'grey'" :isIconOnly="true"><b-icon icon="arrow-down-up"></b-icon></Button>
</div>
</code>```

If you need it, here is the way how I bind the @onclick to my <Button> component:

```<code><button @click="$emit('onclick')" :class="['button', 'size-'+size, 'color-'+color, isRounded ? 'type-rounded' : '', isIconOnly ? 'type-icon-only' : '']">
</code>```

EDIT:
Just noticed this error in my console if I click the button:

答:
v-ifs are working

Are you sure? I expect v-if="this.$isLoggedIn" not to work because this should not be used here (it is redundant; there is an implicit this. already there so you're basically doing this.this.$isLoggedIn).

but I'm not able to toggle the value of the variable

This is probably because you have not defined the variables in a "reactive" way.

```<code>Vue.prototype.$isCompany = true;
Vue.prototype.$isLoggedIn = true;
</code>```

It feels a bit awkward to define the variables like this on the Vue prototype object.

You can define the global variables in a reactive way by defining them as data properties of the root Vue instance:

new Vue({
  router,
  render: h => h(App),

  data: {
    isCompany: false,
    isLoggedIn: false,
  }
}).$mount("#app");
```

<p>You can access them from any descendant component via <code>this.$root.isCompany</code>. So, in your template, you would do:</p>

<pre class="lang-vue prettyprint-override"><code><User v-if="$root.isCompany" name="Company" img="..."></User>
</code>```

If you really want to avoid doing $root. in the template, then you can define proxy properties on the Vue prototype object (in addition to the above):

Object.defineProperties(Vue.prototype, {
  $isCompany: {
    get() { return this.$root.isCompany },
    set(x) { this.$root.isCompany = x }
  },
  $isLoggedIn: {
    get() { return this.$root.isLoggedIn },
    set(x) { this.$root.isLoggedIn = x }
  },
})
```

<p>Now you can do this in the template:</p>

<pre class="lang-vue prettyprint-override"><code><User v-if="$isCompany" name="Company" img="..."></User>
</code>```

Here is a small demo:

Object.defineProperties(Vue.prototype, {
  $isCompany: {
    get() { return this.$root.isCompany },
    set(x) { this.$root.isCompany = x }
  }
})

Vue.component('child', {
  template: '
<input type="checkbox" v-model="$isCompany"> {{ $isCompany }}
'
})

new Vue({
  el: '#app',
  data: {
    isCompany: false,
  },
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <child></child>
</div></code>```

Body:
I just created two variables $isCompany and $isLoggedIn in my main.js.

import Vue from "vue";
import App from "./App.vue";
import "./registerServiceWorker";
import router from "./router";

Vue.config.productionTip = false;
Vue.prototype.$isCompany = true;
Vue.prototype.$isLoggedIn = true;

new Vue({
  router,
  render: h => h(App)
}).$mount("#app");

My Question:
How can I access these variables in my <Button> component in Navigation.vue?
v-ifs are working but I'm not able to toggle the value of the variable, so I think there is an issue with overriding the value.

  <User v-if="this.$isCompany" name="Company" img="..."></User>
  <User v-if="!this.$isCompany" name="Not Company" img="..."></User>
  <Button @onclick="this.$isCompany = !this.$isCompany" :color="'grey'" :isIconOnly="true"></Button>

If you need it, here is the way how I bind the @onclick to my <Button> component:

<button @click="$emit('onclick')" :class="['button', 'size-'+size, 'color-'+color, isRounded ? 'type-rounded' : '', isIconOnly ? 'type-icon-only' : '']">

EDIT:
Just noticed this error in my console if I click the button:

Body:
v-ifs are working

Are you sure? I expect v-if="this.$isLoggedIn" not to work because this should not be used here (it is redundant; there is an implicit this. already there so you're basically doing this.this.$isLoggedIn).

but I'm not able to toggle the value of the variable

This is probably because you have not defined the variables in a "reactive" way.

Vue.prototype.$isCompany = true;
Vue.prototype.$isLoggedIn = true;

It feels a bit awkward to define the variables like this on the Vue prototype object.

You can define the global variables in a reactive way by defining them as data properties of the root Vue instance:

new Vue({
  router,
  render: h => h(App),

  data: {
    isCompany: false,
    isLoggedIn: false,
  }
}).$mount("#app");

You can access them from any descendant component via this.$root.isCompany. So, in your template, you would do:

<User v-if="$root.isCompany" name="Company" img="..."></User>

If you really want to avoid doing $root. in the template, then you can define proxy properties on the Vue prototype object (in addition to the above):

Object.defineProperties(Vue.prototype, {
  $isCompany: {
    get() { return this.$root.isCompany },
    set(x) { this.$root.isCompany = x }
  },
  $isLoggedIn: {
    get() { return this.$root.isLoggedIn },
    set(x) { this.$root.isLoggedIn = x }
  },
})

Now you can do this in the template:

<User v-if="$isCompany" name="Company" img="..."></User>

Here is a small demo:

Object.defineProperties(Vue.prototype, {
  $isCompany: {
    get() { return this.$root.isCompany },
    set(x) { this.$root.isCompany = x }
  }
})

Vue.component('child', {
  template: '<div><input type="checkbox" v-model="$isCompany"> {{ $isCompany }}</div>'
})

new Vue({
  el: '#app',
  data: {
    isCompany: false,
  },
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <child></child>
</div>


问:
Room Persistence: Error:Entities and Pojos must have a usable public constructor
I'm converting a project to Kotlin and I'm trying to make my model (which is also my entity) a data class
I intend to use Moshi to convert the JSON responses from the API

```<code>@Entity(tableName = "movies")
data class MovieKt(
    @PrimaryKey
    var id : Int,
    var title: String,
    var overview: String,
    var poster_path: String,
    var backdrop_path: String,
    var release_date: String,
    var vote_average: Double,
    var isFavorite: Int
)
</code>```

I can't build the app cause of the following error

Entities and Pojos must have a usable public constructor. You can have an empty constructor or a constructor whose parameters match the fields (by name and type).
  Cannot find setter for field.

The examples I found are not far from this

Ideas on how to solve it?

答:
Kotlin plugin doesn't pick up annotationProcessor dependencies, So use the latest version of Kotlin annotation processor - put this line at top of your module's level build.gradle file

apply plugin: 'kotlin-kapt'

like

```<code>apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'  // add this line

android {
    compileSdkVersion 28
    defaultConfig {
      ........
    }
}
</code>```

Don't forget to change the compileSdkVersion accordingly.

Body:
I'm converting a project to Kotlin and I'm trying to make my model (which is also my entity) a data class
I intend to use Moshi to convert the JSON responses from the API

@Entity(tableName = "movies")
data class MovieKt(
    @PrimaryKey
    var id : Int,
    var title: String,
    var overview: String,
    var poster_path: String,
    var backdrop_path: String,
    var release_date: String,
    var vote_average: Double,
    var isFavorite: Int
)

I can't build the app cause of the following error

Entities and Pojos must have a usable public constructor. You can have an empty constructor or a constructor whose parameters match the fields (by name and type).
  Cannot find setter for field.

The examples I found are not far from this

Ideas on how to solve it?

Body:
Kotlin plugin doesn't pick up annotationProcessor dependencies, So use the latest version of Kotlin annotation processor - put this line at top of your module's level build.gradle file

apply plugin: 'kotlin-kapt'

like

apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'  // add this line

android {
    compileSdkVersion 28
    defaultConfig {
      ........
    }
}

Don't forget to change the compileSdkVersion accordingly.


问:
ValueError: No tables found matching pattern '.+' while using pd.read_html()
I am using the following code to scrape data from 'Worldometers' web site. The code was working fine until yesterday. But today it is giving Value error.

I want to continue using urllib Request and urlopen functions.  Appreciate any inputs on what is the problem here. I can still extract the data using BeautifulSoup, which I would do if there is no solution.

```<code>from urllib.request import Request, urlopen
req = Request('https://www.worldometers.info/coronavirus/', headers={'User-Agent': 'Firefox/76.0.1'})
webpage = urlopen(req).read()

tables = pd.read_html(webpage)

ValueError: No tables found matching pattern '.+'
</code>```

答:
Seems that pandas has a problem to parse the markup (even with html5lib, which is strange). Only solution that worked for me was this "dirty" hack - to turn all tags to uppercase:

```<code>import re
from urllib.request import Request, urlopen
req = Request('https://www.worldometers.info/coronavirus/', headers={'User-Agent': 'Firefox/76.0.1'})

webpage = re.sub(r'<.*?>', lambda g: g.group(0).upper(), urlopen(req).read().decode('utf-8') )
tables = pd.read_html(webpage)
print(tables)
</code>```

Prints:

```<code>[      #  Country,Other  TotalCases NewCases  TotalDeaths NewDeaths  TotalRecovered  ... TotalTests  Tests/ 1M pop  Population          Continent  1 Caseevery X ppl  1 Deathevery X ppl  1 Testevery X ppl
0   NaN  North America     1985234   +4,047     120653.0      +479        624697.0  ...        NaN            NaN         NaN      North America                NaN                 NaN                NaN
1   NaN  South America      758107     +619      36746.0       +13        320826.0  ...        NaN            NaN         NaN      South America                NaN                 NaN                NaN
2   NaN         Europe     1979601   +9,702     171874.0      +306        958874.0  ...        NaN            NaN         NaN             Europe                NaN                 NaN                NaN
3   NaN           Asia     1067485  +16,219      29382.0      +262        627546.0  ...        NaN            NaN         NaN               Asia                NaN                 NaN                NaN
4   NaN         Africa      132254     +667       3819.0        +5         55257.0  ...        NaN            NaN         NaN             Africa                NaN                 NaN                NaN
..   ..            ...         ...      ...          ...       ...             ...  ...        ...            ...         ...                ...                ...                 ...                ...
226 NaN         Total:     1067485  +16,219      29382.0      +262        627546.0  ...        NaN            NaN         NaN               Asia                NaN                 NaN                NaN
227 NaN         Total:      132254     +667       3819.0        +5         55257.0  ...        NaN            NaN         NaN             Africa                NaN                 NaN                NaN
228 NaN         Total:        8782      +23        125.0       NaN          8164.0  ...        NaN            NaN         NaN  Australia/Oceania                NaN                 NaN                NaN
229 NaN         Total:         721      NaN         15.0       NaN           651.0  ...        NaN            NaN         NaN                NaN                NaN                 NaN                NaN
230 NaN         Total:     5932184  +31,277     362614.0    +1,065       2596015.0  ...        NaN            NaN         NaN                All                NaN                 NaN                NaN

[231 rows x 19 columns],       #  Country,Other  TotalCases  NewCases  TotalDeaths NewDeaths  TotalRecovered  ... TotalTests  Tests/ 1M pop  Population          Continent  1 Caseevery X ppl  1 Deathevery X ppl  1 Testevery X ppl
0   NaN           Asia     1051266   +25,111      29120.0      +439        621744.0  ...        NaN            NaN         NaN               Asia                NaN                 NaN                NaN
1   NaN  North America     1981187   +28,561     120174.0    +1,828        622301.0  ...        NaN            NaN         NaN      North America                NaN                 NaN                NaN
2   NaN  South America      757488   +37,855      36733.0    +1,303        320777.0  ...        NaN            NaN         NaN      South America                NaN                 NaN                NaN
3   NaN         Europe     1969899   +19,816     171568.0      +937        948496.0  ...        NaN            NaN         NaN             Europe                NaN                 NaN                NaN
4   NaN         Africa      131587    +4,949       3814.0      +104         55126.0  ...        NaN            NaN         NaN             Africa                NaN                 NaN                NaN
..   ..            ...         ...       ...          ...       ...             ...  ...        ...            ...         ...                ...                ...                 ...                ...
226 NaN         Total:     1969899   +19,816     171568.0      +937        948496.0  ...        NaN            NaN         NaN             Europe                NaN                 NaN                NaN
227 NaN         Total:      131587    +4,949       3814.0      +104         55126.0  ...        NaN            NaN         NaN             Africa                NaN                 NaN                NaN
228 NaN         Total:        8759       +12        125.0        +1          8155.0  ...        NaN            NaN         NaN  Australia/Oceania                NaN                 NaN                NaN
229 NaN         Total:         721       NaN         15.0       NaN           651.0  ...        NaN            NaN         NaN                NaN                NaN                 NaN                NaN
230 NaN         Total:     5900907  +116,304     361549.0    +5,677       2577250.0  ...        NaN            NaN         NaN                All                NaN                 NaN                NaN

[231 rows x 19 columns],       #  Country,Other  TotalCases  NewCases  TotalDeaths NewDeaths  TotalRecovered  ... TotalTests  Tests/ 1M pop  Population          Continent  1 Caseevery X ppl  1 Deathevery X ppl  1 Testevery X ppl
0   NaN           Asia     1026155   +23,237      28681.0      +466        604064.0  ...        NaN            NaN         NaN               Asia                NaN                 NaN                NaN
1   NaN  North America     1952626   +26,248     118346.0    +2,183        610327.0  ...        NaN            NaN         NaN      North America                NaN                 NaN                NaN
2   NaN  South America      719633   +35,891      35430.0    +1,506        287501.0  ...        NaN            NaN         NaN      South America                NaN                 NaN                NaN
3   NaN         Europe     1950083   +16,002     170631.0    +1,030        931561.0  ...        NaN            NaN         NaN             Europe                NaN                 NaN                NaN
4   NaN         Africa      126638    +5,091       3710.0       +97         52623.0  ...        NaN            NaN         NaN             Africa                NaN                 NaN                NaN
..   ..            ...         ...       ...          ...       ...             ...  ...        ...            ...         ...                ...                ...                 ...                ...
226 NaN         Total:     1950083   +16,002     170631.0    +1,030        931561.0  ...        NaN            NaN         NaN             Europe                NaN                 NaN                NaN
227 NaN         Total:      126638    +5,091       3710.0       +97         52623.0  ...        NaN            NaN         NaN             Africa                NaN                 NaN                NaN
228 NaN         Total:        8747        +6        124.0        +1          8129.0  ...        NaN            NaN         NaN  Australia/Oceania                NaN                 NaN                NaN
229 NaN         Total:         721       NaN         15.0       NaN           651.0  ...        NaN            NaN         NaN                NaN                NaN                 NaN                NaN
230 NaN         Total:     5784603  +106,475     356937.0   +10,960       2494856.0  ...        NaN            NaN         NaN                All                NaN                 NaN                NaN

[231 rows x 19 columns]]
</code>```

Body:
I am using the following code to scrape data from 'Worldometers' web site. The code was working fine until yesterday. But today it is giving Value error.

I want to continue using urllib Request and urlopen functions.  Appreciate any inputs on what is the problem here. I can still extract the data using BeautifulSoup, which I would do if there is no solution.

from urllib.request import Request, urlopen
req = Request('https://www.worldometers.info/coronavirus/', headers={'User-Agent': 'Firefox/76.0.1'})
webpage = urlopen(req).read()

tables = pd.read_html(webpage)

ValueError: No tables found matching pattern '.+'

Body:
Seems that pandas has a problem to parse the markup (even with html5lib, which is strange). Only solution that worked for me was this "dirty" hack - to turn all tags to uppercase:

import re
from urllib.request import Request, urlopen
req = Request('https://www.worldometers.info/coronavirus/', headers={'User-Agent': 'Firefox/76.0.1'})

webpage = re.sub(r'<.*?>', lambda g: g.group(0).upper(), urlopen(req).read().decode('utf-8') )
tables = pd.read_html(webpage)
print(tables)

Prints:

[      #  Country,Other  TotalCases NewCases  TotalDeaths NewDeaths  TotalRecovered  ... TotalTests  Tests/ 1M pop  Population          Continent  1 Caseevery X ppl  1 Deathevery X ppl  1 Testevery X ppl
0   NaN  North America     1985234   +4,047     120653.0      +479        624697.0  ...        NaN            NaN         NaN      North America                NaN                 NaN                NaN
1   NaN  South America      758107     +619      36746.0       +13        320826.0  ...        NaN            NaN         NaN      South America                NaN                 NaN                NaN
2   NaN         Europe     1979601   +9,702     171874.0      +306        958874.0  ...        NaN            NaN         NaN             Europe                NaN                 NaN                NaN
3   NaN           Asia     1067485  +16,219      29382.0      +262        627546.0  ...        NaN            NaN         NaN               Asia                NaN                 NaN                NaN
4   NaN         Africa      132254     +667       3819.0        +5         55257.0  ...        NaN            NaN         NaN             Africa                NaN                 NaN                NaN
..   ..            ...         ...      ...          ...       ...             ...  ...        ...            ...         ...                ...                ...                 ...                ...
226 NaN         Total:     1067485  +16,219      29382.0      +262        627546.0  ...        NaN            NaN         NaN               Asia                NaN                 NaN                NaN
227 NaN         Total:      132254     +667       3819.0        +5         55257.0  ...        NaN            NaN         NaN             Africa                NaN                 NaN                NaN
228 NaN         Total:        8782      +23        125.0       NaN          8164.0  ...        NaN            NaN         NaN  Australia/Oceania                NaN                 NaN                NaN
229 NaN         Total:         721      NaN         15.0       NaN           651.0  ...        NaN            NaN         NaN                NaN                NaN                 NaN                NaN
230 NaN         Total:     5932184  +31,277     362614.0    +1,065       2596015.0  ...        NaN            NaN         NaN                All                NaN                 NaN                NaN

[231 rows x 19 columns],       #  Country,Other  TotalCases  NewCases  TotalDeaths NewDeaths  TotalRecovered  ... TotalTests  Tests/ 1M pop  Population          Continent  1 Caseevery X ppl  1 Deathevery X ppl  1 Testevery X ppl
0   NaN           Asia     1051266   +25,111      29120.0      +439        621744.0  ...        NaN            NaN         NaN               Asia                NaN                 NaN                NaN
1   NaN  North America     1981187   +28,561     120174.0    +1,828        622301.0  ...        NaN            NaN         NaN      North America                NaN                 NaN                NaN
2   NaN  South America      757488   +37,855      36733.0    +1,303        320777.0  ...        NaN            NaN         NaN      South America                NaN                 NaN                NaN
3   NaN         Europe     1969899   +19,816     171568.0      +937        948496.0  ...        NaN            NaN         NaN             Europe                NaN                 NaN                NaN
4   NaN         Africa      131587    +4,949       3814.0      +104         55126.0  ...        NaN            NaN         NaN             Africa                NaN                 NaN                NaN
..   ..            ...         ...       ...          ...       ...             ...  ...        ...            ...         ...                ...                ...                 ...                ...
226 NaN         Total:     1969899   +19,816     171568.0      +937        948496.0  ...        NaN            NaN         NaN             Europe                NaN                 NaN                NaN
227 NaN         Total:      131587    +4,949       3814.0      +104         55126.0  ...        NaN            NaN         NaN             Africa                NaN                 NaN                NaN
228 NaN         Total:        8759       +12        125.0        +1          8155.0  ...        NaN            NaN         NaN  Australia/Oceania                NaN                 NaN                NaN
229 NaN         Total:         721       NaN         15.0       NaN           651.0  ...        NaN            NaN         NaN                NaN                NaN                 NaN                NaN
230 NaN         Total:     5900907  +116,304     361549.0    +5,677       2577250.0  ...        NaN            NaN         NaN                All                NaN                 NaN                NaN

[231 rows x 19 columns],       #  Country,Other  TotalCases  NewCases  TotalDeaths NewDeaths  TotalRecovered  ... TotalTests  Tests/ 1M pop  Population          Continent  1 Caseevery X ppl  1 Deathevery X ppl  1 Testevery X ppl
0   NaN           Asia     1026155   +23,237      28681.0      +466        604064.0  ...        NaN            NaN         NaN               Asia                NaN                 NaN                NaN
1   NaN  North America     1952626   +26,248     118346.0    +2,183        610327.0  ...        NaN            NaN         NaN      North America                NaN                 NaN                NaN
2   NaN  South America      719633   +35,891      35430.0    +1,506        287501.0  ...        NaN            NaN         NaN      South America                NaN                 NaN                NaN
3   NaN         Europe     1950083   +16,002     170631.0    +1,030        931561.0  ...        NaN            NaN         NaN             Europe                NaN                 NaN                NaN
4   NaN         Africa      126638    +5,091       3710.0       +97         52623.0  ...        NaN            NaN         NaN             Africa                NaN                 NaN                NaN
..   ..            ...         ...       ...          ...       ...             ...  ...        ...            ...         ...                ...                ...                 ...                ...
226 NaN         Total:     1950083   +16,002     170631.0    +1,030        931561.0  ...        NaN            NaN         NaN             Europe                NaN                 NaN                NaN
227 NaN         Total:      126638    +5,091       3710.0       +97         52623.0  ...        NaN            NaN         NaN             Africa                NaN                 NaN                NaN
228 NaN         Total:        8747        +6        124.0        +1          8129.0  ...        NaN            NaN         NaN  Australia/Oceania                NaN                 NaN                NaN
229 NaN         Total:         721       NaN         15.0       NaN           651.0  ...        NaN            NaN         NaN                NaN                NaN                 NaN                NaN
230 NaN         Total:     5784603  +106,475     356937.0   +10,960       2494856.0  ...        NaN            NaN         NaN                All                NaN                 NaN                NaN

[231 rows x 19 columns]]