问:
Tensorflow error : DLL load failed: The specified procedure could not be found
I tried to install tensorflow cpu using pip in my windows8.1 64bit python3.6.0
using pip install tensorflow
but it gives me this error:

```<code>Traceback (most recent call last):   File "C:\Users\Laitooo
San\Desktop\tf.py", line 1, in <module>
     import tensorflow as tf   File "C:\Users\Laitooo San\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\__init__.py",
 line 24, in <module>
     from tensorflow.python import *   File "C:\Users\Laitooo San\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\__init__.py",
 line 52, in <module>
     from tensorflow.core.framework.graph_pb2 import *   File "C:\Users\Laitooo
 San\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\core\framework\graph_pb2.py",
 line 6, in <module>
     from google.protobuf import descriptor as _descriptor   File "C:\Users\Laitooo
 San\AppData\Local\Programs\Python\Python36\lib\site-packages\google\protobuf\descriptor.py",
 line 47, in <module>
     from google.protobuf.pyext import _message ImportError: DLL load failed: The specified procedure could not be found.
</code>```

I downloaded python36.dll and made sure all other .dll is there and install Microsoft visual c++ 2015

I also uninstalled tensorflow and installed another version several times but without any result.

答:
All official tensorflow binaries since 1.6 were made with AVX, rendering older CPUs unsupported.
In order to install recent tensorflow versions on an older CPU you can simply install tensorflow from a non-avx built wheel ( you can find some here)</p>

```<code> pip install <path to the downloaded .whl file>
</code>```

Body:
I tried to install tensorflow cpu using pip in my windows8.1 64bit python3.6.0
using pip install tensorflow
but it gives me this error:

Traceback (most recent call last):   File "C:\Users\Laitooo
San\Desktop\tf.py", line 1, in <module>
     import tensorflow as tf   File "C:\Users\Laitooo San\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\__init__.py",
 line 24, in <module>
     from tensorflow.python import *   File "C:\Users\Laitooo San\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\__init__.py",
 line 52, in <module>
     from tensorflow.core.framework.graph_pb2 import *   File "C:\Users\Laitooo
 San\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\core\framework\graph_pb2.py",
 line 6, in <module>
     from google.protobuf import descriptor as _descriptor   File "C:\Users\Laitooo
 San\AppData\Local\Programs\Python\Python36\lib\site-packages\google\protobuf\descriptor.py",
 line 47, in <module>
     from google.protobuf.pyext import _message ImportError: DLL load failed: The specified procedure could not be found.

I downloaded python36.dll and made sure all other .dll is there and install Microsoft visual c++ 2015

I also uninstalled tensorflow and installed another version several times but without any result.

Body:
All official tensorflow binaries since 1.6 were made with AVX, rendering older CPUs unsupported.
In order to install recent tensorflow versions on an older CPU you can simply install tensorflow from a non-avx built wheel ( you can find some here)

 pip install <path to the downloaded .whl file>


来源: stackexchange

问:
How to test my Exception extension method that uses DbEntityValidationException?
I hope I’m just over looking something really simple…

The answer I need must provide a test that uses Moq due to the fact that I don’t have access to Fakes for my personal MSDN (professional). Only premium and ultimate can use Fakes. The unit test must be able to run without access to any external resources. No connecting to a SQL database with an Entity Framework DbContext.

```<code>public static string ToDetailedString(this Exception ex)
{
    var builder = new StringBuilder();
    AddExceptionToBuilder(builder, ex);
    return builder.ToString();
}

private static void AddExceptionToBuilder(StringBuilder builder, Exception ex)
{
    builder.Append(builder.Length > 0 ? "\r\n" + ex.Message : ex.Message);

    var validationException = ex as DbEntityValidationException;
    if (validationException != null)
    {
        foreach (var detail in validationException.EntityValidationErrors.SelectMany(error => error.ValidationErrors))
        {
            builder.Append("\r\n" + detail.PropertyName + " : " + detail.ErrorMessage);
        }
    }

    if (ex.InnerException != null)
    {
        AddExceptionToBuilder(builder, ex.InnerException);
    }
}
</code>```

Here is why it’s so difficult to test. It’s not as simple as just creating a new DbEntityValidationException because you have to pass in a list of DbEntityValidationResult. You cannot instantiate a DbEntityValidationResult without providing a DbEntityEntry. The only way I’ve found to create an DbEntityEntry is to get it from DbContext.Entry(). This means you must have a valid DbContext that needs access to a database.

This is the only code I've been able to make work but it requires access to a database.

```<code>/// <summary>
/// This test method must be ran against the database. I cannot figure out a way to create an entry without
/// a valid context to a real database?
/// </summary>
[TestMethod]
public void ToDetailStringForDbEntityValiditionException()
{
    if (!TestHelper.RunUnitTestAgainstDatabase)
    {
        return;
    }

    var errors = new List<DbValidationError>();
    errors.Add(new DbValidationError("Username", Constants.UsernameLengthError));

    var context = new EntityFrameworkRepository();
    var entry = context.Entry(new User());
    var results = new List<DbEntityValidationResult>();
    var result = new DbEntityValidationResult(entry, errors);
    results.Add(result);

    var exception = new DbEntityValidationException("Registration Failed.", results);

    var expected = "Registration Failed.\r\nUsername : " + Constants.UsernameLengthError;
    var actual = exception.ToDetailedString();

    Assert.AreEqual(expected, actual);
}
</code>```

答:
This worked for me, using the Entity Model and Connection I had already setup:</p>

```<code>var context = new DbContext("name = JobManagerConnection");
var entry = context.Entry(new Models.JobManager.Job());
var errInner = new System.Data.Entity.Validation.DbValidationError("Test Property", "Test Message");
var lstErrInner = new List<System.Data.Entity.Validation.DbValidationError> { errInner };
var errOuter = new System.Data.Entity.Validation.DbEntityValidationResult (entry, lstErrInner);
var lstErrOuter = new List<System.Data.Entity.Validation.DbEntityValidationResult> { errOuter };
throw new System.Data.Entity.Validation.DbEntityValidationException("Test Data Exception", lstErrOuter);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I hope I’m just over looking something really simple…

The answer I need must provide a test that uses Moq due to the fact that I don’t have access to Fakes for my personal MSDN (professional). Only premium and ultimate can use Fakes. The unit test must be able to run without access to any external resources. No connecting to a SQL database with an Entity Framework DbContext.

public static string ToDetailedString(this Exception ex)
{
    var builder = new StringBuilder();
    AddExceptionToBuilder(builder, ex);
    return builder.ToString();
}

private static void AddExceptionToBuilder(StringBuilder builder, Exception ex)
{
    builder.Append(builder.Length > 0 ? "\r\n" + ex.Message : ex.Message);

    var validationException = ex as DbEntityValidationException;
    if (validationException != null)
    {
        foreach (var detail in validationException.EntityValidationErrors.SelectMany(error => error.ValidationErrors))
        {
            builder.Append("\r\n" + detail.PropertyName + " : " + detail.ErrorMessage);
        }
    }

    if (ex.InnerException != null)
    {
        AddExceptionToBuilder(builder, ex.InnerException);
    }
}

Here is why it’s so difficult to test. It’s not as simple as just creating a new DbEntityValidationException because you have to pass in a list of DbEntityValidationResult. You cannot instantiate a DbEntityValidationResult without providing a DbEntityEntry. The only way I’ve found to create an DbEntityEntry is to get it from DbContext.Entry(). This means you must have a valid DbContext that needs access to a database.

This is the only code I've been able to make work but it requires access to a database.

///
/// This test method must be ran against the database. I cannot figure out a way to create an entry without
/// a valid context to a real database?
///
[TestMethod]
public void ToDetailStringForDbEntityValiditionException()
{
    if (!TestHelper.RunUnitTestAgainstDatabase)
    {
        return;
    }

    var errors = new List<DbValidationError>();
    errors.Add(new DbValidationError("Username", Constants.UsernameLengthError));

    var context = new EntityFrameworkRepository();
    var entry = context.Entry(new User());
    var results = new List<DbEntityValidationResult>();
    var result = new DbEntityValidationResult(entry, errors);
    results.Add(result);

    var exception = new DbEntityValidationException("Registration Failed.", results);

    var expected = "Registration Failed.\r\nUsername : " + Constants.UsernameLengthError;
    var actual = exception.ToDetailedString();

    Assert.AreEqual(expected, actual);
}

Body:
This worked for me, using the Entity Model and Connection I had already setup:

var context = new DbContext("name = JobManagerConnection");
var entry = context.Entry(new Models.JobManager.Job());
var errInner = new System.Data.Entity.Validation.DbValidationError("Test Property", "Test Message");
var lstErrInner = new List<System.Data.Entity.Validation.DbValidationError> { errInner };
var errOuter = new System.Data.Entity.Validation.DbEntityValidationResult (entry, lstErrInner);
var lstErrOuter = new List<System.Data.Entity.Validation.DbEntityValidationResult> { errOuter };
throw new System.Data.Entity.Validation.DbEntityValidationException("Test Data Exception", lstErrOuter);

ContentLicense: CC BY-SA 4.0


问:
How to return custom class from PagingAndSortingRepository in Spring Boot
I have a model that looks like this:

```<code>@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Sale {
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;

  @OneToOne(targetEntity = User.class)
  private User customer;

  @OneToOne(targetEntity = Product.class)
  private Product product;
}
</code>```

And I have a paging-and-sorting repository, like so:

```<code>public interface SaleRepository extends PagingAndSortingRepository<Sale, Long> {}
</code>```

But I would like to the "findAll" method of the repository in order to return a custom class with certain fields (instead of all the data of the nested entities), while still maintain paging and sorting abilities.  The list of objects I would like to return would contain something like:

saleId

customerId

customerName

productId

ProductName

prouctPrice

But I'm not sure how to actually do this.

My controller method accepts sorting and paging parameters and then does this:

```<code>Page<Sale> saleList = saleRepository.findAll(pageable);

return saleList;
</code>```

答:
You can create either and Interface or a DTO and use this as the result of a find declared in your repository:

```<code>Page<YourDTO> findAllAsDtos(Pageable pageable);
</code>```

Read more about projections here: https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#projections

Body:
I have a model that looks like this:

@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Sale {
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;

  @OneToOne(targetEntity = User.class)
  private User customer;

  @OneToOne(targetEntity = Product.class)
  private Product product;
}

And I have a paging-and-sorting repository, like so:

public interface SaleRepository extends PagingAndSortingRepository<Sale, Long> {}

But I would like to the "findAll" method of the repository in order to return a custom class with certain fields (instead of all the data of the nested entities), while still maintain paging and sorting abilities.  The list of objects I would like to return would contain something like:

saleId

customerId

customerName

productId

ProductName

prouctPrice

But I'm not sure how to actually do this.

My controller method accepts sorting and paging parameters and then does this:

Page<Sale> saleList = saleRepository.findAll(pageable);

return saleList;

Body:
You can create either and Interface or a DTO and use this as the result of a find declared in your repository:

Page<YourDTO> findAllAsDtos(Pageable pageable);

Read more about projections here: https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#projections


问:
How to start a python operator boto3 AWS-glue task in airflow based on another AWS-glue task successful completion in Airflow?
My Ariflow script has several tasks using python operator to start a glue job using boto3. Even though the flow depends on each task in Ariflow. The consecutive tasks don't wait until the previous task's successful completion.

Next glue job task is called as soon as the previous glue job task is invoked. At the end even though the Airflow looks like successfully completed the glue jobs are still running for several minutes.

```<code>    from airflow import DAG
    from airflow.operators.python_operator import PythonOperator
    from datetime import datetime, timedelta
    from airflow.operators.sensors import TimeDeltaSensor
    import boto3
    import json

    default_args = {
    'owner': 'SAM',
    'start_date': datetime(2019, 5, 27)
     }

    glue_client = boto3.client('glue', region_name='us-east-1')

    def run_customer_job():
        glue_client.start_job_run(JobName='customer')

    def run_product_job():
        glue_client.start_job_run(JobName='product')

    with DAG('dataload', default_args=default_args, schedule_interval="0 15 * * *") as dag:
        task1 = PythonOperator(task_id='task1',
                               python_callable=run_customer_job)
        task2 = PythonOperator(task_id='task2',
                               python_callable=run_product_job)

    task1 >> task2
</code>```

答:
I would create a status loop after calling start_job_run so your task doesn't finish until the Glue job has.

Quick and simple example (you will need handling for failed tasks etc):

job = glue_client.start_job_run(JobName='customer')

while True:
  status = glue.get_job_run(JobName=job['Name'], RunId=job['JobRunId'])
  if status['JobRun']['JobRunState'] == 'SUCCEEDED':
    break

  time.sleep(10)
```

Body:
My Ariflow script has several tasks using python operator to start a glue job using boto3. Even though the flow depends on each task in Ariflow. The consecutive tasks don't wait until the previous task's successful completion.

Next glue job task is called as soon as the previous glue job task is invoked. At the end even though the Airflow looks like successfully completed the glue jobs are still running for several minutes.

    from airflow import DAG
    from airflow.operators.python_operator import PythonOperator
    from datetime import datetime, timedelta
    from airflow.operators.sensors import TimeDeltaSensor
    import boto3
    import json

    default_args = {
    'owner': 'SAM',
    'start_date': datetime(2019, 5, 27)
     }

    glue_client = boto3.client('glue', region_name='us-east-1')

    def run_customer_job():
        glue_client.start_job_run(JobName='customer')

    def run_product_job():
        glue_client.start_job_run(JobName='product')

    with DAG('dataload', default_args=default_args, schedule_interval="0 15 * * *") as dag:
        task1 = PythonOperator(task_id='task1',
                               python_callable=run_customer_job)
        task2 = PythonOperator(task_id='task2',
                               python_callable=run_product_job)

    task1 >> task2


问:
Post process MongoDB document before saving a Spring Data MongoDB entity
I am working on a service that stores object entities in a MongoDB database. The entities (Java classes) come from a context that I cannot change.

I would like to add time information to the mapped MongoDB documents, without embedding the entities in a special wrapper class.

I know that I don't get the time information back when reading the data via the Java entity. Since the information is only needed for internal purposes (e.g. TTL index) this is no problem for me.

Is there a way to do the entity-document mapping and then post process the result (BSON document) before saving it to the database?

答: You could listen to BeforeSaveEvent as described here which is given the original entity and the already mapped Document.


问:
RabbitMQ how to stop reconnecting after AmqpIOException UnknownHostException
for our integration-test profile we want to disable Spring's automatic reconnecting to fail fast.

```<code>Attempting to connect to: [rabbitmq-invalid-host:5672]
Error creating consumer; retrying in 5000
org.springframework.amqp.AmqpConnectException: org.springframework.amqp.AmqpIOException: java.net.UnknownHostException: rabbitmq-invalid-host
</code>```

the following settings do not have any effect yet:

```<code>spring.rabbitmq.connection-timeout=1000
spring.rabbitmq.requested-heartbeat=1
spring.rabbitmq.listener.direct.missing-queues-fatal=true
spring.rabbitmq.listener.direct.retry.enabled=false
spring.rabbitmq.template.retry.enabled=false
</code>```

any idea how to make amqp give up or even destroy the whole app-context?

full stacktrace:

```<code>2019-06-11 14:56:31.596  INFO 3025 --- [           main] o.s.a.r.c.CachingConnectionFactory       : Attempting to connect to: [rabbitmq-invalid-host:5672]
2019-06-11 14:56:31.698  INFO 3025 --- [           main] o.s.a.r.c.CachingConnectionFactory       : Attempting to connect to: [rabbitmq-invalid-host:5672]
2019-06-11 14:56:31.902  INFO 3025 --- [           main] o.s.a.r.c.CachingConnectionFactory       : Attempting to connect to: [rabbitmq-invalid-host:5672]
2019-06-11 14:56:32.305  INFO 3025 --- [           main] o.s.a.r.c.CachingConnectionFactory       : Attempting to connect to: [rabbitmq-invalid-host:5672]
2019-06-11 14:56:33.108  INFO 3025 --- [           main] o.s.a.r.c.CachingConnectionFactory       : Attempting to connect to: [rabbitmq-invalid-host:5672]
2019-06-11 14:56:34.709  INFO 3025 --- [           main] o.s.a.r.c.CachingConnectionFactory       : Attempting to connect to: [rabbitmq-invalid-host:5672]
2019-06-11 14:56:36.476  INFO 3025 --- [ntContainer#0-1] o.s.a.r.c.CachingConnectionFactory       : Attempting to connect to: [rabbitmq-invalid-host:5672]
2019-06-11 14:56:36.477 ERROR 3025 --- [ntContainer#0-1] o.s.a.r.l.DirectMessageListenerContainer : Error creating consumer; retrying in 5000

org.springframework.amqp.AmqpConnectException: org.springframework.amqp.AmqpIOException: java.net.UnknownHostException: rabbitmq-invalid-host
    at org.springframework.amqp.rabbit.listener.DirectMessageListenerContainer.doConsumeFromQueue(DirectMessageListenerContainer.java:667) [spring-rabbit-2.1.6.RELEASE.jar:2.1.6.RELEASE]
    at org.springframework.amqp.rabbit.listener.DirectMessageListenerContainer.consumeFromQueue(DirectMessageListenerContainer.java:645) [spring-rabbit-2.1.6.RELEASE.jar:2.1.6.RELEASE]
    at org.springframework.amqp.rabbit.listener.DirectMessageListenerContainer.startConsumers(DirectMessageListenerContainer.java:550) [spring-rabbit-2.1.6.RELEASE.jar:2.1.6.RELEASE]
    at org.springframework.amqp.rabbit.listener.DirectMessageListenerContainer.lambda$actualStart$1(DirectMessageListenerContainer.java:410) [spring-rabbit-2.1.6.RELEASE.jar:2.1.6.RELEASE]
    at java.lang.Thread.run(Thread.java:748) ~[na:1.8.0_212]
Caused by: org.springframework.amqp.AmqpIOException: java.net.UnknownHostException: rabbitmq-invalid-host
    at org.springframework.amqp.rabbit.support.RabbitExceptionTranslator.convertRabbitAccessException(RabbitExceptionTranslator.java:71) ~[spring-rabbit-2.1.6.RELEASE.jar:2.1.6.RELEASE]
    at org.springframework.amqp.rabbit.connection.AbstractConnectionFactory.createBareConnection(AbstractConnectionFactory.java:509) ~[spring-rabbit-2.1.6.RELEASE.jar:2.1.6.RELEASE]
    at org.springframework.amqp.rabbit.connection.CachingConnectionFactory.createConnection(CachingConnectionFactory.java:700) ~[spring-rabbit-2.1.6.RELEASE.jar:2.1.6.RELEASE]
    at org.springframework.amqp.rabbit.listener.DirectMessageListenerContainer.doConsumeFromQueue(DirectMessageListenerContainer.java:663) [spring-rabbit-2.1.6.RELEASE.jar:2.1.6.RELEASE]
    ... 4 common frames omitted
Caused by: java.net.UnknownHostException: rabbitmq-invalid-host
    at java.net.InetAddress.getAllByName0(InetAddress.java:1281) ~[na:1.8.0_212]
    at java.net.InetAddress.getAllByName(InetAddress.java:1193) ~[na:1.8.0_212]
    at java.net.InetAddress.getAllByName(InetAddress.java:1127) ~[na:1.8.0_212]
    at com.rabbitmq.client.DnsRecordIpAddressResolver.resolveIpAddresses(DnsRecordIpAddressResolver.java:83) ~[amqp-client-5.4.3.jar:5.4.3]
    at com.rabbitmq.client.DnsRecordIpAddressResolver.getAddresses(DnsRecordIpAddressResolver.java:73) ~[amqp-client-5.4.3.jar:5.4.3]
    at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:1098) ~[amqp-client-5.4.3.jar:5.4.3]
    at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:1054) ~[amqp-client-5.4.3.jar:5.4.3]
    at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:994) ~[amqp-client-5.4.3.jar:5.4.3]
    at org.springframework.amqp.rabbit.connection.AbstractConnectionFactory.createBareConnection(AbstractConnectionFactory.java:462) ~[spring-rabbit-2.1.6.RELEASE.jar:2.1.6.RELEASE]
    ... 6 common frames omitted

2019-06-11 14:56:37.912  INFO 3025 --- [           main] o.s.a.r.c.CachingConnectionFactory       : Attempting to connect to: [rabbitmq-invalid-host:5672]
</code>```

答:
You can listen for the exception in an event listener...

@SpringBootApplication
public class So56270299Application {

    public static void main(String[] args) {
        SpringApplication.run(So56270299Application.class, args);
    }

    @EventListener
    public void events(ListenerContainerConsumerFailedEvent event) {
        System.out.println(event);
        if (event.getThrowable().getCause() instanceof UnknownHostException) {
            System.exit(1);
        }
    }

    @RabbitListener(queues = "so56270299")
    public void listen(String in) {

    }

}
```

<p>and</p>

```spring.rabbitmq.host=junk
```

<p>and</p>

```2019-06-11 09:15:09.205  INFO 96620 --- [ntContainer#0-1] o.s.a.r.c.CachingConnectionFactory       : Attempting to connect to: [junk:5672]
2019-06-11 09:15:09.212  INFO 96620 --- [           main] com.example.So56270299Application        : Started So56270299Application in 0.704 seconds (JVM running for 1.071)
ListenerContainerConsumerFailedEvent [reason=Consumer raised exception, attempting restart, fatal=false, throwable=org.springframework.amqp.AmqpIOException: java.net.UnknownHostException: junk, container=SimpleMessageListenerContainer [concurrentConsumers=1, queueNames=[so56270299]]]
2019-06-11 09:15:14.255  INFO 96620 --- [       Thread-2] o.s.a.r.l.SimpleMessageListenerContainer : Waiting for workers to finish.
2019-06-11 09:15:14.255  INFO 96620 --- [       Thread-2] o.s.a.r.l.SimpleMessageListenerContainer : Successfully waited for workers to finish.
2019-06-11 09:15:14.257  INFO 96620 --- [       Thread-2] o.s.a.r.l.SimpleMessageListenerContainer : Shutdown ignored - container is not active already
```

Body:
for our integration-test profile we want to disable Spring's automatic reconnecting to fail fast.

Attempting to connect to: [rabbitmq-invalid-host:5672]
Error creating consumer; retrying in 5000
org.springframework.amqp.AmqpConnectException: org.springframework.amqp.AmqpIOException: java.net.UnknownHostException: rabbitmq-invalid-host

the following settings do not have any effect yet:

spring.rabbitmq.connection-timeout=1000
spring.rabbitmq.requested-heartbeat=1
spring.rabbitmq.listener.direct.missing-queues-fatal=true
spring.rabbitmq.listener.direct.retry.enabled=false
spring.rabbitmq.template.retry.enabled=false

any idea how to make amqp give up or even destroy the whole app-context?

full stacktrace:

2019-06-11 14:56:31.596  INFO 3025 --- [           main] o.s.a.r.c.CachingConnectionFactory       : Attempting to connect to: [rabbitmq-invalid-host:5672]
2019-06-11 14:56:31.698  INFO 3025 --- [           main] o.s.a.r.c.CachingConnectionFactory       : Attempting to connect to: [rabbitmq-invalid-host:5672]
2019-06-11 14:56:31.902  INFO 3025 --- [           main] o.s.a.r.c.CachingConnectionFactory       : Attempting to connect to: [rabbitmq-invalid-host:5672]
2019-06-11 14:56:32.305  INFO 3025 --- [           main] o.s.a.r.c.CachingConnectionFactory       : Attempting to connect to: [rabbitmq-invalid-host:5672]
2019-06-11 14:56:33.108  INFO 3025 --- [           main] o.s.a.r.c.CachingConnectionFactory       : Attempting to connect to: [rabbitmq-invalid-host:5672]
2019-06-11 14:56:34.709  INFO 3025 --- [           main] o.s.a.r.c.CachingConnectionFactory       : Attempting to connect to: [rabbitmq-invalid-host:5672]
2019-06-11 14:56:36.476  INFO 3025 --- [ntContainer#0-1] o.s.a.r.c.CachingConnectionFactory       : Attempting to connect to: [rabbitmq-invalid-host:5672]
2019-06-11 14:56:36.477 ERROR 3025 --- [ntContainer#0-1] o.s.a.r.l.DirectMessageListenerContainer : Error creating consumer; retrying in 5000

org.springframework.amqp.AmqpConnectException: org.springframework.amqp.AmqpIOException: java.net.UnknownHostException: rabbitmq-invalid-host
    at org.springframework.amqp.rabbit.listener.DirectMessageListenerContainer.doConsumeFromQueue(DirectMessageListenerContainer.java:667) [spring-rabbit-2.1.6.RELEASE.jar:2.1.6.RELEASE]
    at org.springframework.amqp.rabbit.listener.DirectMessageListenerContainer.consumeFromQueue(DirectMessageListenerContainer.java:645) [spring-rabbit-2.1.6.RELEASE.jar:2.1.6.RELEASE]
    at org.springframework.amqp.rabbit.listener.DirectMessageListenerContainer.startConsumers(DirectMessageListenerContainer.java:550) [spring-rabbit-2.1.6.RELEASE.jar:2.1.6.RELEASE]
    at org.springframework.amqp.rabbit.listener.DirectMessageListenerContainer.lambda$actualStart$1(DirectMessageListenerContainer.java:410) [spring-rabbit-2.1.6.RELEASE.jar:2.1.6.RELEASE]
    at java.lang.Thread.run(Thread.java:748) ~[na:1.8.0_212]
Caused by: org.springframework.amqp.AmqpIOException: java.net.UnknownHostException: rabbitmq-invalid-host
    at org.springframework.amqp.rabbit.support.RabbitExceptionTranslator.convertRabbitAccessException(RabbitExceptionTranslator.java:71) ~[spring-rabbit-2.1.6.RELEASE.jar:2.1.6.RELEASE]
    at org.springframework.amqp.rabbit.connection.AbstractConnectionFactory.createBareConnection(AbstractConnectionFactory.java:509) ~[spring-rabbit-2.1.6.RELEASE.jar:2.1.6.RELEASE]
    at org.springframework.amqp.rabbit.connection.CachingConnectionFactory.createConnection(CachingConnectionFactory.java:700) ~[spring-rabbit-2.1.6.RELEASE.jar:2.1.6.RELEASE]
    at org.springframework.amqp.rabbit.listener.DirectMessageListenerContainer.doConsumeFromQueue(DirectMessageListenerContainer.java:663) [spring-rabbit-2.1.6.RELEASE.jar:2.1.6.RELEASE]
    ... 4 common frames omitted
Caused by: java.net.UnknownHostException: rabbitmq-invalid-host
    at java.net.InetAddress.getAllByName0(InetAddress.java:1281) ~[na:1.8.0_212]
    at java.net.InetAddress.getAllByName(InetAddress.java:1193) ~[na:1.8.0_212]
    at java.net.InetAddress.getAllByName(InetAddress.java:1127) ~[na:1.8.0_212]
    at com.rabbitmq.client.DnsRecordIpAddressResolver.resolveIpAddresses(DnsRecordIpAddressResolver.java:83) ~[amqp-client-5.4.3.jar:5.4.3]
    at com.rabbitmq.client.DnsRecordIpAddressResolver.getAddresses(DnsRecordIpAddressResolver.java:73) ~[amqp-client-5.4.3.jar:5.4.3]
    at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:1098) ~[amqp-client-5.4.3.jar:5.4.3]
    at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:1054) ~[amqp-client-5.4.3.jar:5.4.3]
    at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:994) ~[amqp-client-5.4.3.jar:5.4.3]
    at org.springframework.amqp.rabbit.connection.AbstractConnectionFactory.createBareConnection(AbstractConnectionFactory.java:462) ~[spring-rabbit-2.1.6.RELEASE.jar:2.1.6.RELEASE]
    ... 6 common frames omitted

2019-06-11 14:56:37.912  INFO 3025 --- [           main] o.s.a.r.c.CachingConnectionFactory       : Attempting to connect to: [rabbitmq-invalid-host:5672]

Body:
You can listen for the exception in an event listener...

@SpringBootApplication
public class So56270299Application {

    public static void main(String[] args) {
        SpringApplication.run(So56270299Application.class, args);
    }

    @EventListener
    public void events(ListenerContainerConsumerFailedEvent event) {
        System.out.println(event);
        if (event.getThrowable().getCause() instanceof UnknownHostException) {
            System.exit(1);
        }
    }

    @RabbitListener(queues = "so56270299")
    public void listen(String in) {

    }

}

and

spring.rabbitmq.host=junk

and

2019-06-11 09:15:09.205  INFO 96620 --- [ntContainer#0-1] o.s.a.r.c.CachingConnectionFactory       : Attempting to connect to: [junk:5672]
2019-06-11 09:15:09.212  INFO 96620 --- [           main] com.example.So56270299Application        : Started So56270299Application in 0.704 seconds (JVM running for 1.071)
ListenerContainerConsumerFailedEvent [reason=Consumer raised exception, attempting restart, fatal=false, throwable=org.springframework.amqp.AmqpIOException: java.net.UnknownHostException: junk, container=SimpleMessageListenerContainer [concurrentConsumers=1, queueNames=[so56270299]]]
2019-06-11 09:15:14.255  INFO 96620 --- [       Thread-2] o.s.a.r.l.SimpleMessageListenerContainer : Waiting for workers to finish.
2019-06-11 09:15:14.255  INFO 96620 --- [       Thread-2] o.s.a.r.l.SimpleMessageListenerContainer : Successfully waited for workers to finish.
2019-06-11 09:15:14.257  INFO 96620 --- [       Thread-2] o.s.a.r.l.SimpleMessageListenerContainer : Shutdown ignored - container is not active already


问:
How to update Kepler.gl MapBox component style
I'm trying to figure out how to customize the kepler.gl's mapbox style. I want to make the mapbox component fill the screen width and height.

I've already tried updating it using the dispatcher with no success:

```<code>this.props.dispatch(loadCustomMapStyle({inputStyle: {url: 'mapbox://styles/mapbox/navigation-guidance-day-v4', id: 'some-id', style: {width: '100%', height: '100%'}}}));

this.props.dispatch(addCustomMapStyle());
</code>```

I also tried using the styled-components ThemeProvider:

```<code><ThemeProvider theme={{width: '100%', height:'100%'}}>
            <KeplerGl
                id="foo"
                mapboxApiAccessToken={'API_KEY'}
                store={store}
              />
</ThemeProvider>
</code>```

Any help would be greatly appreciated!

答:
The KeplerGl component takes in width and height props (documentation here). To change these with the dimensions of a div, you can use AutoSizer. For example, for the KeplerGl component to fill the screen you could wrap it in a div that is fullscreen as follows:

```<code>import AutoSizer from 'react-virtualized/dist/commonjs/AutoSizer';

...

<div style={{position: "absolute", width: "100%", height: "100%"}}>
    <AutoSizer>
        {({height, width}) => (
            <KeplerGl
                mapboxApiAccessToken={MAPBOX_TOKEN}
                id="map"
                width={width}
                height={height}
            />
        )}
    </AutoSizer>
</div>
</code>```

Body:
I'm trying to figure out how to customize the kepler.gl's mapbox style. I want to make the mapbox component fill the screen width and height.

I've already tried updating it using the dispatcher with no success:

this.props.dispatch(loadCustomMapStyle({inputStyle: {url: 'mapbox://styles/mapbox/navigation-guidance-day-v4', id: 'some-id', style: {width: '100%', height: '100%'}}}));

this.props.dispatch(addCustomMapStyle());

I also tried using the styled-components ThemeProvider:

<ThemeProvider theme={{width: '100%', height:'100%'}}>
            <KeplerGl
                id="foo"
                mapboxApiAccessToken={'API_KEY'}
                store={store}
              />
</ThemeProvider>

Any help would be greatly appreciated!

Body:
The KeplerGl component takes in width and height props (documentation here). To change these with the dimensions of a div, you can use AutoSizer. For example, for the KeplerGl component to fill the screen you could wrap it in a div that is fullscreen as follows:

import AutoSizer from 'react-virtualized/dist/commonjs/AutoSizer';

...

<div style={{position: "absolute", width: "100%", height: "100%"}}>
    <AutoSizer>
        {({height, width}) => (
            <KeplerGl
                mapboxApiAccessToken={MAPBOX_TOKEN}
                id="map"
                width={width}
                height={height}
            />
        )}
    </AutoSizer>
</div>


问:
Stopping a server in a subprocess with its shutdown method
I am implementing a Server class in CPython 3.7 on Windows 10 with a Server.serve method that starts the serving forever and a Server.shutdown method that stops the serving. I need to run multiple server instances in subprocesses.

Running a server instance in a subthread stops the instance as expected:

```<code>import threading
import time

class Server:

    def __init__(self):
        self.shutdown_request = False

    def serve(self):
        print("serving")

        while not self.shutdown_request:
            print("hello")
            time.sleep(1)

        print("done")

    def shutdown(self):
        print("stopping")
        self.shutdown_request = True

if __name__ == "__main__":
    server = Server()
    threading.Thread(target=server.serve).start()
    time.sleep(5)
    server.shutdown()
</code>```

However running a server instance in a subprocess does not stop the instance, unexpectedly:

```<code>import multiprocessing
import time

class Server:

    def __init__(self):
        self.shutdown_request = False

    def serve(self):
        print("serving")

        while not self.shutdown_request:
            print("hello")
            time.sleep(1)

        print("done")

    def shutdown(self):
        print("stopping")
        self.shutdown_request = True

if __name__ == "__main__":
    server = Server()
    multiprocessing.Process(target=server.serve).start()
    time.sleep(5)
    server.shutdown()
</code>```

I suspect that in the multiprocessing case, the self.shutdown_request attribute is not shared between the parent process and the subprocess, and therefore the server.shutdown() call does not affect the running server instance in the subprocess.

I know I could solve this with multiprocessing.Event:

```<code>import multiprocessing
import time

class Server:

    def __init__(self, shutdown_event):
        self.shutdown_event = shutdown_event

    def serve(self):
        print("serving")

        while not self.shutdown_event.is_set():
            print("hello")
            time.sleep(1)

        print("done")

if __name__ == "__main__":
    shutdown_event = multiprocessing.Event()
    server = Server(shutdown_event)
    multiprocessing.Process(target=server.serve).start()
    time.sleep(5)
    shutdown_event.set()
</code>```

But I want to keep the Server.shutdown method instead of changing the Server interface according to its usage (single processing v. multiprocessing) and I don't want clients to deal with multiprocessing.Event.

答:
I have finally figured out a solution by myself:

```<code>import multiprocessing
import time

class Server:

    def __init__(self):
        self.shutdown_event = multiprocessing.Event()

    def serve(self):
        print("serving")

        while not self.shutdown_event.is_set():
            print("hello")
            time.sleep(1)

        print("done")

    def shutdown(self):
        print("stopping")
        self.shutdown_event.set()

if __name__ == "__main__":
    server = Server()
    multiprocessing.Process(target=server.serve).start()
    time.sleep(5)
    server.shutdown()
</code>```

It works in either case: single processing (multithreading) and multiprocessing.

Remark. — With a multiprocessing.Event() in the __init__ method, Server instances are no longer pickable. That might be a problem if one wants to call a Server instance in a process pool (either with multiprocessing.pool.Pool or concurrent.futures.ProcessPoolExecutor). In this case, one should replace multiprocessing.Event() with multiprocessing.Manager().Event() in the __init__ method.

Body:
I am implementing a Server class in CPython 3.7 on Windows 10 with a Server.serve method that starts the serving forever and a Server.shutdown method that stops the serving. I need to run multiple server instances in subprocesses.

Running a server instance in a subthread stops the instance as expected:

import threading
import time

class Server:

    def __init__(self):
        self.shutdown_request = False

    def serve(self):
        print("serving")

        while not self.shutdown_request:
            print("hello")
            time.sleep(1)

        print("done")

    def shutdown(self):
        print("stopping")
        self.shutdown_request = True

if __name__ == "__main__":
    server = Server()
    threading.Thread(target=server.serve).start()
    time.sleep(5)
    server.shutdown()

However running a server instance in a subprocess does not stop the instance, unexpectedly:

import multiprocessing
import time

class Server:

    def __init__(self):
        self.shutdown_request = False

    def serve(self):
        print("serving")

        while not self.shutdown_request:
            print("hello")
            time.sleep(1)

        print("done")

    def shutdown(self):
        print("stopping")
        self.shutdown_request = True

if __name__ == "__main__":
    server = Server()
    multiprocessing.Process(target=server.serve).start()
    time.sleep(5)
    server.shutdown()

I suspect that in the multiprocessing case, the self.shutdown_request attribute is not shared between the parent process and the subprocess, and therefore the server.shutdown() call does not affect the running server instance in the subprocess.

I know I could solve this with multiprocessing.Event:

import multiprocessing
import time

class Server:

    def __init__(self, shutdown_event):
        self.shutdown_event = shutdown_event

    def serve(self):
        print("serving")

        while not self.shutdown_event.is_set():
            print("hello")
            time.sleep(1)

        print("done")

if __name__ == "__main__":
    shutdown_event = multiprocessing.Event()
    server = Server(shutdown_event)
    multiprocessing.Process(target=server.serve).start()
    time.sleep(5)
    shutdown_event.set()

But I want to keep the Server.shutdown method instead of changing the Server interface according to its usage (single processing v. multiprocessing) and I don't want clients to deal with multiprocessing.Event.

Body:
I have finally figured out a solution by myself:

import multiprocessing
import time

class Server:

    def __init__(self):
        self.shutdown_event = multiprocessing.Event()

    def serve(self):
        print("serving")

        while not self.shutdown_event.is_set():
            print("hello")
            time.sleep(1)

        print("done")

    def shutdown(self):
        print("stopping")
        self.shutdown_event.set()

if __name__ == "__main__":
    server = Server()
    multiprocessing.Process(target=server.serve).start()
    time.sleep(5)
    server.shutdown()

It works in either case: single processing (multithreading) and multiprocessing.

Remark. — With a multiprocessing.Event() in the __init__ method, Server instances are no longer pickable. That might be a problem if one wants to call a Server instance in a process pool (either with multiprocessing.pool.Pool or concurrent.futures.ProcessPoolExecutor). In this case, one should replace multiprocessing.Event() with multiprocessing.Manager().Event() in the __init__ method.


答:
Your query is Wrong you should use

You were using DateTime.Now which is Today's Date and current time, so you need to use DateTime.Today which is Today's Date and 00:00 in time.

```<code>return _context.FridgeTemperture.Where(x => x.UpdatedDate >= DateTime.Today && x.Fridgetemp > 26).Count();
</code>```

Update:

And if you want just Today's records.

```<code>_context.FridgeTemperture.Where(
        x =>
        x.UpdatedDate >= DateTime.Today
        && x.UpdatedDate < DateTime.Today.AddDays(1)
        && x.Fridgetemp > 26
    ).Count();
</code>```

Title: How to count today's records in SQL Server using linq

Body:
I want to count the no of records with today's date using a linq query.

I'm getting 0, but it should be 2.

Sample data

Id  ShopId  Fridgetemp  UpdatedDate
---------------------------------------------------
1   NULL    23.00       2019-05-27 17:11:48.0759186
2   1       11.00       2019-05-27 17:19:23.8062202
3   1       7.00        2019-05-27 18:29:59.4886314
4   1       7.00        2019-05-27 18:44:46.6347567
5   1       27.00       2019-05-28 19:12:39.0549385
6   1       7.00        2019-05-28 19:14:59.1307374
7   1       23.00       2019-05-28 19:42:11.0724320
8   1       28.00       2019-05-28 20:08:13.3121901

Linq query

private int CheckSentStatus()
{
    return _context.FridgeTemperture
                   .Where(x => x.UpdatedDate >= DateTime.Now &&
                               x.Fridgetemp > 26).Count();
}

Ex op - 2

Data type of UpdatedDate is datetime2(7).

Body:
Your query is Wrong you should use

You were using DateTime.Now which is Today's Date and current time, so you need to use DateTime.Today which is Today's Date and 00:00 in time.

return _context.FridgeTemperture.Where(x => x.UpdatedDate >= DateTime.Today && x.Fridgetemp > 26).Count();

Update:

And if you want just Today's records.

_context.FridgeTemperture.Where(
        x =>
        x.UpdatedDate >= DateTime.Today
        && x.UpdatedDate < DateTime.Today.AddDays(1)
        && x.Fridgetemp > 26
    ).Count();


问:
Allow null - Javascript
I have this regex for a input only numbers and works fine. The problem is that I also want to allow null.

```<code>validator="/([0-9])$/"
</code>```

I tried using the | but now it allows everything

```<code>validator="/([0-9]|)$/"
</code>```

Any ideas?

答:
my suggestion is keep it simple so you can do something like this:</p>

```<code>validator = /\d+/;
let strToValidate = 'something here';
if (strToValidate === null || validator.test(strToValidate) {
  doSomething();
}
</code>```

Title: Allow null - Javascript

Body:
I have this regex for a input only numbers and works fine. The problem is that I also want to allow null.

validator="/([0-9])$/"

I tried using the | but now it allows everything

validator="/([0-9]|)$/"

Any ideas?

Body:
my suggestion is keep it simple so you can do something like this:

validator = /\d+/;
let strToValidate = 'something here';
if (strToValidate === null || validator.test(strToValidate) {
  doSomething();
}


问:
How to access "parent" index of map() function inside "child" map()
I have an array of array of dates. I need to make a calendar-like table of those dates. Each cell is a stateless component with two buttons, each button going to have a callback function modifying data corresponding to given date.

Table is made by mapping the "parent" array consisting arrays of days (each "child array has length >= 6 for sake of being a calendar) and then each child array is mapped, thus creating rows.

But since each table row is made by mapping separate array, how do I keep track of number of cells in general? I want to each cell have unique index despite being made by separate map().

Why do I want that? Because clicking on a button inside each cell needs to modify some data corresponding to date the cell represents

I have tried mapping array of dates (which is used to make array of arrays) to object to have easy access to each date through callback methods.

I tried some arithmetic operations on "parent" and "child" map() methods but I guess index prop isn't inherited

I even tried to create an array with dates as custom keys, each element being an array of two elements (that's the data I need to operate on through those callbacks)

Example array of array of dates

```<code>let arrayOfWeeks = [
 [
  "01.05.2019",
  "02.05.2019",
  "03.05.2019",
  "04.05.2019",
  "05.05.2019",
  "06.05.2019",
  "07.05.2019",
 ],
 [
  "08.05.2019",
  "09.05.2019",
  "10.05.2019",
  "11.05.2019",
  "12.05.2019",
  "13.05.2019",
  "14.05.2019",
  ]
]
</code>```

Calendar table

```<code><tbody>
  {arrayOfWeeks.map((row, index) =>
    <tr key={index}>
      {row.map((date, index) =>
        <CalendarCell key={index} date={date} index={index} callback={() => this.onCallback(someProps)} />
      )}
    </tr>
  )}
</tbody>
</code>```

CalendarCell stateless component

```<code>const CalendarCell = (props: any) => (
    <td>
        <Row>
            <Col>
                {props.date}
            </Col>
        </Row>
        <Row>
            <Col>
                <Button onClick={props.onCallback}>1</Button>
                <Button onClick={props.onCallback}>2</Button>
            </Col>
        </Row>
    </td>
)
</code>```

I want each CalendarCell component to have unique key/index/id/whatever to be able to access an array in parent component through them

UPDATE:
Thanks Mishel!

Here is what fixed code looks like

```<code><tbody>
  {arrayOfWeeks.map((row, index) =>
    <tr key={index}>
      {row.map((date, index2) =>
        <CallendarCell key={index} date={date} index={index * 7 + index2} onCallback={this.onCallback} />
     )}
   </tr>
  )}
</tbody>
</code>```

Since there are two unique names for indexes, some maths can be done

答:
use different names for index. something like:

```<code><tbody>
    {arrayOfWeeks.map((row, index) =>
        <tr key={index}>
            {row.map((date, index2) =>
                <CalendarCell key={index} date={date} index={index}
                 callback={() => this.onCallback(someProps)} />
            )}
               </tr>
    )}
</tbody>
</code>```

in general:

when you have two functions nested in each other like that you can do this:

```<code>const A = (a)=>{
  const b = (b)=>{
    console.log('A:',a)
    console.log('B:',b)
  }
  b(2);
}
a('1');
//output will be:
// A:1
// B:2
</code>```

If this is not clear for you or you have questions let me know

Body:
I have an array of array of dates. I need to make a calendar-like table of those dates. Each cell is a stateless component with two buttons, each button going to have a callback function modifying data corresponding to given date.

Table is made by mapping the "parent" array consisting arrays of days (each "child array has length >= 6 for sake of being a calendar) and then each child array is mapped, thus creating rows.

But since each table row is made by mapping separate array, how do I keep track of number of cells in general? I want to each cell have unique index despite being made by separate map().

Why do I want that? Because clicking on a button inside each cell needs to modify some data corresponding to date the cell represents

I have tried mapping array of dates (which is used to make array of arrays) to object to have easy access to each date through callback methods.

I tried some arithmetic operations on "parent" and "child" map() methods but I guess index prop isn't inherited

I even tried to create an array with dates as custom keys, each element being an array of two elements (that's the data I need to operate on through those callbacks)

Example array of array of dates

let arrayOfWeeks = [
 [
  "01.05.2019",
  "02.05.2019",
  "03.05.2019",
  "04.05.2019",
  "05.05.2019",
  "06.05.2019",
  "07.05.2019",
 ],
 [
  "08.05.2019",
  "09.05.2019",
  "10.05.2019",
  "11.05.2019",
  "12.05.2019",
  "13.05.2019",
  "14.05.2019",
  ]
]

Calendar table

  {arrayOfWeeks.map((row, index) =>

      {row.map((date, index) =>
        <CalendarCell key={index} date={date} index={index} callback={() => this.onCallback(someProps)} />
      )}

  )}

CalendarCell stateless component

const CalendarCell = (props: any) => (

        <Row>
            <Col>
                {props.date}
            </Col>
        </Row>
        <Row>
            <Col>
                <Button onClick={props.onCallback}>1</Button>
                <Button onClick={props.onCallback}>2</Button>
            </Col>
        </Row>

)

I want each CalendarCell component to have unique key/index/id/whatever to be able to access an array in parent component through them

UPDATE:
Thanks Mishel!

Here is what fixed code looks like

  {arrayOfWeeks.map((row, index) =>

      {row.map((date, index2) =>
        <CallendarCell key={index} date={date} index={index * 7 + index2} onCallback={this.onCallback} />
     )}

  )}

Since there are two unique names for indexes, some maths can be done

Body:
use different names for index. something like:

<tbody>
    {arrayOfWeeks.map((row, index) =>
        <tr key={index}>
            {row.map((date, index2) =>
                <CalendarCell key={index} date={date} index={index}
                 callback={() => this.onCallback(someProps)} />
            )}
               </tr>
    )}
</tbody>

in general:

when you have two functions nested in each other like that you can do this:

const A = (a)=>{
  const b = (b)=>{
    console.log('A:',a)
    console.log('B:',b)
  }
  b(2);
}
a('1');
//output will be:
// A:1
// B:2

If this is not clear for you or you have questions let me know


问:
Kotlin setup via gradle on eclipse
Struggling to get Kotlin running on eclipse.

I've started new graddle project. Added dependencies as prescribed on kotlin's site.

Build passes without errors.

I've created 'main.kt' file under src/java/main with:

```<code>fun main(args: Array<String>) {
    println("foo")
}
</code>```

BUT, I have two problems:
1. anything from kotlin e.g. println highlighted as 'unresolved reference'.
2. I can't run a program - Error: Could not find or load main class MainKt (rightclick on main.kr run as 'kotlin application')

If I create 'new kotlin project' everything works.

my graddle build script:

```<code>plugins {
    id "org.jetbrains.kotlin.jvm" version "1.1.2-2"
}

repositories {

    jcenter()

    mavenCentral()
}

dependencies {

    //api 'org.apache.commons:commons-math3:3.6.1'

    implementation 'com.google.guava:guava:21.0'

    testImplementation 'junit:junit:4.12'

    compile "org.jetbrains.kotlin:kotlin-stdlib:1.1.2-2"
    compile "org.jetbrains.kotlin:kotlin-stdlib-jre8"

    compile "org.jetbrains.kotlin:kotlin-reflect"
    testCompile "org.jetbrains.kotlin:kotlin-test"
    testCompile "org.jetbrains.kotlin:kotlin-test-junit"

}

sourceSets {
    main.java.srcDirs = ['src/main/java']
    main.kotlin.srcDirs = ['src/main/java', 'src/main/kotlin']
    main.resources.srcDirs = ['src/main/resources']
}
</code>```

What did I do wrong?

I've zero Java knowledge if that helps, so probably I've made some trivial error.

UPDATE:

Installed a Spring plugin and generated a new web app via it including gradle.
But Kotlin behaves unpredictably there too.

At first I was not able to run it as run as Kotlin application and it errored with main could not be found, BUT sometimes it run and crashed immediately. It started to launch and crash after I've deleted and edited classes, tried creating it under other package, removing and adding Kotlin (I can't reproduce sequence to make it work again).

Fun part that gradle boot build launches everything and all works it somehow finds Kotlin's main.

Probably some issue with Kotlin plugin itself (it's load probably depends on certain events that doesn't always fire)

答:
I would like to add to Felipe Nascimento's answer that the location of the .settings folder does not yet exist. It works when the line below is inserted into that answer.

```<code>def kotlinPrefs = file("../${project.name}/.settings/org.jetbrains.kotlin.core.prefs".toString())
</code>```

Title: Kotlin setup via gradle on eclipse

Body:
Struggling to get Kotlin running on eclipse.

I've started new graddle project. Added dependencies as prescribed on kotlin's site.

Build passes without errors.

I've created 'main.kt' file under src/java/main with:

fun main(args: Array<String>) {
    println("foo")
}

BUT, I have two problems:
1. anything from kotlin e.g. println highlighted as 'unresolved reference'.
2. I can't run a program - Error: Could not find or load main class MainKt (rightclick on main.kr run as 'kotlin application')

If I create 'new kotlin project' everything works.

my graddle build script:

plugins {
    id "org.jetbrains.kotlin.jvm" version "1.1.2-2"
}

repositories {

    jcenter()

    mavenCentral()
}

dependencies {

    //api 'org.apache.commons:commons-math3:3.6.1'

    implementation 'com.google.guava:guava:21.0'

    testImplementation 'junit:junit:4.12'

    compile "org.jetbrains.kotlin:kotlin-stdlib:1.1.2-2"
    compile "org.jetbrains.kotlin:kotlin-stdlib-jre8"

    compile "org.jetbrains.kotlin:kotlin-reflect"
    testCompile "org.jetbrains.kotlin:kotlin-test"
    testCompile "org.jetbrains.kotlin:kotlin-test-junit"

}

sourceSets {
    main.java.srcDirs = ['src/main/java']
    main.kotlin.srcDirs = ['src/main/java', 'src/main/kotlin']
    main.resources.srcDirs = ['src/main/resources']
}

What did I do wrong?

I've zero Java knowledge if that helps, so probably I've made some trivial error.

UPDATE:

Installed a Spring plugin and generated a new web app via it including gradle.
But Kotlin behaves unpredictably there too.

At first I was not able to run it as run as Kotlin application and it errored with main could not be found, BUT sometimes it run and crashed immediately. It started to launch and crash after I've deleted and edited classes, tried creating it under other package, removing and adding Kotlin (I can't reproduce sequence to make it work again).

Fun part that gradle boot build launches everything and all works it somehow finds Kotlin's main.

Probably some issue with Kotlin plugin itself (it's load probably depends on certain events that doesn't always fire)

Body:
I would like to add to Felipe Nascimento's answer that the location of the .settings folder does not yet exist. It works when the line below is inserted into that answer.

def kotlinPrefs = file("../${project.name}/.settings/org.jetbrains.kotlin.core.prefs".toString())


问:
Why would I get a Forbidden message from AWS API Gateway, even though things are working internally?
I have AWS API gateway setup for a public endpoint with no auth. It connects to a websocket that triggers a Lambda.

I was creating connections with Python's websocket-client lib at https://pypi.org/project/websocket_client/.

I noticed that connections would fail ~10% of the time, and get worse as I increased load. I can't find anywhere that would be throttling me seeing as my general API Gateway settings say Your current account level throttling rate is 10000 requests per second with a burst of 5000 requests.. That’s beside the point that just 2-3 requests per second would trigger issue fairly often.

Meanwhile the failure response would be like {u'message': u'Forbidden', u'connectionId': u'Z2Jp-dR5vHcCJkg=', u'requestId': u'Z2JqAEJRvHcFzvg='}

I went into my CloudWatch log insights and searched for the connection ID and request ID. The log group for the API gateway would find no results with either ID. Yet a search on my Lambda that fires on websocket connect, would have a log with that connection ID. The log showed everything running as expected on our side. The lambda simply runs a MySQL query that fires.

Why would I get a response of forbidden, despite the lambda working as expected?

The existing question over at getting message: forbidden reply from AWS API gateway, seems to address if it's ALWAYS returning forbidden for some private endpoints. Nothing lined up with my use case.

UPDATE

I think this may be related to locust.io, or python, which I'm using to connect every second. I installed https://www.npmjs.com/package/wscat on my machine and am connecting and closing as fast as possible repeatedly. I am not getting a Forbidden message. It's just extra confusing since I'm not sure how the way I connect would randomly spit back a Forbidden message some of the time.

class SocketClient(object):
    def __init__(self, host):
        self.host = host
        self.session_id = uuid4().hex

    def connect(self):
        self.ws = websocket.WebSocket()
        self.ws.settimeout(10)
        self.ws.connect(self.host)

        events.quitting += self.on_close

        data = self.attach_session({})
        return data

    def attach_session(self, payload):
        message_id = uuid4().hex
        start_time = time.time()
        e = None
        try:
            print("Sending payload {}".format(payload))
            data = self.send_with_response(payload)
            assert data['mykey']

        except AssertionError as exp:
            e = exp
        except Exception as exp:
            e = exp
            self.ws.close()
            self.connect()
        elapsed = int((time.time() - start_time) * 1000)
        if e:
            events.request_failure.fire(request_type='sockjs', name='send',
                                        response_time=elapsed, exception=e)
        else:
            events.request_success.fire(request_type='sockjs', name='send',
                                        response_time=elapsed,
                                        response_length=0)
        return data

    def send_with_response(self, payload):
        json_data = json.dumps(payload)

        g = gevent.spawn(self.ws.send, json_data)
        g.get(block=True, timeout=2)
        g = gevent.spawn(self.ws.recv)
        result = g.get(block=True, timeout=10)

        json_data = json.loads(result)
        return json_data
    def on_close(self):
        self.ws.close()

class ActionsTaskSet(TaskSet):
    @task
    def streams(self):
        response = self.client.connect()
        logger.info("Connect Response: {}".format(response))

class WSUser(Locust):
    task_set = ActionsTaskSet
    min_wait = 1000
    max_wait = 3000

    def __init__(self, *args, **kwargs):
        super(WSUser, self).__init__(*args, **kwargs)
        self.client = SocketClient('wss://mydomain.amazonaws.com/endpoint')
```

Update 2

I have enabled access logs, the one type of log that wasn't there before. I can now see that my lambdas are always getting a 200 with no issue. The 403 is coming from some MESSAGE eventType that doesn't hit an actual routeKey. Not sure where it comes from, but pretty sure finding that answer will solve this.

I was also able to confirm there are no ENI issues.

答:
The payload in my example is empty. The API is configured to use $request.body.action to know the routeKey. Connecting makes the default $connect route work.

Adding a proper action in my body made the 403s go away. This is the solution. I was essentially getting 200 responses from the act of connecting and disconnecting, but was getting the 403 whenever my message without a payload went through.

Body:
I have AWS API gateway setup for a public endpoint with no auth. It connects to a websocket that triggers a Lambda.

I was creating connections with Python's websocket-client lib at https://pypi.org/project/websocket_client/.

I noticed that connections would fail ~10% of the time, and get worse as I increased load. I can't find anywhere that would be throttling me seeing as my general API Gateway settings say Your current account level throttling rate is 10000 requests per second with a burst of 5000 requests.. That’s beside the point that just 2-3 requests per second would trigger issue fairly often.

Meanwhile the failure response would be like {u'message': u'Forbidden', u'connectionId': u'Z2Jp-dR5vHcCJkg=', u'requestId': u'Z2JqAEJRvHcFzvg='}

I went into my CloudWatch log insights and searched for the connection ID and request ID. The log group for the API gateway would find no results with either ID. Yet a search on my Lambda that fires on websocket connect, would have a log with that connection ID. The log showed everything running as expected on our side. The lambda simply runs a MySQL query that fires.

Why would I get a response of forbidden, despite the lambda working as expected?

The existing question over at getting message: forbidden reply from AWS API gateway, seems to address if it's ALWAYS returning forbidden for some private endpoints. Nothing lined up with my use case.

UPDATE

I think this may be related to locust.io, or python, which I'm using to connect every second. I installed https://www.npmjs.com/package/wscat on my machine and am connecting and closing as fast as possible repeatedly. I am not getting a Forbidden message. It's just extra confusing since I'm not sure how the way I connect would randomly spit back a Forbidden message some of the time.

class SocketClient(object):
    def __init__(self, host):
        self.host = host
        self.session_id = uuid4().hex

    def connect(self):
        self.ws = websocket.WebSocket()
        self.ws.settimeout(10)
        self.ws.connect(self.host)

        events.quitting += self.on_close

        data = self.attach_session({})
        return data

    def attach_session(self, payload):
        message_id = uuid4().hex
        start_time = time.time()
        e = None
        try:
            print("Sending payload {}".format(payload))
            data = self.send_with_response(payload)
            assert data['mykey']

        except AssertionError as exp:
            e = exp
        except Exception as exp:
            e = exp
            self.ws.close()
            self.connect()
        elapsed = int((time.time() - start_time) * 1000)
        if e:
            events.request_failure.fire(request_type='sockjs', name='send',
                                        response_time=elapsed, exception=e)
        else:
            events.request_success.fire(request_type='sockjs', name='send',
                                        response_time=elapsed,
                                        response_length=0)
        return data

    def send_with_response(self, payload):
        json_data = json.dumps(payload)

        g = gevent.spawn(self.ws.send, json_data)
        g.get(block=True, timeout=2)
        g = gevent.spawn(self.ws.recv)
        result = g.get(block=True, timeout=10)

        json_data = json.loads(result)
        return json_data
    def on_close(self):
        self.ws.close()

class ActionsTaskSet(TaskSet):
    @task
    def streams(self):
        response = self.client.connect()
        logger.info("Connect Response: {}".format(response))

class WSUser(Locust):
    task_set = ActionsTaskSet
    min_wait = 1000
    max_wait = 3000

    def __init__(self, *args, **kwargs):
        super(WSUser, self).__init__(*args, **kwargs)
        self.client = SocketClient('wss://mydomain.amazonaws.com/endpoint')

Update 2

I have enabled access logs, the one type of log that wasn't there before. I can now see that my lambdas are always getting a 200 with no issue. The 403 is coming from some MESSAGE eventType that doesn't hit an actual routeKey. Not sure where it comes from, but pretty sure finding that answer will solve this.

I was also able to confirm there are no ENI issues.


问:
Xamarin forms Label new line
I have a Label in my Xamarin forms page, that receives it's Text from it's view model, and the text contains the \n character.
How can I make the Label to automatically split the text into two different rows?

答:
You can do that it like that:</p>

```<code>Text = "First line string
Second line string"
</code>```

Title: Xamarin forms Label new line

Body:
You can do that it like that:

Text = "First line string&#x0a;Second line string"


问:
Show each row colums information php and sql
I want to print the values of custom columns for all rows, I've got a sql developer file, i mean that i want to print some columns of every rows, if for example my table is named client and has name, subname and email i want to print every client name, subname and email I've found how to make it with mysql but I want to make it with php and sql developer.

The code I've shown only shows the first user name and not the rest names and other columns of other users.

```<code><?php
function clientes($conexion) {
    $consulta = "SELECT NOMBRE FROM CLIENTE";
    $stmt = $conexion -> prepare($consulta);
    $stmt -> execute();
    return $stmt -> fetchColumn();
}

echo clientes($conexion);
?>
</code>```

答:
You're only getting one column since you're explicitly only ask for one column (by using fetchColumn()) and the fact that you've only told SQL to return one single column.

Change your query:

```<code>// Replace column1 etc to the real column names
SELECT column1, column2, column3 FROM CLIENTE
</code>```

Then instead of using fetchColumn() (which is for fetching one column), use:

```<code>return $stmt->fetchAll(PDO::FETCH_ASSOC);
</code>```

and you should get an array containing associative arrays (one per row) with all three columns.

However, you have another issue:

```<code>echo clientes($conexion);
</code>```

Since you're now returning an array, you can't just echo it straight off. If you do, you will get a warning about "Array to string conversion". You need to iterate through the array and output the data as you want it:

```<code>$data = clientes($conexion);

// Again, change the column names
foreach ($data as $row) {
    echo $row['column1'];
    echo $row['column2'];
    echo $row['column3'];
}
</code>```

This will output all the data. You get to decide on the layout though.

Body:
I want to print the values of custom columns for all rows, I've got a sql developer file, i mean that i want to print some columns of every rows, if for example my table is named client and has name, subname and email i want to print every client name, subname and email I've found how to make it with mysql but I want to make it with php and sql developer.

The code I've shown only shows the first user name and not the rest names and other columns of other users.

<?php
function clientes($conexion) {
    $consulta = "SELECT NOMBRE FROM CLIENTE";
    $stmt = $conexion -> prepare($consulta);
    $stmt -> execute();
    return $stmt -> fetchColumn();
}

echo clientes($conexion);
?>

Body:
You're only getting one column since you're explicitly only ask for one column (by using fetchColumn()) and the fact that you've only told SQL to return one single column.

Change your query:

// Replace column1 etc to the real column names
SELECT column1, column2, column3 FROM CLIENTE

Then instead of using fetchColumn() (which is for fetching one column), use:

return $stmt->fetchAll(PDO::FETCH_ASSOC);

and you should get an array containing associative arrays (one per row) with all three columns.

However, you have another issue:

echo clientes($conexion);

Since you're now returning an array, you can't just echo it straight off. If you do, you will get a warning about "Array to string conversion". You need to iterate through the array and output the data as you want it:

$data = clientes($conexion);

// Again, change the column names
foreach ($data as $row) {
    echo $row['column1'];
    echo $row['column2'];
    echo $row['column3'];
}

This will output all the data. You get to decide on the layout though.


问:
Codecademy howOld syntax error at else if
As a coding noob I am always struggling with syntax in my Javascript exercises in Codecademy.  This is my first problem I havent been able to solve without some internet search help - my apologies if this is already solved here.

I am usually a semi-colon away from solving it, but not this time (?).  Im attempting to accommodate 3 outcomes:

someone inputs a year in the future and I tell them their age in that year.

someone inputs a year before they were born and I give them the # of years until they were born.

someone inputs a year after they were born and I give them their age at that time.

I've spent too much time moving curly brackets and semi colons and I guess I just cant see the error.

```<code>const howOld = (age, year) =>

 {
  if
    (year > 2019);
    let calculatedAge = ( year - 2019 + age );
  {
  return `You will be ${calculatedAge } in the year ${year}.`;

  } else if
    (year < (2019-age));
    let calculatedAge = ( 2019 - year + age );
  {
  return `The year ${year } was ${calculatedAge } years before you were
born.`;

  } else
    let calculatedAge = ( year - 2019 + age );
  {
  return `You were ${calculatedAge} in the year ${year}. `;
  }

};

console.log(howOld(47,2000))
</code>```

I am getting a syntax error at my 'else if' statement.

答:
This should do it

```<code>    const howOld = (age, year) =>

 {
  if(year > 2019)
  {
    let calculatedAge = ( year - 2019 + age );
    return `You will be ${calculatedAge } in the year ${year}.`;

  }
  else if(year < (2019-age))
  {
    let calculatedAge = ( 2019 - year + age );
    return `The year ${year } was ${calculatedAge } years before you were born.`;
  }
  else
  {
    let calculatedAge = ( year - 2019 + age );
    return `You were ${calculatedAge} in the year ${year}. `;
  }

};

console.log(howOld(47,2000))
</code>```

To explain your mistake, you had your if statement wrong
instead of having

```<code>if(condition){do}
</code>```

you had

```<code>if(condition);do{do}
</code>```

Body:
As a coding noob I am always struggling with syntax in my Javascript exercises in Codecademy.  This is my first problem I havent been able to solve without some internet search help - my apologies if this is already solved here.

I am usually a semi-colon away from solving it, but not this time (?).  Im attempting to accommodate 3 outcomes:

someone inputs a year in the future and I tell them their age in that year.

someone inputs a year before they were born and I give them the # of years until they were born.

someone inputs a year after they were born and I give them their age at that time.

I've spent too much time moving curly brackets and semi colons and I guess I just cant see the error.

const howOld = (age, year) =>

 {
  if
    (year > 2019);
    let calculatedAge = ( year - 2019 + age );
  {
  return `You will be ${calculatedAge } in the year ${year}.`;

  } else if
    (year < (2019-age));
    let calculatedAge = ( 2019 - year + age );
  {
  return `The year ${year } was ${calculatedAge } years before you were
born.`;

  } else
    let calculatedAge = ( year - 2019 + age );
  {
  return `You were ${calculatedAge} in the year ${year}. `;
  }

};

console.log(howOld(47,2000))

I am getting a syntax error at my 'else if' statement.

Body:
This should do it

    const howOld = (age, year) =>

 {
  if(year > 2019)
  {
    let calculatedAge = ( year - 2019 + age );
    return `You will be ${calculatedAge } in the year ${year}.`;

  }
  else if(year < (2019-age))
  {
    let calculatedAge = ( 2019 - year + age );
    return `The year ${year } was ${calculatedAge } years before you were born.`;
  }
  else
  {
    let calculatedAge = ( year - 2019 + age );
    return `You were ${calculatedAge} in the year ${year}. `;
  }

};

console.log(howOld(47,2000))

To explain your mistake, you had your if statement wrong
instead of having

if(condition){do}

you had

if(condition);do{do}


问:
Isn't this HTML5 date input supposed to have a spinner in Fx4 and Safari5?
Loading

http://diveintohtml5.ep.io/examples/input-type-date.html

```<code><form>
  <input name="birthday" type="date">
  <input type="submit" value="Go">
</form>
</code>```

into Fx4 and Safari5 on XPsp3, I expected to see some kind of enhancement like the up/down on type="number".

Do you?

Update: A date picker appears in Opera - nothing in Safari5 or FX4 on XP

答: "Up" and "down" is for type="number", not type="date", isn't it? This page suggests, that the UIs for the new types are not yet supported in anything but Opera.

Body:
Loading

http://diveintohtml5.ep.io/examples/input-type-date.html

<form>
  <input name="birthday" type="date">
  <input type="submit" value="Go">
</form>

into Fx4 and Safari5 on XPsp3, I expected to see some kind of enhancement like the up/down on type="number".

Do you?

Update: A date picker appears in Opera - nothing in Safari5 or FX4 on XP


答:
You can create a function like validator

Example:

const validator = number => ((/([0-9])$/).test(number) || number === null);

console.log(validator("dddd"))
console.log(validator(null))
console.log(validator(54))```

Title: Allow null - Javascript


问:
Python specify few list return types
I’m writing a python project with PyCharm.
I have a funtion which can return multiple types:

```<code>list(User), list(Player), list(Builder)
</code>```

I want to use pycharm auto complete features but it doesn’t seem to infer the right possible return types, so I read about the typing module and tried to use this syntax as return type:

```<code>-> Union[List[Builder], List[User], List[Player]]
</code>```

And yet PyCharm suggest Builder’s attributes only, which is the first thing one on the Union expression.
If I use non-list return types, typing works as expected and suggest the right attribute from all types written in the Union expression. I.E:

```<code>-> Union[Builder, User, Player]
</code>```

Is there anyway to fix this?

Thanks!

答:
I'm using for that docstrings. I kill two birds with one stone like that. The first one is having my method documented if I was not clear :)

```<code>def method_a():
    """
    :return:
    list of int, list of str
    """
    return [1, 2, 3], ["a", "b", "c"]
</code>```

Title: Python specify few list return types

Body:
I’m writing a python project with PyCharm.
I have a funtion which can return multiple types:

list(User), list(Player), list(Builder)

I want to use pycharm auto complete features but it doesn’t seem to infer the right possible return types, so I read about the typing module and tried to use this syntax as return type:

-> Union[List[Builder], List[User], List[Player]]

And yet PyCharm suggest Builder’s attributes only, which is the first thing one on the Union expression.
If I use non-list return types, typing works as expected and suggest the right attribute from all types written in the Union expression. I.E:

-> Union[Builder, User, Player]

Is there anyway to fix this?

Thanks!

Body:
I'm using for that docstrings. I kill two birds with one stone like that. The first one is having my method documented if I was not clear :)

def method_a():
    """
    :return:
    list of int, list of str
    """
    return [1, 2, 3], ["a", "b", "c"]


问:
Firebase Signup function
I have a function called signup that add a user to my firebase database with javascript in my web project. My function work well but when I want to redirect to another page at the end of the function, it doesn't add the user to my database. In the bottom code, if I remove the if statement, everything work perfectly but with it, it does redirect to the index page but doesn't add the user.</p>

```<code>    function signup() {
        var UserEmail = document.getElementById("email").value;
        var UserPassword = document.getElementById("password").value;
        var errorCode = null;
        var errorMessage = null;
        firebase.auth().createUserWithEmailAndPassword(UserEmail,UserPassword).catch(function (error) {
                // Handle Errors here.
                errorCode = error.code;
                errorMessage = error.message;
                console.log(errorMessage);
            });

            if (errorCode == null) {
                window.location = '/index.html';
            }
        }
</code>```

答:
createUserWithEmailAndPassword(...)

is returning a Future. So, the code inside your catch-function will be called asynchronously.

As a result, the following code

```<code>if (errorCode == null) {
      window.location = '/index.html';
}
</code>```

may be called, before you even retreived an answer from your statement, since it is not in the error-block. At this time, errorCode is still null.

To solve this, you can access the 'then' callback of your function call:

```<code>firebase.auth().createUserWithEmailAndPassword(UserEmail,UserPassword).then((userData) {
    //Redirect the user here
}).catch((error) {
    //Your Error-Handling
});
</code>```

Title: Firebase Signup function

Body:
I have a function called signup that add a user to my firebase database with javascript in my web project. My function work well but when I want to redirect to another page at the end of the function, it doesn't add the user to my database. In the bottom code, if I remove the if statement, everything work perfectly but with it, it does redirect to the index page but doesn't add the user.

    function signup() {
        var UserEmail = document.getElementById("email").value;
        var UserPassword = document.getElementById("password").value;
        var errorCode = null;
        var errorMessage = null;
        firebase.auth().createUserWithEmailAndPassword(UserEmail,UserPassword).catch(function (error) {
                // Handle Errors here.
                errorCode = error.code;
                errorMessage = error.message;
                console.log(errorMessage);
            });

            if (errorCode == null) {
                window.location = '/index.html';
            }
        }

Body:
createUserWithEmailAndPassword(...)

is returning a Future. So, the code inside your catch-function will be called asynchronously.

As a result, the following code

if (errorCode == null) {
      window.location = '/index.html';
}

may be called, before you even retreived an answer from your statement, since it is not in the error-block. At this time, errorCode is still null.

To solve this, you can access the 'then' callback of your function call:

firebase.auth().createUserWithEmailAndPassword(UserEmail,UserPassword).then((userData) {
    //Redirect the user here
}).catch((error) {
    //Your Error-Handling
});


问:
EBCDIC to ASCII in RUBY
I have a EBCDIC file that was generated from a Mainframe and will need to convert it to ASCII for data processing.<br>
Any help would be appreciated. </p>

答:
Since [Ruby 2.3 the EBCDIC-encoding is available][1]:

Encoding

new Encoding::IBM037 (alias ebcdic-cp-us; dummy)

So this should work:

```<code>src = 'out_26877296.tst'
content = File.read(src, encoding: 'IBM037:ASCII')
</code>```

Title: EBCDIC to ASCII in RUBY

Body:
I have a EBCDIC file that was generated from a Mainframe and will need to convert it to ASCII for data processing.

Any help would be appreciated.

Body:
Since [Ruby 2.3 the EBCDIC-encoding is available][1]:

Encoding

new Encoding::IBM037 (alias ebcdic-cp-us; dummy)

So this should work:

src = 'out_26877296.tst'
content = File.read(src, encoding: 'IBM037:ASCII')


问:
Users dissapear when I sort a doubly-linked list using quicksort
I have a doubly-linked list and I want to sort the users by their ELO.

The problem is that when the function swap() is called, some users dissapear

This is what I get in my console:
https://imgur.com/a/pJSPSnW

As you can see, the first swap (between players 1 and 2) is done correctly.
But, when it swaps players 3 and 4, user1 dissapears.

I think that the problem is inside the function swap(), but I can't figure out where exactly

Code:
User/Node declaration

```<code>struct user {
public:
    string username;
    float ELO = NULL; //Score of the user
    user* next = nullptr;
    user* previous = nullptr;
};
</code>```

QuickSortRecursive function

```<code> void ELOManager::_quickSortRecursive(user* low, user* high) {
    if (high != nullptr && low != high && low != nullptr) {
        user* p = partition(low, high);
        _quickSortRecursive(low, p->previous);
        _quickSortRecursive(p->next, high);
    }
}
</code>```

QuickSort function

```<code>void ELOManager::quickSort(){
    _quickSortRecursive(first, last);
}
</code>```

Partition function

```<code>    user* ELOManager::partition(user* low, user* high) {
    float pivot = high->ELO;

    user* i = low->previous;

    for (user* j = low; j != high && j!=nullptr; j = j->next) {
        if (j->ELO <= pivot){
            i = (i == NULL) ? low : i->next;

            swap(i, j);
        }
    }
    //i = (i == NULL) ? low : i->next;
    swap(i->next, high);
    cout << endl << "Loop finished -----------------------" << endl;
    printUsers();
    return i;
}
</code>```

Swap function

```<code>    void ELOManager::swap(user* A, user* B) {
    user* tmp = new user();
    user* swapperVector[4];

    cout << endl << "swap1[" << A->username << "]" << endl;
    cout << "swap2[" << B->username << "]" << endl;

    if (A == B) {
        cout << "Same Users: Continue" << endl;
        return;
    }

    swapperVector[0] = A->previous;
    swapperVector[1] = B->previous;
    swapperVector[2] = A->next;
    swapperVector[3] = B->next;

    if (areTheyNeighbours(A, B)) {
        A->previous->next = B;
        A->next->previous = B;
        B->previous->next = A;
        B->next->previous = A;

        A->previous = B;
        B->previous = swapperVector[1];
        A->next = swapperVector[3];
        B->next = A;
        cout << endl << "Option 1" << endl;
    }
    else {
        A->previous = swapperVector[1];
        B->previous = swapperVector[0];
        A->next = swapperVector[3];
        B->next = swapperVector[2];

        A->previous->next = B;
        A->next->previous = B;
        B->previous->next = A;
        B->next->previous = A;
        cout << endl << "Option 2" << endl;
    }

    cout <<"Print list after swap" << endl << "-----" << endl;
    printUsers();
}
</code>```

Feel free to get into my project's github
https://github.com/pablogalve/ELO-System

I would appreciate your help :)

答:
In your if (areTheyNeighbors(A, B)) block, your linked list pointers end up looking like this:
Notice that:

Both of B's pointers are pointed at A

Both A and A->next think B is their previous list element

This causes multiple problems in list traversal, and might be what causes the first element in the list to be lost.

If A and B are neighbors, this should swap them properly.

```<code>A->previous = B;
B->previous = swapperVector[0];
A->next = swapperVector[3];
B->next = A;
</code>```

Body:
I have a doubly-linked list and I want to sort the users by their ELO.

The problem is that when the function swap() is called, some users dissapear

This is what I get in my console:
https://imgur.com/a/pJSPSnW

As you can see, the first swap (between players 1 and 2) is done correctly.
But, when it swaps players 3 and 4, user1 dissapears.

I think that the problem is inside the function swap(), but I can't figure out where exactly

Code:
User/Node declaration

struct user {
public:
    string username;
    float ELO = NULL; //Score of the user
    user* next = nullptr;
    user* previous = nullptr;
};

QuickSortRecursive function

 void ELOManager::_quickSortRecursive(user* low, user* high) {
    if (high != nullptr && low != high && low != nullptr) {
        user* p = partition(low, high);
        _quickSortRecursive(low, p->previous);
        _quickSortRecursive(p->next, high);
    }
}

QuickSort function

void ELOManager::quickSort(){
    _quickSortRecursive(first, last);
}

Partition function

    user* ELOManager::partition(user* low, user* high) {
    float pivot = high->ELO;

    user* i = low->previous;

    for (user* j = low; j != high && j!=nullptr; j = j->next) {
        if (j->ELO <= pivot){
            i = (i == NULL) ? low : i->next;

            swap(i, j);
        }
    }
    //i = (i == NULL) ? low : i->next;
    swap(i->next, high);
    cout << endl << "Loop finished -----------------------" << endl;
    printUsers();
    return i;
}

Swap function

    void ELOManager::swap(user* A, user* B) {
    user* tmp = new user();
    user* swapperVector[4];

    cout << endl << "swap1[" <username << "]" << endl;
    cout << "swap2[" <username << "]" << endl;

    if (A == B) {
        cout << "Same Users: Continue" << endl;
        return;
    }

    swapperVector[0] = A->previous;
    swapperVector[1] = B->previous;
    swapperVector[2] = A->next;
    swapperVector[3] = B->next;

    if (areTheyNeighbours(A, B)) {
        A->previous->next = B;
        A->next->previous = B;
        B->previous->next = A;
        B->next->previous = A;

        A->previous = B;
        B->previous = swapperVector[1];
        A->next = swapperVector[3];
        B->next = A;
        cout << endl << "Option 1" << endl;
    }
    else {
        A->previous = swapperVector[1];
        B->previous = swapperVector[0];
        A->next = swapperVector[3];
        B->next = swapperVector[2];

        A->previous->next = B;
        A->next->previous = B;
        B->previous->next = A;
        B->next->previous = A;
        cout << endl << "Option 2" << endl;
    }

    cout <<"Print list after swap" << endl << "-----" << endl;
    printUsers();
}

Feel free to get into my project's github
https://github.com/pablogalve/ELO-System

I would appreciate your help :)

Body:
In your if (areTheyNeighbors(A, B)) block, your linked list pointers end up looking like this:
Notice that:

Both of B's pointers are pointed at A

Both A and A->next think B is their previous list element

This causes multiple problems in list traversal, and might be what causes the first element in the list to be lost.

If A and B are neighbors, this should swap them properly.

A->previous = B;
B->previous = swapperVector[0];
A->next = swapperVector[3];
B->next = A;


答:
You can change around your if/else statements a little bit. You were close, just had your conditions and brackets a little mixed up.

You want to make sure you have a syntax like this:

```<code>if (condition)
{
    // do something
} else if (condition)
{
    // do something else
}
</code>```

Try this solution:

```<code>const howOld = (age, year) =>

{
  if (year > 2019)
  {
      let calculatedAge = ( year - 2019 + age );
      return `You will be ${calculatedAge } in the year ${year}.`;
  } else if (year < (2019-age))
  {
      let calculatedAge = ( 2019 - year + age );
      return `The year ${year } was ${calculatedAge } years before you were born.`;
  } else
  {
      let calculatedAge = ( year - 2019 + age );
      return `You were ${calculatedAge} in the year ${year}. `;
  }

};

console.log(howOld(47,2000))
</code>```

Title: Codecademy howOld syntax error at else if

Body:
You can change around your if/else statements a little bit. You were close, just had your conditions and brackets a little mixed up.

You want to make sure you have a syntax like this:

if (condition)
{
    // do something
} else if (condition)
{
    // do something else
}

Try this solution:

const howOld = (age, year) =>

{
  if (year > 2019)
  {
      let calculatedAge = ( year - 2019 + age );
      return `You will be ${calculatedAge } in the year ${year}.`;
  } else if (year < (2019-age))
  {
      let calculatedAge = ( 2019 - year + age );
      return `The year ${year } was ${calculatedAge } years before you were born.`;
  } else
  {
      let calculatedAge = ( year - 2019 + age );
      return `You were ${calculatedAge} in the year ${year}. `;
  }

};

console.log(howOld(47,2000))


问:
Getting day of the week from timestamp using JavaScript
How do I get the day of the week from a timestamp in JavaScript?
I'd like to get this from a timestamp I specify, not the current date.

Thanks

答:
```<code>var timestamp = 654524560; // UNIX timestamp in seconds
var xx = new Date();
xx.setTime(timestamp*1000); // javascript timestamps are in milliseconds
document.write(xx.toUTCString());
document.write(xx.getDay()); // the Day
</code>```

2020 Update

If this browser support is acceptable for you you can use this one liner:

new Date(<TIMESTAMP>).toLocaleDateString('en-US', { weekday: 'long' }); // e.g. Tuesday

Body:
var timestamp = 654524560; // UNIX timestamp in seconds
var xx = new Date();
xx.setTime(timestamp*1000); // javascript timestamps are in milliseconds
document.write(xx.toUTCString());
document.write(xx.getDay()); // the Day

2020 Update

If this browser support is acceptable for you you can use this one liner:

new Date(<TIMESTAMP>).toLocaleDateString('en-US', { weekday: 'long' }); // e.g. Tuesday


问:
Airflow cluster: Is it needed to deploy DAGs / Workflows in all the workers?
We are planning to update Airflow and switch from single Airflow server to Airflow cluster (AWS).

We've been cheking the this article and this one.

We are using SQS as queue service and despite the documentation said that we only need to deploy our DAGs py files in the masters we wonder if this is correct.

The comunications throught queues don't include the code

In our tests, our DAGs are not working in case we don't deploy them in all nodes, workers and masters.

So, what we should do?

Many thanks!

答: Your DAGS need to be synced across all workers for it to work because the airflow_scheduler will send the DAG to whichever worker is available. If the DAGS are not synced across all workers, an older copy of the DAG may be run.


问:
Make String input an object instance
```<code>user1.subscribe();
</code>```

user1 is under a User class, I'm looking at how to use Scanner to get the user input. So when asking username using Scanner, like user2, that can be used to call user2.subscribe();

Used Scanner String input but can't convert to object

```<code>User userID;
Scanner input = new Scanner(System.in);
userID = input.next();
</code>```

Type mismatch: cannot convert from String to User

So the user has been added as follow

```<code>User user1 = new User("user1", "James Smith", "915661829");
</code>```

In main method I can call user1.subscribe() to subscribe the user. I'm trying to ask for an input, like "user2" which will call user2.subscribe().

The Scanner would ask for the username of the user that wants to subscribe.

答:
A Scanner's next() method will indeed only produce String values. If you want to create a new User instance, you would have to convert that String value to a User manually somehow.

Maybe User has a constructor that takes a name?

```<code>String username = input.next();
User userID = new User(username);
</code>```

Title: Make String input an object instance

Body:
user1.subscribe();

user1 is under a User class, I'm looking at how to use Scanner to get the user input. So when asking username using Scanner, like user2, that can be used to call user2.subscribe();

Used Scanner String input but can't convert to object

User userID;
Scanner input = new Scanner(System.in);
userID = input.next();

Type mismatch: cannot convert from String to User

So the user has been added as follow

User user1 = new User("user1", "James Smith", "915661829");

In main method I can call user1.subscribe() to subscribe the user. I'm trying to ask for an input, like "user2" which will call user2.subscribe().

The Scanner would ask for the username of the user that wants to subscribe.

Body:
A Scanner's next() method will indeed only produce String values. If you want to create a new User instance, you would have to convert that String value to a User manually somehow.

Maybe User has a constructor that takes a name?

String username = input.next();
User userID = new User(username);


问:
Solve huge sparse linear system, where A is a result of a kron product
How can I solve the linear system (A ⊗ B + C ⊗ D) x = b in MATLAB without calculating the actual matrix that multiplies x (⊗ denotes the kronecker product). Even though A,B,C and D are sparse matrices, the naive approach,

```<code>x = (kron(A,B) + kron(C,D))\b
</code>```

does not fit in memory and causes MATLAB to crash for large Matrices (~1000 x 1000 elements per matrix).

What can be done about this?

答:
Seeing how your matrices are generally quite sparse, the end result of the tensor product shouldn't take that much memory. This is one of the cases when vectorization simply cannot be done due to the huge memory requirements of the intermediate computations, but it just might be possible using loops (and partial vectorization).

Note that this is a "better than nothing, but not by much" type of a solution.

I'll be using the ndSparse submission, as it makes it easier to work with sparse matrices.

% Create some matrices
[A,B] = deal(sparse(1000,1000));
A(randperm(1000^2, 10000)) = randn(1E4, 1);
B(randperm(1000^2, 10000)) = randn(1E4, 1);
A = ndSparse(A); B = ndSparse(B);

% Kronecker tensor product, copied from kron.m
[ma,na] = size(A);
[mb,nb] = size(B);
A = reshape(A,[1 ma 1 na]);
B = reshape(B,[mb 1 nb 1]);
% K = reshape(A.*B,[ma*mb na*nb]);                    % This fails, too much memory.
K = ndSparse(sparse(mb*ma*nb*na,1),[mb, ma, nb, na]); % This works
```

<p>From here one can proceed depending on the available memory:</p>

<pre class="lang-matlab prettyprint-override"><code>% If there's plenty of memory (2D x 1D -> 3D):
for ind1 = 1:mb
  K(ind1,:,:,:) = bsxfun(@times, A, B(ind1, :, :, :));
end

% If there's less memory (1D x 1D -> 2D):
for ind1 = 1:mb
  for ind2 = 1:ma
    K(ind1,ind2,:,:) = bsxfun(@times, A(:, ind2, :, :), B(ind1, :, :, :));
  end
end

% If there's even less memory (1D x 0D -> 1D):
for ind1 = 1:mb
  for ind2 = 1:ma
    for ind3 = 1:nb
      K(ind1,ind2,ind3,:) = bsxfun(@times, A(:, ind2, :, :), B(ind1, :, ind3, :));
    end
  end
end

% If there's absolutely no memory (0D x 0D  -> 0D):
for ind1 = 1:mb
  for ind2 = 1:ma
    for ind3 = 1:nb
      for ind4 = 1:na
        K(ind1,ind2,ind3,ind4) = A(:, ind2, :, ind4) .* B(ind1, :, ind3, :);
      end
    end
  end
end

K = sparse(reshape(K,[ma*mb na*nb])); % Final touch
</code>```

So this is just a theoretical demonstration of how to eventually perform the computation, but unfortunately it is very inefficient since it has to call class methods over and over again, and also it doesn't guarantee that there will be enough memory to evaluate the \ operator.

One possible way to improve this is by calling matlab.internal.sparse.kronSparse in some blockwise manner and store the intermediate results in the correct position of the output array, but this should require some careful thought.

BTW, I tried using the FEX submission that Ander mentioned (KronProd) but it provides no benefit when you need to compute kron(A,B) + kron(C,D) (although it's amazing for kron(A,B)\b situations).

Body:
How can I solve the linear system (A ⊗ B + C ⊗ D) x = b in MATLAB without calculating the actual matrix that multiplies x (⊗ denotes the kronecker product). Even though A,B,C and D are sparse matrices, the naive approach,

x = (kron(A,B) + kron(C,D))\b

does not fit in memory and causes MATLAB to crash for large Matrices (~1000 x 1000 elements per matrix).

What can be done about this?

Body:
Seeing how your matrices are generally quite sparse, the end result of the tensor product shouldn't take that much memory. This is one of the cases when vectorization simply cannot be done due to the huge memory requirements of the intermediate computations, but it just might be possible using loops (and partial vectorization).

Note that this is a "better than nothing, but not by much" type of a solution.

I'll be using the ndSparse submission, as it makes it easier to work with sparse matrices.

% Create some matrices
[A,B] = deal(sparse(1000,1000));
A(randperm(1000^2, 10000)) = randn(1E4, 1);
B(randperm(1000^2, 10000)) = randn(1E4, 1);
A = ndSparse(A); B = ndSparse(B);

% Kronecker tensor product, copied from kron.m
[ma,na] = size(A);
[mb,nb] = size(B);
A = reshape(A,[1 ma 1 na]);
B = reshape(B,[mb 1 nb 1]);
% K = reshape(A.*B,[ma*mb na*nb]);                    % This fails, too much memory.
K = ndSparse(sparse(mb*ma*nb*na,1),[mb, ma, nb, na]); % This works

From here one can proceed depending on the available memory:

% If there's plenty of memory (2D x 1D -> 3D):
for ind1 = 1:mb
  K(ind1,:,:,:) = bsxfun(@times, A, B(ind1, :, :, :));
end

% If there's less memory (1D x 1D -> 2D):
for ind1 = 1:mb
  for ind2 = 1:ma
    K(ind1,ind2,:,:) = bsxfun(@times, A(:, ind2, :, :), B(ind1, :, :, :));
  end
end

% If there's even less memory (1D x 0D -> 1D):
for ind1 = 1:mb
  for ind2 = 1:ma
    for ind3 = 1:nb
      K(ind1,ind2,ind3,:) = bsxfun(@times, A(:, ind2, :, :), B(ind1, :, ind3, :));
    end
  end
end

% If there's absolutely no memory (0D x 0D  -> 0D):
for ind1 = 1:mb
  for ind2 = 1:ma
    for ind3 = 1:nb
      for ind4 = 1:na
        K(ind1,ind2,ind3,ind4) = A(:, ind2, :, ind4) .* B(ind1, :, ind3, :);
      end
    end
  end
end

K = sparse(reshape(K,[ma*mb na*nb])); % Final touch

So this is just a theoretical demonstration of how to eventually perform the computation, but unfortunately it is very inefficient since it has to call class methods over and over again, and also it doesn't guarantee that there will be enough memory to evaluate the \ operator.

One possible way to improve this is by calling matlab.internal.sparse.kronSparse in some blockwise manner and store the intermediate results in the correct position of the output array, but this should require some careful thought.

BTW, I tried using the FEX submission that Ander mentioned (KronProd) but it provides no benefit when you need to compute kron(A,B) + kron(C,D) (although it's amazing for kron(A,B)\b situations).