问:
How to fix the constantly growing memory usage of ray?
I started using ray for distributed machine learning and I already have some issues.
The memory usage is simply growing until the program crashes. Altough I clear the list constantly, the memory is somehow leaking. Any idea why ?

My specs:
OS Platform and Distribution: Ubuntu 16.04
Ray installed from: binary
Ray version: 0.6.5
Python version:3.6.8

I already tried using the experimental queue instead of the DataServer class, but the problem is still the same.

import numpy as np
import ray
import time
ray.init(redis_max_memory=100000000)

@ray.remote
class Runner():
    def __init__(self, dataList):
        self.run(dataList)

    def run(self,dataList):
        while True:
            dataList.put.remote(np.ones(10))

@ray.remote
class Optimizer():
    def __init__(self, dataList):
        self.optimize(dataList)

    def optimize(self,dataList):
        while True:
            dataList.pop.remote()

@ray.remote
class DataServer():
    def __init__(self):
        self.dataList= []

    def put(self,data):
        self.dataList.append(data)

    def pop(self):
        if len(self.dataList) !=0:
            return self.dataList.pop()
    def get_size(self):
        return len(self.dataList)

dataServer = DataServer.remote()
runner = Runner.remote(dataServer)
optimizer1 = Optimizer.remote(dataServer)
optimizer2 = Optimizer.remote(dataServer)

while True:
    time.sleep(1)
    print(ray.get(dataServer.get_size.remote()))

```

After running for some time I get this error message:

答:
I recently ran into a similar problem and found that if you are frequently putting large objects (using ray.put()) that you need to either:

Manually either adjust the thresholds that the python garbage collector uses

Call the gc.collect() on a regular basis.

I implemented a method that checks the amount of used memory and then calls the garbage collector.

The problem is that the default thresholds are based upon the # of objects, but if you are putting large objects, the gc may never get called until you run out of memory. My utility method is as follows:

def auto_garbage_collect(pct=80.0):
    """
    auto_garbage_collection - Call the garbage collection if memory used is greater than 80% of total available memory.
                              This is called to deal with an issue in Ray not freeing up used memory.

        pct - Default value of 80%.  Amount of memory in use that triggers the garbage collection call.
    """
    if psutil.virtual_memory().percent >= pct:
        gc.collect()
    return
```

Calling this will solve the problem when it is related pushing large objects via ray.put() and running out of memory.

Body:
I started using ray for distributed machine learning and I already have some issues.
The memory usage is simply growing until the program crashes. Altough I clear the list constantly, the memory is somehow leaking. Any idea why ?

My specs:
OS Platform and Distribution: Ubuntu 16.04
Ray installed from: binary
Ray version: 0.6.5
Python version:3.6.8

I already tried using the experimental queue instead of the DataServer class, but the problem is still the same.

import numpy as np
import ray
import time
ray.init(redis_max_memory=100000000)

@ray.remote
class Runner():
    def __init__(self, dataList):
        self.run(dataList)

    def run(self,dataList):
        while True:
            dataList.put.remote(np.ones(10))

@ray.remote
class Optimizer():
    def __init__(self, dataList):
        self.optimize(dataList)

    def optimize(self,dataList):
        while True:
            dataList.pop.remote()

@ray.remote
class DataServer():
    def __init__(self):
        self.dataList= []

    def put(self,data):
        self.dataList.append(data)

    def pop(self):
        if len(self.dataList) !=0:
            return self.dataList.pop()
    def get_size(self):
        return len(self.dataList)

dataServer = DataServer.remote()
runner = Runner.remote(dataServer)
optimizer1 = Optimizer.remote(dataServer)
optimizer2 = Optimizer.remote(dataServer)

while True:
    time.sleep(1)
    print(ray.get(dataServer.get_size.remote()))

After running for some time I get this error message:

Body:
I recently ran into a similar problem and found that if you are frequently putting large objects (using ray.put()) that you need to either:

Manually either adjust the thresholds that the python garbage collector uses

Call the gc.collect() on a regular basis.

I implemented a method that checks the amount of used memory and then calls the garbage collector.

The problem is that the default thresholds are based upon the # of objects, but if you are putting large objects, the gc may never get called until you run out of memory. My utility method is as follows:

def auto_garbage_collect(pct=80.0):
    """
    auto_garbage_collection - Call the garbage collection if memory used is greater than 80% of total available memory.
                              This is called to deal with an issue in Ray not freeing up used memory.

        pct - Default value of 80%.  Amount of memory in use that triggers the garbage collection call.
    """
    if psutil.virtual_memory().percent >= pct:
        gc.collect()
    return

Calling this will solve the problem when it is related pushing large objects via ray.put() and running out of memory.


来源: stackexchange

问:
Can I add attributes to an object property at runtime?
For example I want to remove or change below property attributes or add a new one. Is it possible?</p>

```<code>[XmlElement("bill_info")]
[XmlIgnore]
public BillInfo BillInfo
{
  get { return billInfo; }
  set { billInfo = value; }
}
</code>```

答:
(edit - I misread the original question)

You cannot add actual attributes (they are burned into the IL); however, with XmlSerializer you don't have to - you can supply additional attributes in the constructor to the XmlSerializer. You do, however, need to be a little careful to cache the XmlSerializer instance if you do this, as otherwise it will create an additional assembly per instance, which is a bit leaky. (it doesn't do this if you use the simple constructor that just takes a Type). Look at XmlAttributeOverrides.

For an example:

```<code>using System;
using System.Xml.Serialization;
 public class Person
{
    static void Main()
    {
        XmlAttributeOverrides overrides = new XmlAttributeOverrides();
        XmlAttributes attribs = new XmlAttributes();
        attribs.XmlIgnore = false;
        attribs.XmlElements.Add(new XmlElementAttribute("personName"));
        overrides.Add(typeof(Person), "Name", attribs);

        XmlSerializer ser = new XmlSerializer(typeof(Person), overrides);
        Person person = new Person();
        person.Name = "Marc";
        ser.Serialize(Console.Out, person);
    }
    private string name;
    [XmlElement("name")]
    [XmlIgnore]
    public string Name { get { return name; } set { name = value; } }
}
</code>```

Note also; if the xml attributes were just illustrative, then there is a second way to add attributes for things related to data-binding, by using TypeDescriptor.CreateProperty and either ICustomTypeDescriptor or TypeDescriptionProvider. Much more complex than the xml case, I'm afraid - and doesn't work for all code - just code that uses the component-model.

OwnerDisplayName: Alish

ContentLicense: CC BY-SA 2.5

Body:
For example I want to remove or change below property attributes or add a new one. Is it possible?

[XmlElement("bill_info")]
[XmlIgnore]
public BillInfo BillInfo
{
  get { return billInfo; }
  set { billInfo = value; }
}

LastEditorDisplayName: Dimitre Novatchev

Body:
(edit - I misread the original question)

You cannot add actual attributes (they are burned into the IL); however, with XmlSerializer you don't have to - you can supply additional attributes in the constructor to the XmlSerializer. You do, however, need to be a little careful to cache the XmlSerializer instance if you do this, as otherwise it will create an additional assembly per instance, which is a bit leaky. (it doesn't do this if you use the simple constructor that just takes a Type). Look at XmlAttributeOverrides.

For an example:

using System;
using System.Xml.Serialization;
 public class Person
{
    static void Main()
    {
        XmlAttributeOverrides overrides = new XmlAttributeOverrides();
        XmlAttributes attribs = new XmlAttributes();
        attribs.XmlIgnore = false;
        attribs.XmlElements.Add(new XmlElementAttribute("personName"));
        overrides.Add(typeof(Person), "Name", attribs);

        XmlSerializer ser = new XmlSerializer(typeof(Person), overrides);
        Person person = new Person();
        person.Name = "Marc";
        ser.Serialize(Console.Out, person);
    }
    private string name;
    [XmlElement("name")]
    [XmlIgnore]
    public string Name { get { return name; } set { name = value; } }
}

Note also; if the xml attributes were just illustrative, then there is a second way to add attributes for things related to data-binding, by using TypeDescriptor.CreateProperty and either ICustomTypeDescriptor or TypeDescriptionProvider. Much more complex than the xml case, I'm afraid - and doesn't work for all code - just code that uses the component-model.

OwnerDisplayName: Marc Gravell

LastEditorDisplayName: Marc Gravell


问:
Decode cryptlib encoded text using Java (without cryptlib)
Hello.

First of all: I'm new to stackOverflow and to the subject I'm talking about...

I am trying to avoid the usage of the cryptlib library for TripleDES encryption in my Java application (now i am using AES - to ensure the downward compatibility I also want to be able to decode the strings which were created with the cryptlib library but without the useage of JNI).

But none of the things I tried by now worked for me.

Configuration:

Algorithm: TripleDES

Mode: CBC

Format: CRYPT_FORMAT_CRYPTLIB

The key has a size of 16 byte (which is inconvenient, but BouncyCastle would support it).

And the encrypted data has a size which is not a multiple of 8 (for exmaple 81 byte).

In my wrapper of the library (also in C) the context is created this way:

```<code>cryptCreateContext( &cryptContext, CRYPT_UNUSED, CRYPT_ALGO_3DES);
cryptSetAttribute( cryptContext, CRYPT_CTXINFO_MODE, CRYPT_MODE_CBC );
cryptSetAttributeString( cryptContext, CRYPT_CTXINFO_KEY, key, keyLen);
</code>```

The envelope is created this way:

```<code>cryptCreateEnvelope( envelope, CRYPT_FORMAT_CRYPTLIB );
</code>```

I think the problem is the format (since it is a "cryptlib native" format) - I can not find any description about it in the net...

Currently my best try was this one:

```<code>Security.addProvider(new BouncyCastleProvider());
SecretKeySpec keySpec = new SecretKeySpec(KEY.getBytes(), "DESede");
IvParameterSpec iv = new IvParameterSpec(new byte[8]);
Cipher e_cipher = Cipher.getInstance("DESede/CBC/PKCS7Padding", "BC");
e_cipher.init(Cipher.DECRYPT_MODE, keySpec, iv);

byte[] hexdecoded = Hex.decode(ENCRYPTED.getBytes());
byte [] cipherText = e_cipher.doFinal(hexdecoded);

return new String(cipherText);
</code>```

I also tried different paddings, but I always end in one of these two Exceptions:

javax.crypto.IllegalBlockSizeException:
data not block size aligned

javax.crypto.IllegalBlockSizeException:
last block incomplete in decryption

I'm getting a little desperate, so I would be really happy if someone here could help me...

EDIT:
Here is the code for the encryption (CryptData.cpp):

```<code>bool CCryptData::encryptData(BYTE *key,int keyLen, BYTE *data, int dataLen, int resultMemSize, BYTE *result, int &resultLen)
{
    CRYPT_ENVELOPE cryptEnvelope;
    CRYPT_CONTEXT cryptContext;
    CRYPT_ALGO cryptAlgo = selectCipher( CRYPT_ALGO_3DES );
    int count;

    /* Create the session key context.  We don't check for errors here since
       this code will already have been tested earlier */
    cryptCreateContext( &cryptContext, CRYPT_UNUSED, cryptAlgo );
    cryptSetAttribute( cryptContext, CRYPT_CTXINFO_MODE, CRYPT_MODE_CBC );
    cryptSetAttributeString( cryptContext, CRYPT_CTXINFO_KEY, key, keyLen );

    /* Create the envelope, push in a password and the data, pop the
       enveloped result, and destroy the envelope */
    if( !createEnvelope( &cryptEnvelope ) || \
        !addEnvInfoNumeric( cryptEnvelope, CRYPT_ENVINFO_SESSIONKEY,
                            cryptContext ) )
        return( FALSE );

    cryptSetAttribute( cryptEnvelope, CRYPT_ENVINFO_DATASIZE, dataLen );

    count = pushData( cryptEnvelope, data, dataLen, NULL, 0 );

    if( cryptStatusError( count ) )
        return( FALSE );

    resultLen = popData( cryptEnvelope, result, resultMemSize);

    if( cryptStatusError( count ) )
        return( FALSE );
    if( !destroyEnvelope( cryptEnvelope ) )
        return( FALSE );

    return true;
}

bool CCryptData::checkErrorStatus(int status, CString function)
{
    if( cryptStatusError( status ) )
    {
        m_lastError  = "Error occured in function " + function;
        m_lastError += " with StatusCode: " + status;
        m_bError = true;
        return true;
    }

    return false;
}

int CCryptData::createEnvelope( CRYPT_ENVELOPE *envelope )
{
    int status;

    /* Create the envelope */
    status = cryptCreateEnvelope( envelope, CRYPT_UNUSED, CRYPT_FORMAT_CRYPTLIB );
    if( checkErrorStatus(status, "createEnvelope"))
        return false;

    return( TRUE );
}

int CCryptData::destroyEnvelope( CRYPT_ENVELOPE envelope )
{
    int status;

    /* Destroy the envelope */
    status = cryptDestroyEnvelope( envelope );
    if( checkErrorStatus( status, "destroyEnvelope"))
        return false;

    return( TRUE );

}

int CCryptData::pushData( const CRYPT_ENVELOPE envelope, const BYTE *buffer,
                         const int length, const void *stringEnvInfo,
                         const int numericEnvInfo )
{
    int status, bytesIn;

    /* Push in the data */
    status = cryptPushData( envelope, buffer, length, &bytesIn );
    if( cryptStatusError( status ) )
    {
        printf( "cryptPushData() failed with error code %d, line %d.\n",
                status, __LINE__ );
        return( status );
    }
    if( bytesIn != length )
    {
        printf( "cryptPushData() only copied %d of %d bytes, line %d.\n",
                bytesIn, length, __LINE__ );
        return( SENTINEL );
    }

    /* Flush the data */
    status = cryptPushData( envelope, NULL, 0, NULL );
    if( cryptStatusError( status ) && status != CRYPT_ERROR_COMPLETE )
        {
        printf( "cryptPushData() (flush) failed with error code %d, line "
                "%d.\n", status, __LINE__ );
        return( status );
        }

    return( bytesIn );

}

int CCryptData::popData( CRYPT_ENVELOPE envelope, BYTE *buffer, int bufferSize )
{
    int status, bytesOut;

    status = cryptPopData( envelope, buffer, bufferSize, &bytesOut );
    if( cryptStatusError( status ) )
        {
        printf( "cryptPopData() failed with error code %d, line %d.\n",
                status, __LINE__ );
        return( status );
        }

    return( bytesOut );

}

int CCryptData::addEnvInfoNumeric( const CRYPT_ENVELOPE envelope,
                              const CRYPT_ATTRIBUTE_TYPE type,
                              const int envInfo )
{
    int status;

    status = cryptSetAttribute( envelope, type, envInfo );
    if( checkErrorStatus( status, "addEnvInfoNumeric"))
        return false;

    return( TRUE );

}

CRYPT_ALGO CCryptData::selectCipher( const CRYPT_ALGO algorithm )
{
    if( cryptStatusOK( cryptQueryCapability( algorithm, NULL ) ) )
        return( algorithm );
    return( CRYPT_ALGO_BLOWFISH );
}
</code>```

EDIT 2:
In comparision it is the same implementation as descripted in this mailing list.

But i want to decode it in Java...

EDIT 3:
I think the problem is, that the encrypted data is enveloped in cryptlib (as seen in the code).

EDIT 4:
I know know that the problem is the enveloping. The cryptlib uses the session key of the created crypt context to envelope the decrypted data in the CRYPT_FORMAT_CRYPTLIB format.
The question now is how to decode the envelope before performing the real decryption.

Any suggestions how i could perform the decoding?

答: The exceptions appear to lead directly from the ciphertext length you're putting in. By definition CBC outputs a whole number of blocks so it should be giving us a multiple of 8... The question I'd be asking at this point is, what on earth is cryptlib doing? Can you show us the cryptlib code you're using to create the encrypted string?</p>

ContentLicense: CC BY-SA 3.0

Body:
Hello.

First of all: I'm new to stackOverflow and to the subject I'm talking about...

I am trying to avoid the usage of the cryptlib library for TripleDES encryption in my Java application (now i am using AES - to ensure the downward compatibility I also want to be able to decode the strings which were created with the cryptlib library but without the useage of JNI).

But none of the things I tried by now worked for me.

Configuration:

Algorithm: TripleDES

Mode: CBC

Format: CRYPT_FORMAT_CRYPTLIB

The key has a size of 16 byte (which is inconvenient, but BouncyCastle would support it).

And the encrypted data has a size which is not a multiple of 8 (for exmaple 81 byte).

In my wrapper of the library (also in C) the context is created this way:

cryptCreateContext( &cryptContext, CRYPT_UNUSED, CRYPT_ALGO_3DES);
cryptSetAttribute( cryptContext, CRYPT_CTXINFO_MODE, CRYPT_MODE_CBC );
cryptSetAttributeString( cryptContext, CRYPT_CTXINFO_KEY, key, keyLen);

The envelope is created this way:

cryptCreateEnvelope( envelope, CRYPT_FORMAT_CRYPTLIB );

I think the problem is the format (since it is a "cryptlib native" format) - I can not find any description about it in the net...

Currently my best try was this one:

Security.addProvider(new BouncyCastleProvider());
SecretKeySpec keySpec = new SecretKeySpec(KEY.getBytes(), "DESede");
IvParameterSpec iv = new IvParameterSpec(new byte[8]);
Cipher e_cipher = Cipher.getInstance("DESede/CBC/PKCS7Padding", "BC");
e_cipher.init(Cipher.DECRYPT_MODE, keySpec, iv);

byte[] hexdecoded = Hex.decode(ENCRYPTED.getBytes());
byte [] cipherText = e_cipher.doFinal(hexdecoded);

return new String(cipherText);

I also tried different paddings, but I always end in one of these two Exceptions:

javax.crypto.IllegalBlockSizeException:
data not block size aligned

javax.crypto.IllegalBlockSizeException:
last block incomplete in decryption

I'm getting a little desperate, so I would be really happy if someone here could help me...

EDIT:
Here is the code for the encryption (CryptData.cpp):

bool CCryptData::encryptData(BYTE *key,int keyLen, BYTE *data, int dataLen, int resultMemSize, BYTE *result, int &resultLen)
{
    CRYPT_ENVELOPE cryptEnvelope;
    CRYPT_CONTEXT cryptContext;
    CRYPT_ALGO cryptAlgo = selectCipher( CRYPT_ALGO_3DES );
    int count;

    /* Create the session key context.  We don't check for errors here since
       this code will already have been tested earlier */
    cryptCreateContext( &cryptContext, CRYPT_UNUSED, cryptAlgo );
    cryptSetAttribute( cryptContext, CRYPT_CTXINFO_MODE, CRYPT_MODE_CBC );
    cryptSetAttributeString( cryptContext, CRYPT_CTXINFO_KEY, key, keyLen );

    /* Create the envelope, push in a password and the data, pop the
       enveloped result, and destroy the envelope */
    if( !createEnvelope( &cryptEnvelope ) || \
        !addEnvInfoNumeric( cryptEnvelope, CRYPT_ENVINFO_SESSIONKEY,
                            cryptContext ) )
        return( FALSE );

    cryptSetAttribute( cryptEnvelope, CRYPT_ENVINFO_DATASIZE, dataLen );

    count = pushData( cryptEnvelope, data, dataLen, NULL, 0 );

    if( cryptStatusError( count ) )
        return( FALSE );

    resultLen = popData( cryptEnvelope, result, resultMemSize);

    if( cryptStatusError( count ) )
        return( FALSE );
    if( !destroyEnvelope( cryptEnvelope ) )
        return( FALSE );

    return true;
}

bool CCryptData::checkErrorStatus(int status, CString function)
{
    if( cryptStatusError( status ) )
    {
        m_lastError  = "Error occured in function " + function;
        m_lastError += " with StatusCode: " + status;
        m_bError = true;
        return true;
    }

    return false;
}

int CCryptData::createEnvelope( CRYPT_ENVELOPE *envelope )
{
    int status;

    /* Create the envelope */
    status = cryptCreateEnvelope( envelope, CRYPT_UNUSED, CRYPT_FORMAT_CRYPTLIB );
    if( checkErrorStatus(status, "createEnvelope"))
        return false;

    return( TRUE );
}

int CCryptData::destroyEnvelope( CRYPT_ENVELOPE envelope )
{
    int status;

    /* Destroy the envelope */
    status = cryptDestroyEnvelope( envelope );
    if( checkErrorStatus( status, "destroyEnvelope"))
        return false;

    return( TRUE );

}

int CCryptData::pushData( const CRYPT_ENVELOPE envelope, const BYTE *buffer,
                         const int length, const void *stringEnvInfo,
                         const int numericEnvInfo )
{
    int status, bytesIn;

    /* Push in the data */
    status = cryptPushData( envelope, buffer, length, &bytesIn );
    if( cryptStatusError( status ) )
    {
        printf( "cryptPushData() failed with error code %d, line %d.\n",
                status, __LINE__ );
        return( status );
    }
    if( bytesIn != length )
    {
        printf( "cryptPushData() only copied %d of %d bytes, line %d.\n",
                bytesIn, length, __LINE__ );
        return( SENTINEL );
    }

    /* Flush the data */
    status = cryptPushData( envelope, NULL, 0, NULL );
    if( cryptStatusError( status ) && status != CRYPT_ERROR_COMPLETE )
        {
        printf( "cryptPushData() (flush) failed with error code %d, line "
                "%d.\n", status, __LINE__ );
        return( status );
        }

    return( bytesIn );

}

int CCryptData::popData( CRYPT_ENVELOPE envelope, BYTE *buffer, int bufferSize )
{
    int status, bytesOut;

    status = cryptPopData( envelope, buffer, bufferSize, &bytesOut );
    if( cryptStatusError( status ) )
        {
        printf( "cryptPopData() failed with error code %d, line %d.\n",
                status, __LINE__ );
        return( status );
        }

    return( bytesOut );

}

int CCryptData::addEnvInfoNumeric( const CRYPT_ENVELOPE envelope,
                              const CRYPT_ATTRIBUTE_TYPE type,
                              const int envInfo )
{
    int status;

    status = cryptSetAttribute( envelope, type, envInfo );
    if( checkErrorStatus( status, "addEnvInfoNumeric"))
        return false;

    return( TRUE );

}

CRYPT_ALGO CCryptData::selectCipher( const CRYPT_ALGO algorithm )
{
    if( cryptStatusOK( cryptQueryCapability( algorithm, NULL ) ) )
        return( algorithm );
    return( CRYPT_ALGO_BLOWFISH );
}

EDIT 2:
In comparision it is the same implementation as descripted in this mailing list.

But i want to decode it in Java...

EDIT 3:
I think the problem is, that the encrypted data is enveloped in cryptlib (as seen in the code).

EDIT 4:
I know know that the problem is the enveloping. The cryptlib uses the session key of the created crypt context to envelope the decrypted data in the CRYPT_FORMAT_CRYPTLIB format.
The question now is how to decode the envelope before performing the real decryption.

Any suggestions how i could perform the decoding?


问:
PHP app cannot connect to docker mysql container at 127.0.0.1
Mysql is in it's own docker-compose.yml as I want a mysql server up and running that any other php application can connect to. So I do not have php and mysql in the same docker-compose.yml. From the php application, I can connect to mysql if I use the mysql container's gateway ip address by looking it up and then hard coding it into the php application. docker inspect mysql-db. But docker will change that 172... ip address each time mysql restarts so that is not ideal for development.

I can connect to mysql via mysql -h 127.0.0.1 no problem, but from the php application if I try to use 127.0.0.1 I get connection refused. I can only connect if I use the 172... gateway ip address.

How do I get the mysql container listening for connections from the host to 127.0.0.1?

docker-compose.yml for mysql

```<code>version: "3"

services:
  mysql:
    container_name: mysql-db
    image: mysql
    build:
      dockerfile: Dockerfile
      context: ./server/mysql
    environment:
      - MYSQL_ROOT_PASSWORD=admin
    volumes:
      - ./data/mysql:/var/lib/mysql
    ports:
      - 3306:3306
</code>```

docker-compose.yml for php

```<code>version: "3"

services:
  nginx:
    container_name: nginx_myapp
    image: nginx
    build:
      dockerfile: Dockerfile
      context: ./server/nginx
    ports:
      - 80:80
      - 443:443
    volumes:
      - ./app:/var/www/html
    networks:
      - myapp
  php:
    container_name: php_myapp
    image: php:7.3-fpm
    build:
      dockerfile: Dockerfile
      context: ./server/php-fpm
    environment:
      CI_ENV: development
    volumes:
      - ./app:/var/www/html
    networks:
      - myapp

networks:
  myapp:
</code>```

答:
Few solutions for you

1) you can duplicate mysql section in each file using same volume path, in that case when you start project you will have same databases

```<code>project1
version: "3.2"
services:
  mysql:
    volumes:
      - /var/mysql:/var/lib/mysql
  php:
    build:
      context: './php/'

project2
version: "3.2"
services:
  mysql:
    volumes:
      - /var/mysql:/var/lib/mysql
  php:
    build:
      context: './php/'
</code>```

2) you can connect using host.docker.internal or macos (docker.for.mac.localhost) directly to your host machine more information here From inside of a Docker container, how do I connect to the localhost of the machine?

ContentLicense: CC BY-SA 4.0

Body:
Mysql is in it's own docker-compose.yml as I want a mysql server up and running that any other php application can connect to. So I do not have php and mysql in the same docker-compose.yml. From the php application, I can connect to mysql if I use the mysql container's gateway ip address by looking it up and then hard coding it into the php application. docker inspect mysql-db. But docker will change that 172... ip address each time mysql restarts so that is not ideal for development.

I can connect to mysql via mysql -h 127.0.0.1 no problem, but from the php application if I try to use 127.0.0.1 I get connection refused. I can only connect if I use the 172... gateway ip address.

How do I get the mysql container listening for connections from the host to 127.0.0.1?

docker-compose.yml for mysql

version: "3"

services:
  mysql:
    container_name: mysql-db
    image: mysql
    build:
      dockerfile: Dockerfile
      context: ./server/mysql
    environment:
      - MYSQL_ROOT_PASSWORD=admin
    volumes:
      - ./data/mysql:/var/lib/mysql
    ports:
      - 3306:3306

docker-compose.yml for php

version: "3"

services:
  nginx:
    container_name: nginx_myapp
    image: nginx
    build:
      dockerfile: Dockerfile
      context: ./server/nginx
    ports:
      - 80:80
      - 443:443
    volumes:
      - ./app:/var/www/html
    networks:
      - myapp
  php:
    container_name: php_myapp
    image: php:7.3-fpm
    build:
      dockerfile: Dockerfile
      context: ./server/php-fpm
    environment:
      CI_ENV: development
    volumes:
      - ./app:/var/www/html
    networks:
      - myapp

networks:
  myapp:

Body:
Few solutions for you

1) you can duplicate mysql section in each file using same volume path, in that case when you start project you will have same databases

project1
version: "3.2"
services:
  mysql:
    volumes:
      - /var/mysql:/var/lib/mysql
  php:
    build:
      context: './php/'

project2
version: "3.2"
services:
  mysql:
    volumes:
      - /var/mysql:/var/lib/mysql
  php:
    build:
      context: './php/'

2) you can connect using host.docker.internal or macos (docker.for.mac.localhost) directly to your host machine more information here From inside of a Docker container, how do I connect to the localhost of the machine?


问:
JavaScript SWITCH CASE not working with variables Date Format
The Case should stop on Cartagena's Day.
I am trying to math the Dynamic Public Holidays of the Colombian Calendar with an INPUT VAR.
This code is defined by 3 main functions, 1 for calculating the PASCUA DAY, 1 for calculating MONDAY public holidays but with dynamic week and the last one for static public holidays.

I can't find why is not wokring, there is a lot of console log for debug purpose.

var date = new Date();
var dateYear = date.getFullYear();

// Dia de San Jose
var dateSanJose = dateYear + "/03/19";
dateSanJose = new Date(dateSanJose);

// Dia de la epifania
var dateEpifania = dateYear + "/01/06";
dateEpifania = new Date(dateEpifania);

// Dia de San Pedro y San Pablo
var dateSPSP = dateYear + "/06/29";
dateSPSP = new Date(dateSPSP);

// Dia de la Asunción de la Virgen
var dateAsuncVirgen = dateYear + "/08/15";
dateAsuncVirgen = new Date(dateAsuncVirgen);

// Día de la raza
var dateRaza = dateYear + "/10/12";
dateRaza = new Date(dateRaza);

// Día de todos los santos
var dateSantos = dateYear + "/11/01";
dateSantos = new Date(dateSantos);

// Día de la independencia de cartagena
var dateCartagena = dateYear + "/11/11";
dateCartagena = new Date(dateCartagena);

//---------- FECHAS FIJAS -----------//
var dateNuevoAno = new Date(dateYear + "/01/01");
var dateTrabajo = new Date(dateYear + "/05/01");
var dateIndependencia = new Date(dateYear + "/07/20");
var dateBatallaBoyaca = new Date(dateYear + "/08/07");
var dateInmaculada = new Date(dateYear + "/12/08");
var dateNavidad = new Date(dateYear + "/12/25");

//---------- FECHAS SEGÚN PASCUA -----------//
var pascuaDay = pascua(dateYear);
var dateJuevesSanto = operateDays(3, pascuaDay, false);
var dateViernesSanto = operateDays(2, pascuaDay, false);
var dateAscencion = operateDays(43, pascuaDay, true);
var dateCorpusChristi = operateDays(64, pascuaDay, true);
var dateSagradoCorazon = operateDays(71, pascuaDay, true);

//----------- FECHAS TRASLADABLES----------//

var dateSanJose = trasladableHolidays(dateSanJose);
var dateEpifania = trasladableHolidays(dateEpifania);
var dateSPSP = trasladableHolidays(dateSPSP);
var dateAsuncVirgen = trasladableHolidays(dateAsuncVirgen);
var dateRaza = trasladableHolidays(dateRaza);
var dateSantos = trasladableHolidays(dateSantos);
var dateCartagena = trasladableHolidays(dateCartagena);

function trasladableHolidays(dateVariable){
    dateCorrect = dateVariable;
    dateCorrect.setDate(dateVariable.getDate() + (1 + 7 - dateVariable.getDay()) % 7);
    return dateCorrect;
}

function operateDays(days, date, suma){
    var initialDate = new Date(date);
    var newDate = new Date(date);
    if (suma) {
        newDate.setDate(initialDate.getDate() + days);
    }else{
        newDate.setDate(initialDate.getDate() - days);
    }
    return newDate;
}

//Función para realizar el cálculo del domingo de pascua
function pascua(year) {
    if(year>1900 && year<2099) {
        M=24; N=5;
    }
    else if (year>2100 && year<2199) {
        M=24; N=6;
    }
    else if (year>2200 && year<2299) {
        M=25; N=0;
    }
    a = year % 19;
    b = year % 4;
    c = year % 7;
    d = ((19*a) + M) % 30;
    e = ((2*b) + (4*c) + (6*d) + N) % 7;
    f = d + e;
    if (f < 10) {
        dia = f + 22; mes = 3;
    }
    else  {
        dia = f - 9;  mes = 4;
    }
    if(dia==26 && mes==4){
        dia = 19;
    }
    if(dia==25 && mes==4 && d==28 && e==6 && a>10){
        dia = 18;
    }
    pascua = new Date(year,mes-1,dia);
    return pascua;
};

console.log("Año nuevo: " + dateNuevoAno)
console.log("Día del trabajo: " + dateTrabajo)
console.log("Día de la independencia: " + dateIndependencia)
console.log("La batalla de Boyaca: " + dateBatallaBoyaca)
console.log("Día de la inmaculada concepción: " + dateInmaculada)
console.log("Día de Navidad: " + dateNavidad)
console.log("Jueves Santo: " + dateJuevesSanto)
console.log("Viernes Santo: " + dateViernesSanto)
console.log("Día de la ascensión: " + dateAscencion)
console.log("Día del corpus christi: " + dateCorpusChristi)
console.log("Día del sagrado corazón: " + dateSagradoCorazon)
console.log("Día de los reyes magos: " + dateEpifania)
console.log("Día de San Jose: " + dateSanJose)
console.log("Dia de San Pedro y San Pablo: " + dateSPSP)
console.log("Día de la Asunción de la virgen: " + dateAsuncVirgen)
console.log("Día de la raza: " + dateRaza)
console.log("Día de todos los santos: " + dateSantos)
console.log("Día de la independencia de cartagena: " + dateCartagena)

//------------------------------------//
//----Validación Motor de Reglas-----//
//-----------------------------------//

var InputDate = new Date("2020-11-16 00:00:00");
console.log("DEFINICION INPUT DATE: " + InputDate);

//InputDate = dateCartagena
switch (InputDate)
   {
    case dateCartagena :
       console.log("TODAY IS CARTAGENA")
        break;
    case 1:
        console.log("Today is Monday")
        break;
    default:
        console.log("VALOR POR DEFECTO SW CASE: " + dateCartagena);
        break;
}```
</div>
</div>
</p>

<p>This is the final solution hope this works for any one else.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var date = new Date();
var dateYear = date.getFullYear();

// Dia de San Jose
var dateSanJose = dateYear + "/03/19";
dateSanJose = new Date(dateSanJose);

// Dia de la epifania
var dateEpifania = dateYear + "/01/06";
dateEpifania = new Date(dateEpifania);

// Dia de San Pedro y San Pablo
var dateSPSP = dateYear + "/06/29";
dateSPSP = new Date(dateSPSP);

// Dia de la Asunción de la Virgen
var dateAsuncVirgen = dateYear + "/08/15";
dateAsuncVirgen = new Date(dateAsuncVirgen);

// Día de la raza
var dateRaza = dateYear + "/10/12";
dateRaza = new Date(dateRaza);

// Día de todos los santos
var dateSantos = dateYear + "/11/01";
dateSantos = new Date(dateSantos);

// Día de la independencia de cartagena
var dateCartagena = dateYear + "/11/11";
dateCartagena = new Date(dateCartagena);

//---------- FECHAS FIJAS -----------//
var dateNuevoAno = new Date(dateYear + "/01/01");
var dateTrabajo = new Date(dateYear + "/05/01");
var dateIndependencia = new Date(dateYear + "/07/20");
var dateBatallaBoyaca = new Date(dateYear + "/08/07");
var dateInmaculada = new Date(dateYear + "/12/08");
var dateNavidad = new Date(dateYear + "/12/25");

//---------- FECHAS SEGÚN PASCUA -----------//
var pascuaDay = pascua(dateYear);
var dateJuevesSanto = operateDays(3, pascuaDay, false);
var dateViernesSanto = operateDays(2, pascuaDay, false);
var dateAscencion = operateDays(43, pascuaDay, true);
var dateCorpusChristi = operateDays(64, pascuaDay, true);
var dateSagradoCorazon = operateDays(71, pascuaDay, true);

//----------- FECHAS TRASLADABLES----------//

var dateSanJose = trasladableHolidays(dateSanJose);
var dateEpifania = trasladableHolidays(dateEpifania);
var dateSPSP = trasladableHolidays(dateSPSP);
var dateAsuncVirgen = trasladableHolidays(dateAsuncVirgen);
var dateRaza = trasladableHolidays(dateRaza);
var dateSantos = trasladableHolidays(dateSantos);
var dateCartagena = trasladableHolidays(dateCartagena);

function trasladableHolidays(dateVariable){
    dateCorrect = dateVariable;
    dateCorrect.setDate(dateVariable.getDate() + (1 + 7 - dateVariable.getDay()) % 7);
    return dateCorrect;
}

function operateDays(days, date, suma){
    var initialDate = new Date(date);
    var newDate = new Date(date);
    if (suma) {
        newDate.setDate(initialDate.getDate() + days);
    }else{
        newDate.setDate(initialDate.getDate() - days);
    }
    return newDate;
}

//Función para realizar el cálculo del domingo de pascua
function pascua(year) {
    if(year>1900 && year<2099) {
        M=24; N=5;
    }
    else if (year>2100 && year<2199) {
        M=24; N=6;
    }
    else if (year>2200 && year<2299) {
        M=25; N=0;
    }
    a = year % 19;
    b = year % 4;
    c = year % 7;
    d = ((19*a) + M) % 30;
    e = ((2*b) + (4*c) + (6*d) + N) % 7;
    f = d + e;
    if (f < 10) {
        dia = f + 22; mes = 3;
    }
    else  {
        dia = f - 9;  mes = 4;
    }
    if(dia==26 && mes==4){
        dia = 19;
    }
    if(dia==25 && mes==4 && d==28 && e==6 && a>10){
        dia = 18;
    }
    pascua = new Date(year,mes-1,dia);
    return pascua;
};

//console.log("Año nuevo: " + dateNuevoAno)
//console.log("Día del trabajo: " + dateTrabajo)
//console.log("Día de la independencia: " + dateIndependencia)
//console.log("La batalla de Boyaca: " + dateBatallaBoyaca)
//console.log("Día de la inmaculada concepción: " + dateInmaculada)
//console.log("Día de Navidad: " + dateNavidad)
//console.log("Jueves Santo: " + dateJuevesSanto)
//console.log("Viernes Santo: " + dateViernesSanto)
//console.log("Día de la ascensión: " + dateAscencion)
//console.log("Día del corpus christi: " + dateCorpusChristi)
//console.log("Día del sagrado corazón: " + dateSagradoCorazon)
//console.log("Día de los reyes magos: " + dateEpifania)
//console.log("Día de San Jose: " + dateSanJose)
//console.log("Dia de San Pedro y San Pablo: " + dateSPSP)
//console.log("Día de la Asunción de la virgen: " + dateAsuncVirgen)
//console.log("Día de la raza: " + dateRaza)
//console.log("Día de todos los santos: " + dateSantos)
//console.log("Día de la independencia de cartagena: " + dateCartagena)

//------------------------------------//
//----Validación Motor de Reglas-----//
//-----------------------------------//

var InputDate = new Date("2020-01-06 00:00:00");
console.log("DEFINICION INPUT DATE: " + InputDate);

//InputDate = dateCartagena
switch (InputDate.toString())
   {
    case dateCartagena.toString() :
       console.log("TODAY IS CARTAGENA")
        break;
    case dateSantos.toString() :
       console.log("TODAY IS dateSantos")
        break;
    case dateRaza.toString() :
       console.log("TODAY IS dateRaza")
        break;
    case dateAsuncVirgen.toString() :
       console.log("TODAY IS dateAsuncVirgen")
        break;
    case dateSPSP.toString() :
       console.log("TODAY IS dateSPSP")
        break;
    case dateSanJose.toString() :
       console.log("TODAY IS CARTAGENA")
        break;
    case dateEpifania.toString() :
       console.log("TODAY IS dateEpifania")
        break;
    case dateSagradoCorazon.toString() :
       console.log("TODAY IS dateSagradoCorazon")
        break;
    case dateCorpusChristi.toString() :
       console.log("TODAY IS dateCorpusChristi")
        break;
    case dateAscencion.toString() :
       console.log("TODAY IS dateAscencion")
        break;
    case dateViernesSanto.toString() :
       console.log("TODAY IS dateViernesSanto")
        break;
    case dateJuevesSanto.toString() :
       console.log("TODAY IS dateJuevesSanto")
        break;
    case dateInmaculada.toString() :
       console.log("TODAY IS dateInmaculada")
        break;
    case dateBatallaBoyaca.toString() :
       console.log("TODAY IS dateBatallaBoyaca")
        break;
    case dateIndependencia.toString() :
       console.log("TODAY IS dateIndependencia")
        break;
    case dateTrabajo.toString() :
       console.log("TODAY IS dateTrabajo")
        break;
    case dateNuevoAno.toString() :
       console.log("TODAY IS dateNuevoAno")
        break;
    default:
        console.log("VALOR POR DEFECTO SW CASE: " + dateCartagena);
        break;
}</code>```

答:
You can not compare date objects like that.

Despite both of these dates being the same value. They are not equal.

const dateString = "2020/11/11"
let date1 = new Date(dateString)
let date2 = new Date(dateString)

console.log('date1', date1)
console.log('date2', date2)

console.log('equal =', date1 === date2)```
</div>
</div>
</p>

<p>To fix this, you can call <code>toString()</code> and compare the strings.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const dateString = "2020/11/11"
let date1 = new Date(dateString)
let date1String = date1.toString()
let date2 = new Date(dateString)
let date2String = date2.toString()

console.log('date1String', date1String)
console.log('date2String', date2String)

console.log('equal =', date1String === date2String)</code>```

Body:
The Case should stop on Cartagena's Day.
I am trying to math the Dynamic Public Holidays of the Colombian Calendar with an INPUT VAR.
This code is defined by 3 main functions, 1 for calculating the PASCUA DAY, 1 for calculating MONDAY public holidays but with dynamic week and the last one for static public holidays.

I can't find why is not wokring, there is a lot of console log for debug purpose.

var date = new Date();
var dateYear = date.getFullYear();

// Dia de San Jose
var dateSanJose = dateYear + "/03/19";
dateSanJose = new Date(dateSanJose);

// Dia de la epifania
var dateEpifania = dateYear + "/01/06";
dateEpifania = new Date(dateEpifania);

// Dia de San Pedro y San Pablo
var dateSPSP = dateYear + "/06/29";
dateSPSP = new Date(dateSPSP);

// Dia de la Asunción de la Virgen
var dateAsuncVirgen = dateYear + "/08/15";
dateAsuncVirgen = new Date(dateAsuncVirgen);

// Día de la raza
var dateRaza = dateYear + "/10/12";
dateRaza = new Date(dateRaza);

// Día de todos los santos
var dateSantos = dateYear + "/11/01";
dateSantos = new Date(dateSantos);

// Día de la independencia de cartagena
var dateCartagena = dateYear + "/11/11";
dateCartagena = new Date(dateCartagena);

//---------- FECHAS FIJAS -----------//
var dateNuevoAno = new Date(dateYear + "/01/01");
var dateTrabajo = new Date(dateYear + "/05/01");
var dateIndependencia = new Date(dateYear + "/07/20");
var dateBatallaBoyaca = new Date(dateYear + "/08/07");
var dateInmaculada = new Date(dateYear + "/12/08");
var dateNavidad = new Date(dateYear + "/12/25");

//---------- FECHAS SEGÚN PASCUA -----------//
var pascuaDay = pascua(dateYear);
var dateJuevesSanto = operateDays(3, pascuaDay, false);
var dateViernesSanto = operateDays(2, pascuaDay, false);
var dateAscencion = operateDays(43, pascuaDay, true);
var dateCorpusChristi = operateDays(64, pascuaDay, true);
var dateSagradoCorazon = operateDays(71, pascuaDay, true);

//----------- FECHAS TRASLADABLES----------//

var dateSanJose = trasladableHolidays(dateSanJose);
var dateEpifania = trasladableHolidays(dateEpifania);
var dateSPSP = trasladableHolidays(dateSPSP);
var dateAsuncVirgen = trasladableHolidays(dateAsuncVirgen);
var dateRaza = trasladableHolidays(dateRaza);
var dateSantos = trasladableHolidays(dateSantos);
var dateCartagena = trasladableHolidays(dateCartagena);

function trasladableHolidays(dateVariable){
    dateCorrect = dateVariable;
    dateCorrect.setDate(dateVariable.getDate() + (1 + 7 - dateVariable.getDay()) % 7);
    return dateCorrect;
}

function operateDays(days, date, suma){
    var initialDate = new Date(date);
    var newDate = new Date(date);
    if (suma) {
        newDate.setDate(initialDate.getDate() + days);
    }else{
        newDate.setDate(initialDate.getDate() - days);
    }
    return newDate;
}

//Función para realizar el cálculo del domingo de pascua
function pascua(year) {
    if(year>1900 && year<2099) {
        M=24; N=5;
    }
    else if (year>2100 && year<2199) {
        M=24; N=6;
    }
    else if (year>2200 && year<2299) {
        M=25; N=0;
    }
    a = year % 19;
    b = year % 4;
    c = year % 7;
    d = ((19*a) + M) % 30;
    e = ((2*b) + (4*c) + (6*d) + N) % 7;
    f = d + e;
    if (f < 10) {
        dia = f + 22; mes = 3;
    }
    else  {
        dia = f - 9;  mes = 4;
    }
    if(dia==26 && mes==4){
        dia = 19;
    }
    if(dia==25 && mes==4 && d==28 && e==6 && a>10){
        dia = 18;
    }
    pascua = new Date(year,mes-1,dia);
    return pascua;
};

console.log("Año nuevo: " + dateNuevoAno)
console.log("Día del trabajo: " + dateTrabajo)
console.log("Día de la independencia: " + dateIndependencia)
console.log("La batalla de Boyaca: " + dateBatallaBoyaca)
console.log("Día de la inmaculada concepción: " + dateInmaculada)
console.log("Día de Navidad: " + dateNavidad)
console.log("Jueves Santo: " + dateJuevesSanto)
console.log("Viernes Santo: " + dateViernesSanto)
console.log("Día de la ascensión: " + dateAscencion)
console.log("Día del corpus christi: " + dateCorpusChristi)
console.log("Día del sagrado corazón: " + dateSagradoCorazon)
console.log("Día de los reyes magos: " + dateEpifania)
console.log("Día de San Jose: " + dateSanJose)
console.log("Dia de San Pedro y San Pablo: " + dateSPSP)
console.log("Día de la Asunción de la virgen: " + dateAsuncVirgen)
console.log("Día de la raza: " + dateRaza)
console.log("Día de todos los santos: " + dateSantos)
console.log("Día de la independencia de cartagena: " + dateCartagena)

//------------------------------------//
//----Validación Motor de Reglas-----//
//-----------------------------------//

var InputDate = new Date("2020-11-16 00:00:00");
console.log("DEFINICION INPUT DATE: " + InputDate);

//InputDate = dateCartagena
switch (InputDate)
   {
    case dateCartagena :
       console.log("TODAY IS CARTAGENA")
        break;
    case 1:
        console.log("Today is Monday")
        break;
    default:
        console.log("VALOR POR DEFECTO SW CASE: " + dateCartagena);
        break;
}

This is the final solution hope this works for any one else.

var date = new Date();
var dateYear = date.getFullYear();

// Dia de San Jose
var dateSanJose = dateYear + "/03/19";
dateSanJose = new Date(dateSanJose);

// Dia de la epifania
var dateEpifania = dateYear + "/01/06";
dateEpifania = new Date(dateEpifania);

// Dia de San Pedro y San Pablo
var dateSPSP = dateYear + "/06/29";
dateSPSP = new Date(dateSPSP);

// Dia de la Asunción de la Virgen
var dateAsuncVirgen = dateYear + "/08/15";
dateAsuncVirgen = new Date(dateAsuncVirgen);

// Día de la raza
var dateRaza = dateYear + "/10/12";
dateRaza = new Date(dateRaza);

// Día de todos los santos
var dateSantos = dateYear + "/11/01";
dateSantos = new Date(dateSantos);

// Día de la independencia de cartagena
var dateCartagena = dateYear + "/11/11";
dateCartagena = new Date(dateCartagena);

//---------- FECHAS FIJAS -----------//
var dateNuevoAno = new Date(dateYear + "/01/01");
var dateTrabajo = new Date(dateYear + "/05/01");
var dateIndependencia = new Date(dateYear + "/07/20");
var dateBatallaBoyaca = new Date(dateYear + "/08/07");
var dateInmaculada = new Date(dateYear + "/12/08");
var dateNavidad = new Date(dateYear + "/12/25");

//---------- FECHAS SEGÚN PASCUA -----------//
var pascuaDay = pascua(dateYear);
var dateJuevesSanto = operateDays(3, pascuaDay, false);
var dateViernesSanto = operateDays(2, pascuaDay, false);
var dateAscencion = operateDays(43, pascuaDay, true);
var dateCorpusChristi = operateDays(64, pascuaDay, true);
var dateSagradoCorazon = operateDays(71, pascuaDay, true);

//----------- FECHAS TRASLADABLES----------//

var dateSanJose = trasladableHolidays(dateSanJose);
var dateEpifania = trasladableHolidays(dateEpifania);
var dateSPSP = trasladableHolidays(dateSPSP);
var dateAsuncVirgen = trasladableHolidays(dateAsuncVirgen);
var dateRaza = trasladableHolidays(dateRaza);
var dateSantos = trasladableHolidays(dateSantos);
var dateCartagena = trasladableHolidays(dateCartagena);

function trasladableHolidays(dateVariable){
    dateCorrect = dateVariable;
    dateCorrect.setDate(dateVariable.getDate() + (1 + 7 - dateVariable.getDay()) % 7);
    return dateCorrect;
}

function operateDays(days, date, suma){
    var initialDate = new Date(date);
    var newDate = new Date(date);
    if (suma) {
        newDate.setDate(initialDate.getDate() + days);
    }else{
        newDate.setDate(initialDate.getDate() - days);
    }
    return newDate;
}

//Función para realizar el cálculo del domingo de pascua
function pascua(year) {
    if(year>1900 && year<2099) {
        M=24; N=5;
    }
    else if (year>2100 && year<2199) {
        M=24; N=6;
    }
    else if (year>2200 && year<2299) {
        M=25; N=0;
    }
    a = year % 19;
    b = year % 4;
    c = year % 7;
    d = ((19*a) + M) % 30;
    e = ((2*b) + (4*c) + (6*d) + N) % 7;
    f = d + e;
    if (f < 10) {
        dia = f + 22; mes = 3;
    }
    else  {
        dia = f - 9;  mes = 4;
    }
    if(dia==26 && mes==4){
        dia = 19;
    }
    if(dia==25 && mes==4 && d==28 && e==6 && a>10){
        dia = 18;
    }
    pascua = new Date(year,mes-1,dia);
    return pascua;
};

//console.log("Año nuevo: " + dateNuevoAno)
//console.log("Día del trabajo: " + dateTrabajo)
//console.log("Día de la independencia: " + dateIndependencia)
//console.log("La batalla de Boyaca: " + dateBatallaBoyaca)
//console.log("Día de la inmaculada concepción: " + dateInmaculada)
//console.log("Día de Navidad: " + dateNavidad)
//console.log("Jueves Santo: " + dateJuevesSanto)
//console.log("Viernes Santo: " + dateViernesSanto)
//console.log("Día de la ascensión: " + dateAscencion)
//console.log("Día del corpus christi: " + dateCorpusChristi)
//console.log("Día del sagrado corazón: " + dateSagradoCorazon)
//console.log("Día de los reyes magos: " + dateEpifania)
//console.log("Día de San Jose: " + dateSanJose)
//console.log("Dia de San Pedro y San Pablo: " + dateSPSP)
//console.log("Día de la Asunción de la virgen: " + dateAsuncVirgen)
//console.log("Día de la raza: " + dateRaza)
//console.log("Día de todos los santos: " + dateSantos)
//console.log("Día de la independencia de cartagena: " + dateCartagena)

//------------------------------------//
//----Validación Motor de Reglas-----//
//-----------------------------------//

var InputDate = new Date("2020-01-06 00:00:00");
console.log("DEFINICION INPUT DATE: " + InputDate);

//InputDate = dateCartagena
switch (InputDate.toString())
   {
    case dateCartagena.toString() :
       console.log("TODAY IS CARTAGENA")
        break;
    case dateSantos.toString() :
       console.log("TODAY IS dateSantos")
        break;
    case dateRaza.toString() :
       console.log("TODAY IS dateRaza")
        break;
    case dateAsuncVirgen.toString() :
       console.log("TODAY IS dateAsuncVirgen")
        break;
    case dateSPSP.toString() :
       console.log("TODAY IS dateSPSP")
        break;
    case dateSanJose.toString() :
       console.log("TODAY IS CARTAGENA")
        break;
    case dateEpifania.toString() :
       console.log("TODAY IS dateEpifania")
        break;
    case dateSagradoCorazon.toString() :
       console.log("TODAY IS dateSagradoCorazon")
        break;
    case dateCorpusChristi.toString() :
       console.log("TODAY IS dateCorpusChristi")
        break;
    case dateAscencion.toString() :
       console.log("TODAY IS dateAscencion")
        break;
    case dateViernesSanto.toString() :
       console.log("TODAY IS dateViernesSanto")
        break;
    case dateJuevesSanto.toString() :
       console.log("TODAY IS dateJuevesSanto")
        break;
    case dateInmaculada.toString() :
       console.log("TODAY IS dateInmaculada")
        break;
    case dateBatallaBoyaca.toString() :
       console.log("TODAY IS dateBatallaBoyaca")
        break;
    case dateIndependencia.toString() :
       console.log("TODAY IS dateIndependencia")
        break;
    case dateTrabajo.toString() :
       console.log("TODAY IS dateTrabajo")
        break;
    case dateNuevoAno.toString() :
       console.log("TODAY IS dateNuevoAno")
        break;
    default:
        console.log("VALOR POR DEFECTO SW CASE: " + dateCartagena);
        break;
}

Body:
You can not compare date objects like that.

Despite both of these dates being the same value. They are not equal.

const dateString = "2020/11/11"
let date1 = new Date(dateString)
let date2 = new Date(dateString)

console.log('date1', date1)
console.log('date2', date2)

console.log('equal =', date1 === date2)

To fix this, you can call toString() and compare the strings.

const dateString = "2020/11/11"
let date1 = new Date(dateString)
let date1String = date1.toString()
let date2 = new Date(dateString)
let date2String = date2.toString()

console.log('date1String', date1String)
console.log('date2String', date2String)

console.log('equal =', date1String === date2String)


问:
Variation in prediction length and test data length while using predict_generator
```<code>df = pd.read_csv('F:/series.csv')

train, validate, test = df[0:60], df[60:80], df[80:100]

sc = MinMaxScaler(feature_range = (-1, 1))

train = sc.fit_transform(train)

validate = sc.fit_transform(validate)

test = sc.fit_transform(test)

train = train.reshape((len(train),1))

test = test.reshape((len(test),1))

validate = validate.reshape((len(validate),1))

n_input = 5

n_features = 1

generator_train = TimeseriesGenerator(train, train, length=n_input, batch_size=2)

generator_validate = TimeseriesGenerator(validate, validate, length=n_input, batch_size=2)

generator_test = TimeseriesGenerator(test, test, length=n_input, batch_size=2)

model = Sequential()

model.add(LSTM(200, return_sequences = True,  input_shape=(n_input, n_features)))

model.add(Dropout(0.2))

model.add(LSTM(200))

model.add(Dense(units = 1))

model.compile(loss='mean_squared_error', optimizer='adam')

history = model.fit_generator(generator_train, epochs= 100, validation_data = generator_validate)

model.evaluate_generator(generator_test)

prediction = model.predict_generator(generator_test, steps = 5)

prediction.shape
(10,1)

test.shape
(20,1)
</code>```

This confuses me, How to solve the problem? How to evaluate the predicted and test data? Whats the mistake I am making?

答: I just found the answer, the predict generator length depends on length of (test_generator*batch_size). Now to measure RMSE eliminate the first n_input length of test data. Now the size becomes equal.</p>

Body:
df = pd.read_csv('F:/series.csv')

train, validate, test = df[0:60], df[60:80], df[80:100]

sc = MinMaxScaler(feature_range = (-1, 1))

train = sc.fit_transform(train)

validate = sc.fit_transform(validate)

test = sc.fit_transform(test)

train = train.reshape((len(train),1))

test = test.reshape((len(test),1))

validate = validate.reshape((len(validate),1))

n_input = 5

n_features = 1

generator_train = TimeseriesGenerator(train, train, length=n_input, batch_size=2)

generator_validate = TimeseriesGenerator(validate, validate, length=n_input, batch_size=2)

generator_test = TimeseriesGenerator(test, test, length=n_input, batch_size=2)

model = Sequential()

model.add(LSTM(200, return_sequences = True,  input_shape=(n_input, n_features)))

model.add(Dropout(0.2))

model.add(LSTM(200))

model.add(Dense(units = 1))

model.compile(loss='mean_squared_error', optimizer='adam')

history = model.fit_generator(generator_train, epochs= 100, validation_data = generator_validate)

model.evaluate_generator(generator_test)

prediction = model.predict_generator(generator_test, steps = 5)

prediction.shape
(10,1)

test.shape
(20,1)

This confuses me, How to solve the problem? How to evaluate the predicted and test data? Whats the mistake I am making?


问:
Architectural Patterns for a Game
So I've got a solution that contains a few big projects, which I'm trying to break down into smaller projects with more isolated responsibilities. This is a game, but I'm mainly a LOB developer and I think the principles are probably universal, and I think I could learn something here.

The dependencies in some of the objects are a bit too tightly intertwined, and I'm hoping for some help on how to untangle them. Or maybe some sort of pattern or abstraction that might make them more manageable.

Ares.Core.World has classes in it like Creatures, Items, etc. All of them inherit from Entity, which is aware of what cell on the map it exist at. It accomplishes this by holding a reference to a  Ares.Core.UI.MapControls.MapCell... And you can see that the wires are already getting crossed.

Ares.Core.UI.MapControls contains Map and MapCell, each of which contain Lists of creatures and items that they contain. MapCell also inherits from Ares.Core.World.Entity since that solved a few early problems very elegantly -- for instance, all Entities have inventory.

I would like to find a way to split UI and World out into seperate projects (Ares.World and Ares.UI) since UI and the overarching world should probably be seperate concerns. But as you can see, the way it is now the two projects would need to reference each other, and circular references are not allowed.

I'm wondering if there are any architectural patterns out there that might help in this situation. Thanks!

答:
So, your World classes - Creatures, Items, etc. - they all need something from MapCell.

Can you reasonably create an interface (or several) that represent what the World Entities need?  So that the Entities only need an implementation of that interface?

This would be the first step to decoupling the two.  Perhaps obviously, none of the method signatures or properties of this interface can include classes from the UI project.  It should be defined with standard types or custom types in a library both World and UI reference (e.g., Ares.Core).

Then, in the UI project define implementations of the interface(s) that encapsulate a MapCell and provide what is needed to the World Entities.

Use your IoC of choice to provide the implementation where it is needed, depending on how you get the MapCell, you may need to also layer on a Factory.

Without more details of your particular needs it's hard to be specific, but I think this approach in general should be workable.

Title: Architectural Patterns for a Game


答: Here problem is var InputDate = new Date("2020-11-16 00:00:00"); statement since InputDate will be an Object and switch statement works with primitive data type.

Title: JavaScript SWITCH CASE not working with variables Date Format


问:
Running Mean of Circular Data: Average and Standard Deviation?
Given such a list:

mylist = [1, 2, 3, 4, 5, 6, 7]

with N = 3 as the size of running mean at each step.

What is the fastest way to calculate the average and standard deviation of this list?

If it was only average np.convolve could do the job, but what about the standard deviation? or standard error?

答:
import numpy as np

mylist = [1, 2, 3, 4, 5, 6, 7]
double = mylist * 2
N = 3
mean_std = [(np.mean(double[i:i+N]), np.std(double[i:i+N])) for i in range(len(mylist))]
```


问:
Power BI Retrieve Last Column Value by Group
I'm working in a dashboard that control some kpis at my company. Now, I need to compare every result with the previous one, according to employee number. In the sample below, I show a little exemple of my data, and the expected result in the last column (previous score). I've tryed to solve that using a lot os calculated columns. I got close using the following:

```<code>PreviousScore =
VAR EMPNUMBER = BASE[Employee Number]
VAR REF = BASE[Score]

RETURN
CALCULATE(LASTNONBLANK(BASE[Employee Number];EMPNUMBER);FILTER(BASE;BASE[Employee Number]=EMPNUMBER);FILTER(BASE;BASE[Date]<EARLIER(BASE[Date])))
</code>```

Employee Number Date    Score   Previous score

1234    01/01/2019  1   BLANK

1235    01/01/2019  4   BLANK

1236    01/01/2019  2   BLANK

1288    01/01/2019  0   BLANK

1259    01/01/2019  0   BLANK

1234    01/02/2019  3   1

1235    01/02/2019  4   4

1236    01/02/2019  1   2

1288    01/02/2019  2   0

1259    01/02/2019  4   0

1234    01/03/2019  1   3

1235    01/03/2019  2   4

1236    01/03/2019  3   1

1288    01/03/2019  0   2

1259    01/03/2019  1   4

1234    01/04/2019  2   1

1235    01/04/2019  3   2

1236    01/04/2019  8   3

1288    01/04/2019  BLANK   0

1259    01/04/2019  BLANK   1

I hope someone could help with this issue.

LW

答:
You have no dependance between your dates, you pickup the earlier column and by accident they are in the right order.

The following query will give you the right result:

```<code>Previous score =
    var empNR = score[Employee Number]
    var theDate = score[Date]
    var empData = FILTER(score;score[Employee Number] = empNR)
    var prevDate = CALCULATE(MAX(score[Date]);empData;score[Date] < theDate)
    return CALCULATE(MAX(score[Score]);FILTER(empData; score[Date] = prevDate))
</code>```

I filter on emp number to get the data of that employee

I get the prevDate by getting the max of all dates which are lower
than selected date

last step is to get the one row and return the score

Body:
I'm working in a dashboard that control some kpis at my company. Now, I need to compare every result with the previous one, according to employee number. In the sample below, I show a little exemple of my data, and the expected result in the last column (previous score). I've tryed to solve that using a lot os calculated columns. I got close using the following:

PreviousScore =
VAR EMPNUMBER = BASE[Employee Number]
VAR REF = BASE[Score]

RETURN
CALCULATE(LASTNONBLANK(BASE[Employee Number];EMPNUMBER);FILTER(BASE;BASE[Employee Number]=EMPNUMBER);FILTER(BASE;BASE[Date]<EARLIER(BASE[Date])))

Employee Number Date    Score   Previous score

1234    01/01/2019  1   BLANK

1235    01/01/2019  4   BLANK

1236    01/01/2019  2   BLANK

1288    01/01/2019  0   BLANK

1259    01/01/2019  0   BLANK

1234    01/02/2019  3   1

1235    01/02/2019  4   4

1236    01/02/2019  1   2

1288    01/02/2019  2   0

1259    01/02/2019  4   0

1234    01/03/2019  1   3

1235    01/03/2019  2   4

1236    01/03/2019  3   1

1288    01/03/2019  0   2

1259    01/03/2019  1   4

1234    01/04/2019  2   1

1235    01/04/2019  3   2

1236    01/04/2019  8   3

1288    01/04/2019  BLANK   0

1259    01/04/2019  BLANK   1

I hope someone could help with this issue.

LW

Body:
You have no dependance between your dates, you pickup the earlier column and by accident they are in the right order.

The following query will give you the right result:

Previous score =
    var empNR = score[Employee Number]
    var theDate = score[Date]
    var empData = FILTER(score;score[Employee Number] = empNR)
    var prevDate = CALCULATE(MAX(score[Date]);empData;score[Date] < theDate)
    return CALCULATE(MAX(score[Score]);FILTER(empData; score[Date] = prevDate))

I filter on emp number to get the data of that employee

I get the prevDate by getting the max of all dates which are lower
than selected date

last step is to get the one row and return the score


问:
"self" in objective C

Possible Duplicate:

  Should I Use self Keyword (Properties) In The Implementation?

Say I have a class "Person", with an instance variable "age". Coming from Python, when writing methods for the Person class, I am used to accessing age using "self.age", however in Objective C I have noticed that both and "self.age" and "age" are accepted when referring to the instance variable (whereas in Python only the former would work).

When it is not explicitly specified which instance's variable you mean, does it default to 'self'? And is it considered bad style not to explicitly specify self? If not, are there conventions on when to use self.age and when to use age?

答: age and self.age are two completely different things. Inside of instance methods, the object's instance variables are implicitly defined in the scope, unless shadowed by a local variable (See The Objective-C Programming Language). That is why age works correctly. When using the dot notation, you are referencing a property, which means you are actually calling [self age] instead of directly accessing the instance variable. You can also access an instance variable directly by using the structure pointer operator (->). This is rarely used, but can be used to directly access variables in other instances of the same class or different classes, as well as self. Therefore, age and self->age are exactly the same thing, but self.age is completely different.

Title: "self" in objective C


问:
Django - specify upload path
So I have a upload form:

def upload(request):
    if request.method == 'POST':
        uploaded_file = request.FILES['file']
        fs = FileSystemStorage()
        fs.save(uploaded_file.name, uploaded_file)
    return render(request, 'nas/upload.html')
```

But I am not sure where to specify where the file gets uploaded to. I would like it to come from the currently active drive, which has an attribute Drive.path

答:
We can do something like this:

```<code>def upload(request):

    if request.method == 'POST':

        # unpack request:
        uploaded_file = request.FILES['file']

        # save file locally:
        with open('/path/to/file/destination/file.extension', 'w+') as destination:
            destination.write(uploaded_file)

    return render(request, 'nas/upload.html')
</code>```

More here: https://docs.djangoproject.com/en/3.0/topics/http/file-uploads/

Title: Django - specify upload path

Body:
So I have a upload form:

def upload(request):
    if request.method == 'POST':
        uploaded_file = request.FILES['file']
        fs = FileSystemStorage()
        fs.save(uploaded_file.name, uploaded_file)
    return render(request, 'nas/upload.html')

But I am not sure where to specify where the file gets uploaded to. I would like it to come from the currently active drive, which has an attribute Drive.path

Body:
We can do something like this:

def upload(request):

    if request.method == 'POST':

        # unpack request:
        uploaded_file = request.FILES['file']

        # save file locally:
        with open('/path/to/file/destination/file.extension', 'w+') as destination:
            destination.write(uploaded_file)

    return render(request, 'nas/upload.html')

More here: https://docs.djangoproject.com/en/3.0/topics/http/file-uploads/


问:
Angular 5 Reactive Form Pattern Validators
I need to come up with a validation pattern in Reactive Form (Form Control) using Validators.pattern. The conditions are Alphanumeric, Only underscore_, hyphen- are allowed. Any type of space should not be allowed. Is there any one single pattern that will help me achieve this.

Thanks.

答:
try this

```<code> pattern1 =  "^[0-9_-]{10,12}$";
 phone: ['', [Validators.required, Validators.pattern(this.pattern1)]]
</code>```

Body:
try this

 pattern1 =  "^[0-9_-]{10,12}$";
 phone: ['', [Validators.required, Validators.pattern(this.pattern1)]]


问:
ConfigurationLoadError: Unable to load configuration file
I have no idea why but I am unable to use conda within terminal. Conda command results in "ConfigurationLoadError"

```<code>ConfigurationLoadError: Unable to load configuration file.
  path: /Users/kiranmarathe/.condarc
  reason: invalid yaml at line 2, column 42
</code>```

kiranmarathe$ cat /Users/kiranmarathe/.condarc

```<code>channels:
  - defaults
  - conda-forge
  - bioconda
  - http://conda.binstar.org/faircloth-lab
</code>```

答: Go to the /Users/kiranmarathe/ path and delete the .condarc file. I think the issue will be resolved.

Body:
I have no idea why but I am unable to use conda within terminal. Conda command results in "ConfigurationLoadError"

ConfigurationLoadError: Unable to load configuration file.
  path: /Users/kiranmarathe/.condarc
  reason: invalid yaml at line 2, column 42

kiranmarathe$ cat /Users/kiranmarathe/.condarc

channels:
  - defaults
  - conda-forge
  - bioconda
  - http://conda.binstar.org/faircloth-lab


问:
Log Buffering Through MSMQ to WCF Web Service
I have an interesting situation on my hands. For a few years now we've had a WCF service that runs on an IIS box on our network that we use for logging. Applications use basicHttpBinding to send log messages and it logs them to a database. Most of the logging from all other applications is limited to a few dozen logs per operation. Recently we've ported another application to use this logging service. This application logs quite a bit more aggressively than any of the other clients for our logging service. It has an operation that during its course could log over 100,000 messages (this is for importing 100,000 records via CSV file).

In trying to find a way to make this run more efficiently it was suggested that I try MSMQ to queue the log requests and forward them on to the service instead of having the application communicate directly with the logging service (the request was being sent in a separate thread for performance purposes). In this way the application isn't blocked while the log is being written. I have implemented a proof of concept for this MSMQ solution on my local machine but as I have never used MSMQ before, and as I am only now learning what its place is technologically, I'm finding myself with a lot of questions and few answers. I'm hoping someone can point me to some concise information on how MSMQ works so that I can better debug this proof of concept I have written.

What I'm seeing after implementing MSMQ:

My application that sends the logs to
MSMQ returns almost immediately
(rather than waiting for the log to
be committed) which is what I want.

Even though I sent 1000 logs to the
MSMQ application in fewer than 30
seconds, it takes several minutes for
all 1000 logs to make it to the
database. It appears as though my
queue has some sort of throttling
enabled where it is holding back the
log requests but I don't know how / where to check that.

If I use net.tcp on the server receiving the logs from the MSMQ service I get a ton of service timeout errors and only 90% (or so) of the logs make it to the database but if I use basicHttpBinding it works reliably.

Here is the code in my MSMQ service:

```<code>public void QueueLog(Log log)
{
    try
    {
        ServiceClient writeLog = getLoggingService();

        string exceptionText = log.Exception == null ? string.Empty : log.Exception.ToString();
        writeLog.WriteCompatibleLog(log.LoggerName, (LoggingService.Logging.LogType)log.LogType, exceptionText, log.Message, log.ApplicationName, Utility.GetAssemblyVersion(Assembly.GetCallingAssembly()),
            Utility.GetFirstIPAddress(), Utility.GetHostName(), log.Category);
    }
    catch (Exception ex)
    {
        Debug.WriteLine("LoggingServiceWrapper.DotNet Error\n\n" + ex.GetBaseException().Message + "\n\n" + ex.GetBaseException().StackTrace);
    }
}

private ServiceClient getLoggingService()
{
    return new ServiceClient(new BasicHttpBinding(), new EndpointAddress("http://MyServer/Service.svc"));

}
</code>```

Here is the code of me creating the MSMQ service

```<code>if (!MessageQueue.Exists(Properties.Settings.Default.QueueName))
{
    MessageQueue.Create(Properties.Settings.Default.QueueName, true);
}

ServiceHost serviceHost = new ServiceHost(typeof(LoggingServiceQueue.LoggingServiceQueue), new Uri(Properties.Settings.Default.Address));
{
    serviceHost.Open();

    Console.ReadLine();

    serviceHost.Close();
}
</code>```

Here is the code in the application I use to call the MSMQ service:

```<code>LoggingServiceQueueClient client = new LoggingServiceQueueClient(new NetMsmqBinding(NetMsmqSecurityMode.None), new EndpointAddress("net.msmq://localhost/private/Logging"));

client.QueueLog(new LoggingServiceQueue.Log
{
    LoggerName = loggerName,
    LogType = (LoggingServiceQueue.LogType)logType,
    ApplicationName = applicationName,
    Category = category,
    Exception = exception,
    Message = message,
    SourceHostName = Utility.GetHostName(),
    SourceIp = Utility.GetFirstIPAddress(),
    Version = Utility.GetAssemblyVersion(callingAssembly)
});
</code>```

I appreciate any help someone can provide. I'm a little lost on exactly what set of features are available to me using MSMQ. I have done 6 or so hours of research via google. Most docs I have found are pretty old (2007) and are a tough read. Perhaps they are expecting me to have some baser level of knowledge on the subject.

答:
What you're seeing (if you're using net.msmq binding on your WCF) is what is designed to happen.

MSMQ, as a store-and-forward facility, will store messages in a queue at the sending client and the receiving server until either network or processing bandwidth is available. What this does is take load off the client (as you've observed) by making the process asynchronous.

You can view the statuses of the queues using Performance Monitor, the number of messages in the outbound queue (at the client) and the server queue are written to performance counters in realtime and can be viewed and/or logged.

If the performance is sub-optimal, you could look to change the WCF throttling settings to allow more concurrent connections in your service behaviour.

e.g.

```<code><serviceThrottling
         maxConcurrentCalls="20"
         maxConcurrentSessions="20"
         maxConcurrentInstances="20"
       />
</code>```

Body:
I have an interesting situation on my hands. For a few years now we've had a WCF service that runs on an IIS box on our network that we use for logging. Applications use basicHttpBinding to send log messages and it logs them to a database. Most of the logging from all other applications is limited to a few dozen logs per operation. Recently we've ported another application to use this logging service. This application logs quite a bit more aggressively than any of the other clients for our logging service. It has an operation that during its course could log over 100,000 messages (this is for importing 100,000 records via CSV file).

In trying to find a way to make this run more efficiently it was suggested that I try MSMQ to queue the log requests and forward them on to the service instead of having the application communicate directly with the logging service (the request was being sent in a separate thread for performance purposes). In this way the application isn't blocked while the log is being written. I have implemented a proof of concept for this MSMQ solution on my local machine but as I have never used MSMQ before, and as I am only now learning what its place is technologically, I'm finding myself with a lot of questions and few answers. I'm hoping someone can point me to some concise information on how MSMQ works so that I can better debug this proof of concept I have written.

What I'm seeing after implementing MSMQ:

My application that sends the logs to
MSMQ returns almost immediately
(rather than waiting for the log to
be committed) which is what I want.

Even though I sent 1000 logs to the
MSMQ application in fewer than 30
seconds, it takes several minutes for
all 1000 logs to make it to the
database. It appears as though my
queue has some sort of throttling
enabled where it is holding back the
log requests but I don't know how / where to check that.

If I use net.tcp on the server receiving the logs from the MSMQ service I get a ton of service timeout errors and only 90% (or so) of the logs make it to the database but if I use basicHttpBinding it works reliably.

Here is the code in my MSMQ service:

public void QueueLog(Log log)
{
    try
    {
        ServiceClient writeLog = getLoggingService();

        string exceptionText = log.Exception == null ? string.Empty : log.Exception.ToString();
        writeLog.WriteCompatibleLog(log.LoggerName, (LoggingService.Logging.LogType)log.LogType, exceptionText, log.Message, log.ApplicationName, Utility.GetAssemblyVersion(Assembly.GetCallingAssembly()),
            Utility.GetFirstIPAddress(), Utility.GetHostName(), log.Category);
    }
    catch (Exception ex)
    {
        Debug.WriteLine("LoggingServiceWrapper.DotNet Error\n\n" + ex.GetBaseException().Message + "\n\n" + ex.GetBaseException().StackTrace);
    }
}

private ServiceClient getLoggingService()
{
    return new ServiceClient(new BasicHttpBinding(), new EndpointAddress("http://MyServer/Service.svc"));

}

Here is the code of me creating the MSMQ service

if (!MessageQueue.Exists(Properties.Settings.Default.QueueName))
{
    MessageQueue.Create(Properties.Settings.Default.QueueName, true);
}

ServiceHost serviceHost = new ServiceHost(typeof(LoggingServiceQueue.LoggingServiceQueue), new Uri(Properties.Settings.Default.Address));
{
    serviceHost.Open();

    Console.ReadLine();

    serviceHost.Close();
}

Here is the code in the application I use to call the MSMQ service:

LoggingServiceQueueClient client = new LoggingServiceQueueClient(new NetMsmqBinding(NetMsmqSecurityMode.None), new EndpointAddress("net.msmq://localhost/private/Logging"));

client.QueueLog(new LoggingServiceQueue.Log
{
    LoggerName = loggerName,
    LogType = (LoggingServiceQueue.LogType)logType,
    ApplicationName = applicationName,
    Category = category,
    Exception = exception,
    Message = message,
    SourceHostName = Utility.GetHostName(),
    SourceIp = Utility.GetFirstIPAddress(),
    Version = Utility.GetAssemblyVersion(callingAssembly)
});

I appreciate any help someone can provide. I'm a little lost on exactly what set of features are available to me using MSMQ. I have done 6 or so hours of research via google. Most docs I have found are pretty old (2007) and are a tough read. Perhaps they are expecting me to have some baser level of knowledge on the subject.

Body:
What you're seeing (if you're using net.msmq binding on your WCF) is what is designed to happen.

MSMQ, as a store-and-forward facility, will store messages in a queue at the sending client and the receiving server until either network or processing bandwidth is available. What this does is take load off the client (as you've observed) by making the process asynchronous.

You can view the statuses of the queues using Performance Monitor, the number of messages in the outbound queue (at the client) and the server queue are written to performance counters in realtime and can be viewed and/or logged.

If the performance is sub-optimal, you could look to change the WCF throttling settings to allow more concurrent connections in your service behaviour.

e.g.

<serviceThrottling
         maxConcurrentCalls="20"
         maxConcurrentSessions="20"
         maxConcurrentInstances="20"
       />


问:
How do I create an html code with a string on python to render on django template
In my views:

```<code>post_image = '<div class="images slides"></div>'
</code>```

console.log(document.body):

```<code><body>
    "<div class="images slides"</div>"
</body>
</code>```

What I want:

```<code><body>
    <div class="images slides"</div>
</body>
</code>```

答:
To render the content as HTML, use the safe filter

```<code><div>
    {{ post_image|safe }}
</div>
</code>```

https://docs.djangoproject.com/en/3.0/ref/templates/builtins/#safe

Body:
In my views:

post_image = '

'

console.log(document.body):

    "<div class="images slides"
"

What I want:

    <div class="images slides"

Body:
To render the content as HTML, use the safe filter

<div>
    {{ post_image|safe }}
</div>

https://docs.djangoproject.com/en/3.0/ref/templates/builtins/#safe


问:
Onclick event on html calendar
I've been making a simple scheduler using html,css and js. I've not made any tables using the table tags in html but I've made the table using div tags and css. Now I want to add and onclick function on one of the cells that appear on the table. Can someone help make that function cause every time I try, a cell suddenly disappears upon refresh. Here's the source code to the calendar that I've made.</p>

```<code><div id="calendar">
        <ul class="weekdays">
            <div id="course">BIT</div>
            <li>Time</li>
            <li>Sunday</li>
            <li>Monday</li>
            <li>Tuesday</li>
            <li>Wednesday</li>
            <li>Thursday</li>
            <li>Friday</li>
            <li>Saturday</li>

        </ul>
        <ul class="days">
            <li class="day other-month">
                <div class="date">8AM</div>
            </li>
            <li class="day other-month">
                <div class="date"></div>
                <div class="event">
                    <div class="event-desc">

                    </div>
                    <div class="event-time">

                    </div>
                </div>
            </li>
            <li class="day other-month">
                <div class="date"></div>
            </li>
            <li class="day other-month">
                <div class="date"></div>
            </li>
            <li class="day other-month">
                <div class="date"></div>
            </li>
            <li class="day">
                <div class="date"></div>
            </li>

            <li class="day">
                <div class="date"></div>
            </li>
            <li class="day">
                <div class="date"></div>
                <div class="event">
                    <div class="event-desc">

                    </div>
                    <div class="event-time">

                    </div>
                </div>
            </li>
        </ul>

        <ul class="days">
            <li class="day">
                <div class="date">9AM</div>
            </li>
            <li class="day">
                <div class="date"></div>
            </li>
            <li class="day">
                <div class="date"></div>
            </li>
            <li class="day">
                <div class="date"></div>
                <div class="event">
                    <div class="event-desc">

                    </div>
                    <div class="event-time">

                    </div>
                </div>
            </li>
            <li class="day">
                <div class="date"></div>

            </li>
            <li class="day">
                <div class="date"></div>
            </li>
            <li class="day">
                <div class="date"></div>
            </li>
            <li class="day">
                <div class="date"></div>
            </li>
        </ul>

        <ul class="days">
            <li class="day">
                <div class="date">10AM</div>
            </li>
            <li class="day">
                <div class="date"></div>
                <div class="event">
                    <div class="event-desc">

                    </div>
                    <div class="event-time">

                    </div>
                </div>

            </li>
            <li class="day">
                <div class="date"></div>
            </li>
            <li class="day">
                <div class="date"></div>
            </li>
            <li class="day">
                <div class="date"></div>
            </li>
            <li class="day">
                <div class="date"></div>
            </li>
            <li class="day">
                <div class="date"></div>
                <div class="event">
                    <div class="event-desc">

                    </div>
                    <div class="event-time">

                    </div>
                </div>
                <li class="day">
                <div class="date"></div>
            </li>
            </li>
        </ul>

        <ul class="days">
            <li class="day">
                <div class="date">11AM</div>
            </li>
            <li class="day">
                <div class="date"></div>
            </li>
            <li class="day">
                <div class="date"></div>
                <div class="event">
                    <div class="event-desc">

                    </div>
                    <div class="event-time">

                    </div>
                </div>
            </li>
            <li class="day">
                <div class="date"></div>
            </li>
            <li class="day">
                <div class="date"></div>
            </li>
            <li class="day">
                <div class="date"></div>
            </li>
            <li class="day">
                <div class="date"></div>
            </li>
            <li class="day">
                <div class="date"></div>
            </li>
        </ul>
        <ul class="days">
            <li class="day">
                <div class="date">12PM</div>
            </li>
            <li class="day">
                <div class="date"></div>
                <div class="event">
                    <div class="event-desc">

                    </div>
                    <div class="event-time">

                    </div>
                </div>
            </li>
            <li class="day">
                <div class="date"></div>
            </li>
            <li class="day">
                <div class="date"></div>
            </li>
            <li class="day">
                <div class="date"></div>
            </li>
            <li class="day">
                <div class="date"></div>
            </li>
            <li class="day">
                <div class="date"></div>
            </li>
            <li class="day">
                <div class="date"></div>
            </li>

        </ul>
        <ul class="days">
            <li class="day">
                <div class="date">1PM</div>
            </li>
            <li class="day">
                <div class="date other-month"></div>
            </li>
            <li class="day other-month">
                <div class="date"></div>
                <div class="event">
                    <div class="event-desc">

                    </div>
                    <div class="event-time">

                    </div>
                </div>
            </li>
            <li class="day other-month">
                <div class="date"></div>
            </li>
            <li class="day other-month">
                <div class="date"></div>
            </li>
            <li class="day other-month">
                <div class="date"></div>
            </li>
            <li class="day other-month">
                <div class="date"></div>
            </li>
            <li class="day">
                <div class="date"></div>
            </li>
        </ul>

        <ul class="days">
            <li class="day">
                <div class="date">2PM</div>
            </li>
            <li class="day">
                <div class="date other-month"></div>
            </li>
            <li class="day other-month">
                <div class="date"></div>
                <div class="event">
                    <div class="event-desc">

                    </div>
                    <div class="event-time">

                    </div>
                </div>
            </li>
            <li class="day other-month">
                <div class="date"></div>
            </li>
            <li class="day other-month">
                <div class="date"></div>
            </li>
            <li class="day other-month">
                <div class="date"></div>
            </li>
            <li class="day other-month">
                <div class="date"></div>
            </li>
            <li class="day">
                <div class="date"></div>
            </li>
        </ul>
        <ul class="days">
            <li class="day">
                <div class="date">3PM</div>
            </li>
            <li class="day">
                <div class="date other-month"></div>
            </li>
            <li class="day other-month">
                <div class="date"></div>
                <div class="event">
                    <div class="event-desc">

                    </div>
                    <div class="event-time">

                    </div>
                </div>
            </li>
            <li class="day other-month">
                <div class="date"></div>
            </li>
            <li class="day other-month">
                <div class="date"></div>
            </li>
            <li class="day other-month">
                <div class="date"></div>
            </li>
            <li class="day other-month">
                <div class="date"></div>
            </li>
            <li class="day">
                <div class="date"></div>
            </li>
        </ul>
        <ul class="days">
            <li class="day">
                <div class="date">4PM</div>
            </li>
            <li class="day">
                <div class="date other-month"></div>
            </li>
            <li class="day other-month">
                <div class="date"></div>
                <div class="event">
                    <div class="event-desc">

                    </div>
                    <div class="event-time">

                    </div>
                </div>
            </li>
            <li class="day other-month">
                <div class="date"></div>
            </li>
            <li class="day other-month">
                <div class="date"></div>
            </li>
            <li class="day other-month">
                <div class="date"></div>
            </li>
            <li class="day other-month">
                <div class="date"></div>
            </li>
            <li class="day">
                <div class="date"></div>
            </li>
        </ul>
        <ul class="days">
            <li class="day">
                <div class="date">5PM</div>
            </li>
            <li class="day">
                <div class="date other-month"></div>
            </li>
            <li class="day other-month">
                <div class="date"></div>
                <div class="event">
                    <div class="event-desc">

                    </div>
                    <div class="event-time">

                    </div>
                </div>
            </li>
            <li class="day other-month">
                <div class="date"></div>
            </li>
            <li class="day other-month">
                <div class="date"></div>
            </li>
            <li class="day other-month">
                <div class="date"></div>
            </li>
            <li class="day other-month">
                <div class="date"></div>
            </li>
            <li class="day">
                <div class="date"></div>
            </li>
        </ul>
      </div>
</code>```

答:
You can simply try javascript query selecter and event listener in this case.</p>

```<code><script>
  document.querySelector(".date").addEventListener("click", function() {
     // Do what you want to be onClick
     console.log("Done..");
  });
</script>
</code>```

Title: Onclick event on html calendar

Body:
I've been making a simple scheduler using html,css and js. I've not made any tables using the table tags in html but I've made the table using div tags and css. Now I want to add and onclick function on one of the cells that appear on the table. Can someone help make that function cause every time I try, a cell suddenly disappears upon refresh. Here's the source code to the calendar that I've made.

BIT

Time

Sunday

Monday

Tuesday

Wednesday

Thursday

Friday

Saturday

8AM

9AM

10AM

11AM

12PM

1PM

2PM

3PM

4PM

5PM

Body:
You can simply try javascript query selecter and event listener in this case.

<script>
  document.querySelector(".date").addEventListener("click", function() {
     // Do what you want to be onClick
     console.log("Done..");
  });
</script>


问:
How to document OData endpoints (swagger, swashbuckle, other)?
What is the best way of documenting OData endpoints?
Is there a way to use Swashbuckle for it?</p>

答:
Asp NET and Asp NET Core Api Versioning

You can use Api Versioning (as it extends ApiExplorer with Odata information) for both WebApi and AspNetCore.

There are samples available for both:

WebApi

Asp Net Core

This sample how it integrates well with Swashbuckle/Swagger ui.


问:
Check if a file exists locally using JavaScript only
I want to check if a file exists locally, where the HTML file is located. It has to be JavaScript. JavaScript will never be disabled. jQuery is not good but can do.

By the way, I am making a titanium app for Mac so I am looking for a way of protecting my files from people who click "show package contents".

答:
No need for an external library if you use Nodejs all you need to do is import the file system module. feel free to edit the code below:
    const fs = require('fs')</p>

```<code>const path = './file.txt'

fs.access(path, fs.F_OK, (err) => {
  if (err) {
    console.error(err)
    return
  }

  //file exists
})
</code>```

Body:
No need for an external library if you use Nodejs all you need to do is import the file system module. feel free to edit the code below:
    const fs = require('fs')

const path = './file.txt'

fs.access(path, fs.F_OK, (err) => {
  if (err) {
    console.error(err)
    return
  }

  //file exists
})


问:
if let editItemVC = segue.destination as? ItemDetailViewController {} doesn't work
i have two segues in this tableViewController, but the downcasting in prepare(for: segue) doesn't work.

```<code>override func prepare(for segue: UIStoryboardSegue, sender: Any?)
{
    print("into segue")
    super.prepare(for: segue, sender: sender)

    switch segue.identifier {
    case "addItem":
        print("addItem Segue")
        if let addItemVC = segue.destination as? ItemDetailViewController {
            print("if let done")
            addItemVC.container = container
        } else {
            print("WTF")
        }
    case "editItem":
        print("editItem Segue")
        if let editItemVC = segue.destination as? ItemDetailViewController {
            guard let selectedItemCell = sender as? PriorityListTVCell else {
                fatalError("Unexpected sender: \(String(describing: sender))")
            }
            guard let indexPath = tableView.indexPath(for: selectedItemCell) else {
                fatalError("The selected cell is not being displayed by the table")
            }

            editItemVC.editedInfo = list[indexPath.row]
            print("passed indexPath.row: \(indexPath.row)")
            editItemVC.container = container
        }
    default:
        break
    }
}
</code>```

if i click "add" button, in the console it'll print out

```<code>into segue
addItem Segue
WTF
</code>```

not sure why the downcasting doesn't work, does it have anything to do with segue types of destination?
Thanks for help!

答:
This

```<code>if let addItemVC = segue.destination as? ItemDetailViewController {
</code>```

won't work if the destination vc isn't of type ItemDetailViewController meaning you need to assign the class name in IB , for help you can do

```<code>print(type(of:segue.destination))
</code>```

For navigation do

```<code>if let nav = segue.destination as? UINavigationController ,
   let addItemVC = nav.viewControllers?.first as? ItemDetailViewController {}
</code>```

Body:
i have two segues in this tableViewController, but the downcasting in prepare(for: segue) doesn't work.

override func prepare(for segue: UIStoryboardSegue, sender: Any?)
{
    print("into segue")
    super.prepare(for: segue, sender: sender)

    switch segue.identifier {
    case "addItem":
        print("addItem Segue")
        if let addItemVC = segue.destination as? ItemDetailViewController {
            print("if let done")
            addItemVC.container = container
        } else {
            print("WTF")
        }
    case "editItem":
        print("editItem Segue")
        if let editItemVC = segue.destination as? ItemDetailViewController {
            guard let selectedItemCell = sender as? PriorityListTVCell else {
                fatalError("Unexpected sender: \(String(describing: sender))")
            }
            guard let indexPath = tableView.indexPath(for: selectedItemCell) else {
                fatalError("The selected cell is not being displayed by the table")
            }

            editItemVC.editedInfo = list[indexPath.row]
            print("passed indexPath.row: \(indexPath.row)")
            editItemVC.container = container
        }
    default:
        break
    }
}

if i click "add" button, in the console it'll print out

into segue
addItem Segue
WTF

not sure why the downcasting doesn't work, does it have anything to do with segue types of destination?
Thanks for help!

Body:
This

if let addItemVC = segue.destination as? ItemDetailViewController {

won't work if the destination vc isn't of type ItemDetailViewController meaning you need to assign the class name in IB , for help you can do

print(type(of:segue.destination))

For navigation do

if let nav = segue.destination as? UINavigationController ,
   let addItemVC = nav.viewControllers?.first as? ItemDetailViewController {}


问:
fading in and fading out a dropdown an unordered list
I am trying to fade in and fade out a
 on a click. I know the method I am using is wrong because it doesn't work, but also because I am pretty sure it's because I need to use $(this) instead of the current $('#innerList') but I am just not sure what I have to do.

http://jsfiddle.net/kyllle/tfZXE/

答:
Keep it simple, that's the point of JQuery:</p>

```<code>    $(document).ready(function(){
        $('#innerList').hide();
        $('.dropLink').click(function(){
            $("#innerList").fadeToggle();
        });
    });
</code>```

Body:
Keep it simple, that's the point of JQuery:

    $(document).ready(function(){
        $('#innerList').hide();
        $('.dropLink').click(function(){
            $("#innerList").fadeToggle();
        });
    });