问:
Other Ways of Singleton in Java
Just i was thinking about the other ways of writing singleton class. So is this class considered as a singleton class?

```<code>      public class MyClass{
            static Myclass myclass;

            static { myclass = new MyClass();}

            private MyClass(){}

            public static MyClass getInstance()
            {
                return myclass;
            }
       }
</code>```

as the static block run only once.

答:
Might be a little late to the game on this, but a basic implementation would look something like this:

```<code>public class MySingleton {

     private static MySingleton INSTANCE;

     public static MySingleton getInstance() {
        if (INSTANCE == null) {
            INSTANCE = new MySingleton();
        }

        return INSTANCE;
    }
    ...
}
</code>```

Here we have the MySingleton class which has a private static member called INSTANCE, and a public static method called getInstance(). The first time getInstance() is called, the INSTANCE member is null. The flow will then fall into the creation condition and create a new instance of the MySingleton class. Subsequent calls to getInstance() will find that the INSTANCE variable is already set, and therefore not create another MySingleton instance. This ensures there is only one instance of MySingleton which is shared among all callers of getInstance().

But this implementation has a problem. Multi-threaded applications will have a race condition on the creation of the single instance. If multiple threads of execution hit the getInstance() method at (or around) the same time, they will each see the INSTANCE member as null. This will result in each thread creating a new MySingleton instance and subsequently setting the INSTANCE member.

```<code>private static MySingleton INSTANCE;

public static synchronized MySingleton getInstance() {
    if (INSTANCE == null) {
        INSTANCE = new MySingleton();
    }

    return INSTANCE;
}
</code>```

Here we’ve used the synchronized keyword in the method signature to synchronize the getInstance() method. This will certainly fix our race condition. Threads will now block and enter the method one at a time. But it also creates a performance problem. Not only does this implementation synchronize the creation of the single instance, it synchronizes all calls to getInstance(), including reads. Reads do not need to be synchronized as they simply return the value of INSTANCE. Since reads will make up the bulk of our calls (remember, instantiation only happens on the first call), we will incur an unnecessary performance hit by synchronizing the entire method.

```<code>private static MySingleton INSTANCE;

public static MySingleton getInstance() {
    if (INSTANCE == null) {
        synchronize(MySingleton.class) {
            INSTANCE = new MySingleton();
        }
    }

    return INSTANCE;
}
</code>```

Here we’ve moved synchronization from the method signature, to a synchronized block that wraps the creation of the MySingleton instance. But does this solve our problem? Well, we are no longer blocking on reads, but we’ve also taken a step backward. Multiple threads will hit the getInstance() method at or around the same time and they will all see the INSTANCE member as null. They will then hit the synchronized block where one will obtain the lock and create the instance. When that thread exits the block, the other threads will contend for the lock, and one by one each thread will fall through the block and create a new instance of our class. So we are right back where we started.

```<code>private static MySingleton INSTANCE;

public static MySingleton getInstance() {
    if (INSTANCE == null) {
        synchronized(MySingleton.class) {
            if (INSTANCE == null) {
                INSTANCE = createInstance();
            }
        }
    }

    return INSTANCE;
}
</code>```

Here we issue another check from INSIDE the block. If the INSTANCE member has already been set, we’ll skip initialization. This is called double-checked locking.

This solves our problem of multiple instantiation. But once again, our solution has presented another challenge. Other threads might not “see” that the INSTANCE member has been updated. This is because of how Java optimizes memory operations. Threads copy the original values of variables from main memory into the CPU’s cache. Changes to values are then written to, and read from, that cache. This is a feature of Java designed to optimize performance. But this creates a problem for our singleton implementation. A second thread — being processed by a different CPU or core, using a different cache — will not see the changes made by the first. This will cause the second thread to see the INSTANCE member as null forcing a new instance of our singleton to be created.

```<code>private static volatile MySingleton INSTANCE;

public static MySingleton getInstance() {
    if (INSTANCE == null) {
        synchronized(MySingleton.class) {
            if (INSTANCE == null) {
                INSTANCE = createInstance();
            }
        }
    }

    return INSTANCE;
}
</code>```

We solve this by using the volatile keyword on the declaration of the INSTANCE member. This will tell the compiler to always read from, and write to, main memory, and not the CPU cache.

But this simple change comes at a cost. Because we are bypassing the CPU cache, we will take a performance hit each time we operate on the volatile INSTANCE member — which we do 4 times. We double-check existence (1 and 2), set the value (3), and then return the value (4). One could argue that this path is the fringe case as we only create the instance during the first call of the method. Perhaps a performance hit on creation is tolerable. But even our main use-case, reads, will operate on the volatile member twice. Once to check existence, and again to return its value.

```<code>private static volatile MySingleton INSTANCE;

public static MySingleton getInstance() {
    MySingleton result = INSTANCE;
    if (result == null) {
        synchronized(MySingleton.class) {
            result = INSTANCE;
            if (result == null) {
                INSTANCE = result = createInstance();
            }
        }
    }

    return result;
}
</code>```

Since the performance hit is due to operating directly on the volatile member, let’s set a local variable to the value of the volatile and operate on the local variable instead. This will decrease the number of times we operate on the volatile, thereby reclaiming some of our lost performance. Note that we have to set our local variable again when we enter the synchronized block. This ensures it is up to date with any changes that occured while we were waiting for the lock.

I wrote an article about this recently. Deconstructing The Singleton. You can find more info on these examples and an example of the "holder" pattern there. There is also a real-world example showcasing the double-checked volatile approach. Hope this helps.

ContentLicense: CC BY-SA 4.0

Title: Other Ways of Singleton in Java

Body:
Just i was thinking about the other ways of writing singleton class. So is this class considered as a singleton class?

      public class MyClass{
            static Myclass myclass;

            static { myclass = new MyClass();}

            private MyClass(){}

            public static MyClass getInstance()
            {
                return myclass;
            }
       }

as the static block run only once.

Body:
Might be a little late to the game on this, but a basic implementation would look something like this:

public class MySingleton {

     private static MySingleton INSTANCE;

     public static MySingleton getInstance() {
        if (INSTANCE == null) {
            INSTANCE = new MySingleton();
        }

        return INSTANCE;
    }
    ...
}

Here we have the MySingleton class which has a private static member called INSTANCE, and a public static method called getInstance(). The first time getInstance() is called, the INSTANCE member is null. The flow will then fall into the creation condition and create a new instance of the MySingleton class. Subsequent calls to getInstance() will find that the INSTANCE variable is already set, and therefore not create another MySingleton instance. This ensures there is only one instance of MySingleton which is shared among all callers of getInstance().

But this implementation has a problem. Multi-threaded applications will have a race condition on the creation of the single instance. If multiple threads of execution hit the getInstance() method at (or around) the same time, they will each see the INSTANCE member as null. This will result in each thread creating a new MySingleton instance and subsequently setting the INSTANCE member.

private static MySingleton INSTANCE;

public static synchronized MySingleton getInstance() {
    if (INSTANCE == null) {
        INSTANCE = new MySingleton();
    }

    return INSTANCE;
}

Here we’ve used the synchronized keyword in the method signature to synchronize the getInstance() method. This will certainly fix our race condition. Threads will now block and enter the method one at a time. But it also creates a performance problem. Not only does this implementation synchronize the creation of the single instance, it synchronizes all calls to getInstance(), including reads. Reads do not need to be synchronized as they simply return the value of INSTANCE. Since reads will make up the bulk of our calls (remember, instantiation only happens on the first call), we will incur an unnecessary performance hit by synchronizing the entire method.

private static MySingleton INSTANCE;

public static MySingleton getInstance() {
    if (INSTANCE == null) {
        synchronize(MySingleton.class) {
            INSTANCE = new MySingleton();
        }
    }

    return INSTANCE;
}

Here we’ve moved synchronization from the method signature, to a synchronized block that wraps the creation of the MySingleton instance. But does this solve our problem? Well, we are no longer blocking on reads, but we’ve also taken a step backward. Multiple threads will hit the getInstance() method at or around the same time and they will all see the INSTANCE member as null. They will then hit the synchronized block where one will obtain the lock and create the instance. When that thread exits the block, the other threads will contend for the lock, and one by one each thread will fall through the block and create a new instance of our class. So we are right back where we started.

private static MySingleton INSTANCE;

public static MySingleton getInstance() {
    if (INSTANCE == null) {
        synchronized(MySingleton.class) {
            if (INSTANCE == null) {
                INSTANCE = createInstance();
            }
        }
    }

    return INSTANCE;
}

Here we issue another check from INSIDE the block. If the INSTANCE member has already been set, we’ll skip initialization. This is called double-checked locking.

This solves our problem of multiple instantiation. But once again, our solution has presented another challenge. Other threads might not “see” that the INSTANCE member has been updated. This is because of how Java optimizes memory operations. Threads copy the original values of variables from main memory into the CPU’s cache. Changes to values are then written to, and read from, that cache. This is a feature of Java designed to optimize performance. But this creates a problem for our singleton implementation. A second thread — being processed by a different CPU or core, using a different cache — will not see the changes made by the first. This will cause the second thread to see the INSTANCE member as null forcing a new instance of our singleton to be created.

private static volatile MySingleton INSTANCE;

public static MySingleton getInstance() {
    if (INSTANCE == null) {
        synchronized(MySingleton.class) {
            if (INSTANCE == null) {
                INSTANCE = createInstance();
            }
        }
    }

    return INSTANCE;
}

We solve this by using the volatile keyword on the declaration of the INSTANCE member. This will tell the compiler to always read from, and write to, main memory, and not the CPU cache.

But this simple change comes at a cost. Because we are bypassing the CPU cache, we will take a performance hit each time we operate on the volatile INSTANCE member — which we do 4 times. We double-check existence (1 and 2), set the value (3), and then return the value (4). One could argue that this path is the fringe case as we only create the instance during the first call of the method. Perhaps a performance hit on creation is tolerable. But even our main use-case, reads, will operate on the volatile member twice. Once to check existence, and again to return its value.

private static volatile MySingleton INSTANCE;

public static MySingleton getInstance() {
    MySingleton result = INSTANCE;
    if (result == null) {
        synchronized(MySingleton.class) {
            result = INSTANCE;
            if (result == null) {
                INSTANCE = result = createInstance();
            }
        }
    }

    return result;
}

Since the performance hit is due to operating directly on the volatile member, let’s set a local variable to the value of the volatile and operate on the local variable instead. This will decrease the number of times we operate on the volatile, thereby reclaiming some of our lost performance. Note that we have to set our local variable again when we enter the synchronized block. This ensures it is up to date with any changes that occured while we were waiting for the lock.

I wrote an article about this recently. Deconstructing The Singleton. You can find more info on these examples and an example of the "holder" pattern there. There is also a real-world example showcasing the double-checked volatile approach. Hope this helps.


来源: stackexchange

问:
AWS and Django: "Couldn't import Django"
I am new programming in Django. I do a local demo and it runs without problem but the next step is deploying the Django application on AWS Elastic beanstalk, I am trying that.

I have this Enviroment:
~/Python_Env/MiEntorno

And this Project:
 ~/ProyectosDjango/Refugio

My current Django project structure is this:

```<code>requirements.txt
.ebextensions
    |-01-django_env.config
.elasticbeanstalk
    |-config.yml
.gitignore
custom_storage.py
manage.py
Refugio
   |__init__.py
   |-settings
   |-urls.py
   |-wsgi.py
|-apps
|-templates
|-static
</code>```

I have this error when i execute this command: (Mi Entorno) /ProyectosDjango/Refugio> manage.py collectstatic or manage.py runserver

"Couldn't import Django. Are you sure it's installed and available on
  your PYTHONPATH environment variable? Did you forget to activate a
  virtual environment?"

I put this in my -01-django_env.config:

```<code>option_settings:
    "aws:elasticbeanstalk:application:environment":
    DJANGO_SETTINGS_MODULE: "Refugio.settings"
    PYTHONPATH: "/opt/python/current/app/Refugio:$PYTHONPATH"
    "aws:elasticbeanstalk:container:python"
    WSGIPath: "Refugio/Refugio/wsgi.py"
</code>```

and in setting I edit the database and add this:

```<code>STATICFILES_LOCATION = 'static'
MEDIAFILES_LOCATION = 'media'

AWS_STORAGE_BUCKET_NAME = 's3.refugioprueba.com'
AWS_ACCESS_KEY_ID = 'xxx'
AWS_SECRET_ACCESS_KEY = 'yy/xxx/'

STATICFILES_STORAGE = 'custom_storages.StaticStorage'
DEFAULT_FILE_STORAGE = 'custom_storages.MediaStorage'
AWS_S3_CUSTOM_DOMAIN = '%s.s3-us-west-1.amazonaws.com' % AWS_STORAGE_BUCKET_NAME
AWS_S3_SECURE_URLS = False

from boto.s3.connection import ProtocolIndependentOrdinaryCallingFormat
AWS_S3_CALLING_FORMAT = ProtocolIndependentOrdinaryCallingFormat
from boto.s3.connection import S3Connection
S3Connection.DefaultHost = 's3.us.west-1.amazonaws.com'

STATIC_URL = "http://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, STATICFILES_LOCATION)
MEDIA_URL = "http://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, MEDIAFILES_LOCATION )

WSGI_APPLICATION = 'Refugio.wsgi.application'

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'ebdb',
        'USER': 'root',
        'PASSWORD': 'XXX',
        'HOST': 'XXXrds.amazonaws.com',
        'PORT': 3306,
    }
}
</code>```

答:
Are you sure it's installed in the environment? As in pip install django (or whichever specific version you are using)? Or alternatively pip install -r requirements.txt if it's in your requirements.txt file?
EBS usually automatically installs requirements.txt dependencies so placing it there is the safest

ContentLicense: CC BY-SA 3.0

Body:
I am new programming in Django. I do a local demo and it runs without problem but the next step is deploying the Django application on AWS Elastic beanstalk, I am trying that.

I have this Enviroment:
~/Python_Env/MiEntorno

And this Project:
 ~/ProyectosDjango/Refugio

My current Django project structure is this:

requirements.txt
.ebextensions
    |-01-django_env.config
.elasticbeanstalk
    |-config.yml
.gitignore
custom_storage.py
manage.py
Refugio
   |__init__.py
   |-settings
   |-urls.py
   |-wsgi.py
|-apps
|-templates
|-static

I have this error when i execute this command: (Mi Entorno) /ProyectosDjango/Refugio> manage.py collectstatic or manage.py runserver

"Couldn't import Django. Are you sure it's installed and available on
  your PYTHONPATH environment variable? Did you forget to activate a
  virtual environment?"

I put this in my -01-django_env.config:

option_settings:
    "aws:elasticbeanstalk:application:environment":
    DJANGO_SETTINGS_MODULE: "Refugio.settings"
    PYTHONPATH: "/opt/python/current/app/Refugio:$PYTHONPATH"
    "aws:elasticbeanstalk:container:python"
    WSGIPath: "Refugio/Refugio/wsgi.py"

and in setting I edit the database and add this:

STATICFILES_LOCATION = 'static'
MEDIAFILES_LOCATION = 'media'

AWS_STORAGE_BUCKET_NAME = 's3.refugioprueba.com'
AWS_ACCESS_KEY_ID = 'xxx'
AWS_SECRET_ACCESS_KEY = 'yy/xxx/'

STATICFILES_STORAGE = 'custom_storages.StaticStorage'
DEFAULT_FILE_STORAGE = 'custom_storages.MediaStorage'
AWS_S3_CUSTOM_DOMAIN = '%s.s3-us-west-1.amazonaws.com' % AWS_STORAGE_BUCKET_NAME
AWS_S3_SECURE_URLS = False

from boto.s3.connection import ProtocolIndependentOrdinaryCallingFormat
AWS_S3_CALLING_FORMAT = ProtocolIndependentOrdinaryCallingFormat
from boto.s3.connection import S3Connection
S3Connection.DefaultHost = 's3.us.west-1.amazonaws.com'

STATIC_URL = "http://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, STATICFILES_LOCATION)
MEDIA_URL = "http://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, MEDIAFILES_LOCATION )

WSGI_APPLICATION = 'Refugio.wsgi.application'

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'ebdb',
        'USER': 'root',
        'PASSWORD': 'XXX',
        'HOST': 'XXXrds.amazonaws.com',
        'PORT': 3306,
    }
}


问:
Choosing between Windows Process Activation Services (WAS) and IIS 7
I am writing a WCF service which will run on a server computer (Windows 10 OS). To host that service, I am considering WAS and IIS 7. I know earlier versions of IIS only support HTTP protocol, but IIS 7 and later support TCP/IP too.

My WCF service will be consumed by desktop/mobile WCF client for now, so I am planning to use only TCP/IP for now. But it might be expanded to include HTTP in the future to support Web.

Please advice which host I should use - WAS or IIS?

答:
You need both.

From the documentation (https://technet.microsoft.com/en-us/library/cc735229(v=ws.10).aspx):

Windows Process Activation Service (WAS) manages application pool configuration and the creation and lifetime of worker processes for HTTP and other protocols. The World Wide Web Publishing Service (W3SVC) and other services depend on WAS.

You have to install the needed activations (Programs and Features | Turn windows features on and off | .Net framework advanced services | WCF services), create a service, host it in IIS, configure WCF and configure bindings in the IIS.
You can configure bindings using IIS management (on the top right side of the IIS Manager, under Edit Site | Bindings...) or a command line tool, like this:

```<code>%windir%\system32\inetsrv\appcmd.exe set site "Default Web Site" -+bindings.[protocol='net.tcp',bindingInformation='808:*']
</code>```

Command line sample and more information here:

https://learn.microsoft.com/en-us/dotnet/framework/wcf/feature-details/how-to-install-and-configure-wcf-activation-components

and here:

https://learn.microsoft.com/en-us/dotnet/framework/wcf/feature-details/how-to-host-a-wcf-service-in-was

Body:
You need both.

From the documentation (https://technet.microsoft.com/en-us/library/cc735229(v=ws.10).aspx):

Windows Process Activation Service (WAS) manages application pool configuration and the creation and lifetime of worker processes for HTTP and other protocols. The World Wide Web Publishing Service (W3SVC) and other services depend on WAS.

You have to install the needed activations (Programs and Features | Turn windows features on and off | .Net framework advanced services | WCF services), create a service, host it in IIS, configure WCF and configure bindings in the IIS.
You can configure bindings using IIS management (on the top right side of the IIS Manager, under Edit Site | Bindings...) or a command line tool, like this:

%windir%\system32\inetsrv\appcmd.exe set site "Default Web Site" -+bindings.[protocol='net.tcp',bindingInformation='808:*']

Command line sample and more information here:

https://learn.microsoft.com/en-us/dotnet/framework/wcf/feature-details/how-to-install-and-configure-wcf-activation-components

and here:

https://learn.microsoft.com/en-us/dotnet/framework/wcf/feature-details/how-to-host-a-wcf-service-in-was


问:
Unknown External Data Source type - in Always Encrypted
I've Created my self-signed Certificate in my local and uploaded in the Azure Key Vault.So that i can use it for my always Encrypted (column Encryption in Azure SQL DB)

Initally I experienced with Purge issue and solved it here

Proceeding further I get the Error While Performing my Encrypted Operations

This is my Log file

```<code>Jul 6 2017 16:01:16: Log opened. TraceLevel:Informational
Jul 6 2017 16:01:37 [Informational] WizardSummary: Message:Source database settings.

Jul 6 2017 16:01:37 [Informational] WizardSummary: Message: Source server name: xxx.database.windows.net.

Jul 6 2017 16:01:37 [Informational] WizardSummary: Message: Source database name: db.

Jul 6 2017 16:01:37 [Informational] WizardSummary: Message:Create new encryption key.

Jul 6 2017 16:01:37 [Informational] WizardSummary: Message: New encryption key: CEK_Auto1.

Jul 6 2017 16:01:37 [Informational] WizardSummary: Message:Encrypt column blobname.

Jul 6 2017 16:01:37 [Informational] WizardSummary: Message:   Table name: filenames.

Jul 6 2017 16:01:37 [Informational] WizardSummary: Message:   Encryption key name: CEK_Auto1.

Jul 6 2017 16:01:37 [Informational] WizardSummary: Message:   Encryption type: Deterministic.

Jul 6 2017 16:01:38 [Informational] WorkitemExecution: Message:Work item 'Generate new column encryption key CEK_Auto1' started..

Jul 6 2017 16:01:38 [Informational] TaskUpdates: Message:Task: 'Generate new column encryption key CEK_Auto1' -- Status: 'Started' -- Details: 'Task 'Generate new column encryption key CEK_Auto1' started ....'.

Jul 6 2017 16:01:40 [Informational] TaskUpdates: Message:Task: 'Generate new column encryption key CEK_Auto1' -- Status: 'Completed' -- Details: 'Task 'Generate new column encryption key CEK_Auto1' completed'.

Jul 6 2017 16:01:40 [Informational] WorkitemExecution: Message:Work item 'Generate new column encryption key CEK_Auto1' stopped..

Jul 6 2017 16:01:40 [Informational] WorkitemExecution: Message:Work item 'Generate new column encryption key CEK_Auto1' completed successfully!.

Jul 6 2017 16:01:40 [Informational] WorkitemExecution: Message:Work item 'Performing encryption operations' started..

Jul 6 2017 16:01:40 [Informational] TaskUpdates: Message:Task: 'Performing encryption operations' -- Status: 'Started' -- Details: 'Task 'Performing encryption operations' started ....'.

Jul 6 2017 16:02:15 [Informational] TaskUpdates: Message:Task: 'Performing encryption operations' -- Status: 'Failed' -- Details: 'Task failed due to following error: Unknown external data source type'.

Jul 6 2017 16:02:15 [Informational] WorkitemExecution: Message:Work item 'Performing encryption operations' stopped..

Jul 6 2017 16:02:15 [Error] WorkitemExecution: Message:Work item 'Performing encryption operations' did not complete. Details: Unknown external data source type.

Jul 6 2017 16:02:15 [Informational] Log Closed: Message:Job processing completed.
</code>```

The main error is unknown External Data Source Type

UPDATE

I can able to overcome this error with my other Azure DB which was Standard Pricing Tier

答:
Did you register the Azure Key Vault provider? Did you configure the Master Key?
Please read the following article:

https://learn.microsoft.com/en-us/azure/sql-database/sql-database-always-encrypted-azure-key-vault

Hope this helps.

Regards,

Alberto Morillo

Body:
I've Created my self-signed Certificate in my local and uploaded in the Azure Key Vault.So that i can use it for my always Encrypted (column Encryption in Azure SQL DB)

Initally I experienced with Purge issue and solved it here

Proceeding further I get the Error While Performing my Encrypted Operations

This is my Log file

Jul 6 2017 16:01:16: Log opened. TraceLevel:Informational
Jul 6 2017 16:01:37 [Informational] WizardSummary: Message:Source database settings.

Jul 6 2017 16:01:37 [Informational] WizardSummary: Message: Source server name: xxx.database.windows.net.

Jul 6 2017 16:01:37 [Informational] WizardSummary: Message: Source database name: db.

Jul 6 2017 16:01:37 [Informational] WizardSummary: Message:Create new encryption key.

Jul 6 2017 16:01:37 [Informational] WizardSummary: Message: New encryption key: CEK_Auto1.

Jul 6 2017 16:01:37 [Informational] WizardSummary: Message:Encrypt column blobname.

Jul 6 2017 16:01:37 [Informational] WizardSummary: Message:   Table name: filenames.

Jul 6 2017 16:01:37 [Informational] WizardSummary: Message:   Encryption key name: CEK_Auto1.

Jul 6 2017 16:01:37 [Informational] WizardSummary: Message:   Encryption type: Deterministic.

Jul 6 2017 16:01:38 [Informational] WorkitemExecution: Message:Work item 'Generate new column encryption key CEK_Auto1' started..

Jul 6 2017 16:01:38 [Informational] TaskUpdates: Message:Task: 'Generate new column encryption key CEK_Auto1' -- Status: 'Started' -- Details: 'Task 'Generate new column encryption key CEK_Auto1' started ....'.

Jul 6 2017 16:01:40 [Informational] TaskUpdates: Message:Task: 'Generate new column encryption key CEK_Auto1' -- Status: 'Completed' -- Details: 'Task 'Generate new column encryption key CEK_Auto1' completed'.

Jul 6 2017 16:01:40 [Informational] WorkitemExecution: Message:Work item 'Generate new column encryption key CEK_Auto1' stopped..

Jul 6 2017 16:01:40 [Informational] WorkitemExecution: Message:Work item 'Generate new column encryption key CEK_Auto1' completed successfully!.

Jul 6 2017 16:01:40 [Informational] WorkitemExecution: Message:Work item 'Performing encryption operations' started..

Jul 6 2017 16:01:40 [Informational] TaskUpdates: Message:Task: 'Performing encryption operations' -- Status: 'Started' -- Details: 'Task 'Performing encryption operations' started ....'.

Jul 6 2017 16:02:15 [Informational] TaskUpdates: Message:Task: 'Performing encryption operations' -- Status: 'Failed' -- Details: 'Task failed due to following error: Unknown external data source type'.

Jul 6 2017 16:02:15 [Informational] WorkitemExecution: Message:Work item 'Performing encryption operations' stopped..

Jul 6 2017 16:02:15 [Error] WorkitemExecution: Message:Work item 'Performing encryption operations' did not complete. Details: Unknown external data source type.

Jul 6 2017 16:02:15 [Informational] Log Closed: Message:Job processing completed.

The main error is unknown External Data Source Type

UPDATE

I can able to overcome this error with my other Azure DB which was Standard Pricing Tier


问:
Laravel Query Builder - how to format the query using joins
I know this is a poorly written query. How can I re-write this using the Laravel Query builder?</p>

```<code>SELECT tgi.rate, tgi.tax_types_id, tt.name, tt.sales_chart_master_id, tt.purchase_chart_master_id
FROM tax_group_items tgi, tax_types tt
WHERE tgi.tax_groups_id = (SELECT tax_groups_id FROM customers WHERE id=2)
AND tt.id = tgi.tax_types_id
AND tt.id NOT IN (SELECT tax_types_id FROM item_tax_type_exemptions WHERE item_tax_types_id = (SELECT item_tax_types_id FROM products WHERE id = 1))
</code>```

答:
```<code>DB::table(DB::raw('tax_group_items tgi, tax_types tt'))
    ->select(['tgi.rate', 'tgi.tax_types_id', 'tt.name', 'tt.sales_chart_master_id', 'tt.purchase_chart_master_id'])
    ->whereRaw('tgi.tax_groups_id = (SELECT tax_groups_id FROM customers WHERE id=2)')
    ->where('tt.id', 'tgi.tax_types_id')
    ->whereRaw('tt.id NOT IN (SELECT tax_types_id FROM item_tax_type_exemptions WHERE item_tax_types_id = (SELECT item_tax_types_id FROM products WHERE id = 1))')
    ->get();
</code>```

Body:
I know this is a poorly written query. How can I re-write this using the Laravel Query builder?

SELECT tgi.rate, tgi.tax_types_id, tt.name, tt.sales_chart_master_id, tt.purchase_chart_master_id
FROM tax_group_items tgi, tax_types tt
WHERE tgi.tax_groups_id = (SELECT tax_groups_id FROM customers WHERE id=2)
AND tt.id = tgi.tax_types_id
AND tt.id NOT IN (SELECT tax_types_id FROM item_tax_type_exemptions WHERE item_tax_types_id = (SELECT item_tax_types_id FROM products WHERE id = 1))


问:
Override Users Form Sonata UserBundle
Hello I tried to follow the explanation given here:

How to remove fields from the admin user create page of Sonata User Bundle?

To add / remove lines to the Sonata Userbundle registration form but the problem is that I find myself for this error:

Here are the few lines of code that I put:
in src/Application/Sonata/userBundle/Admin/UserAdmin.php

```<code>use Sonata\UserBundle\Admin\Model\UserAdmin as BaseUserAdmin;
use Sonata\AdminBundle\Form\FormMapper;
class UserAdmin extends BaseUserAdmin {
    protected function configureFormFields( FormMapper $formMapper ) {
        parent::configureFormFields($formMapper);
        $formMapper
            ->remove('facebookUid');
    }
}
</code>```

In
app/config/config.php :

```<code>sonata_user:
    security_acl: true
    manager_type: orm
    admin:                  # Admin Classes
            user:
                class:          Application\Sonata\UserBundle\Admin\UserAdmin
                controller:     SonataAdminBundle:CRUD
</code>```

Can someone tell me why? Thank you

答:
You have forgotten to declare the namespace of your UserAdmin class.
It has to be the very first line of code, and will be like that in your case:</p>

```<code><?php
namespace UserBundle\Admin;

use Sonata\UserBundle\Admin\Model\UserAdmin as BaseUserAdmin;
use Sonata\AdminBundle\Form\FormMapper;

class UserAdmin extends BaseUserAdmin {
</code>```

Title: Override Users Form Sonata UserBundle

Body:
Hello I tried to follow the explanation given here:

How to remove fields from the admin user create page of Sonata User Bundle?

To add / remove lines to the Sonata Userbundle registration form but the problem is that I find myself for this error:

Here are the few lines of code that I put:
in src/Application/Sonata/userBundle/Admin/UserAdmin.php

use Sonata\UserBundle\Admin\Model\UserAdmin as BaseUserAdmin;
use Sonata\AdminBundle\Form\FormMapper;
class UserAdmin extends BaseUserAdmin {
    protected function configureFormFields( FormMapper $formMapper ) {
        parent::configureFormFields($formMapper);
        $formMapper
            ->remove('facebookUid');
    }
}

In
app/config/config.php :

sonata_user:
    security_acl: true
    manager_type: orm
    admin:                  # Admin Classes
            user:
                class:          Application\Sonata\UserBundle\Admin\UserAdmin
                controller:     SonataAdminBundle:CRUD

Can someone tell me why? Thank you

Body:
You have forgotten to declare the namespace of your UserAdmin class.
It has to be the very first line of code, and will be like that in your case:

<?php
namespace UserBundle\Admin;

use Sonata\UserBundle\Admin\Model\UserAdmin as BaseUserAdmin;
use Sonata\AdminBundle\Form\FormMapper;

class UserAdmin extends BaseUserAdmin {


问:
How to rewrite SQL joins into window functions?
Database is HP Vertica 7 or PostgreSQL 9.

```<code>create table test (
id int,
card_id int,
tran_dt date,
amount int
);

insert into test values (1, 1, '2017-07-06', 10);
insert into test values (2, 1, '2017-06-01', 20);
insert into test values (3, 1, '2017-05-01', 30);
insert into test values (4, 1, '2017-04-01', 40);
insert into test values (5, 2, '2017-07-04', 10);
</code>```

Of the payment cards used in the last 1 day, what is the maximum amount charged on that card in the last 90 days.

```<code>select t.card_id, max(t2.amount) max
from test t
join test t2 on t2.card_id=t.card_id and t2.tran_dt>='2017-04-06'
where t.tran_dt>='2017-07-06'
group by t.card_id
order by t.card_id;
</code>```

Results are correct

```<code>card_id    max
-------    ---
1          30
</code>```

I want to rewrite the query into sql window functions.

```<code>select card_id, max(amount) over(partition by card_id order by tran_dt range between '60 days' preceding and current row) max
from test
where card_id in (select card_id from test where tran_dt>='2017-07-06')
order by card_id;
</code>```

But result set does not match, how can this be done?

Test data here:
http://sqlfiddle.com/#!17/db317/1

答:
I can't try PostgreSQL, but in Vertica, you can apply the ANSI standard OLAP window function.

But you'll need to nest two queries: The window function only returns sensible results if it has all rows that need to be evaluated in the result set.

But you only want the row from '2017-07-06' to be displayed.

So you'll have to filter for that date in an outer query:

```<code>WITH olap_output AS (
  SELECT
    card_id
  , tran_dt
  , MAX(amount) OVER (
      PARTITION BY card_id
      ORDER BY tran_dt
      RANGE BETWEEN '90 DAYS' PRECEDING AND CURRENT ROW
    ) AS the_max
  FROM test
)
SELECT
  card_id
, the_max
FROM olap_output
WHERE tran_dt='2017-07-06'
;

card_id|the_max
      1|     30
</code>```

Body:
Database is HP Vertica 7 or PostgreSQL 9.

create table test (
id int,
card_id int,
tran_dt date,
amount int
);

insert into test values (1, 1, '2017-07-06', 10);
insert into test values (2, 1, '2017-06-01', 20);
insert into test values (3, 1, '2017-05-01', 30);
insert into test values (4, 1, '2017-04-01', 40);
insert into test values (5, 2, '2017-07-04', 10);

Of the payment cards used in the last 1 day, what is the maximum amount charged on that card in the last 90 days.

select t.card_id, max(t2.amount) max
from test t
join test t2 on t2.card_id=t.card_id and t2.tran_dt>='2017-04-06'
where t.tran_dt>='2017-07-06'
group by t.card_id
order by t.card_id;

Results are correct

card_id    max
-------    ---
1          30

I want to rewrite the query into sql window functions.

select card_id, max(amount) over(partition by card_id order by tran_dt range between '60 days' preceding and current row) max
from test
where card_id in (select card_id from test where tran_dt>='2017-07-06')
order by card_id;

But result set does not match, how can this be done?

Test data here:
http://sqlfiddle.com/#!17/db317/1

Body:
I can't try PostgreSQL, but in Vertica, you can apply the ANSI standard OLAP window function.

But you'll need to nest two queries: The window function only returns sensible results if it has all rows that need to be evaluated in the result set.

But you only want the row from '2017-07-06' to be displayed.

So you'll have to filter for that date in an outer query:

WITH olap_output AS (
  SELECT
    card_id
  , tran_dt
  , MAX(amount) OVER (
      PARTITION BY card_id
      ORDER BY tran_dt
      RANGE BETWEEN '90 DAYS' PRECEDING AND CURRENT ROW
    ) AS the_max
  FROM test
)
SELECT
  card_id
, the_max
FROM olap_output
WHERE tran_dt='2017-07-06'
;

card_id|the_max
      1|     30


问:
Can't make PTRACE_SEIZED(ptrace request) work
I'm playing with ptrace and trying to get register system calls value(orig_rax) of my process, I have no problem doing it with PTRACE_TRACEME request(tracer/tracee), then I tried with PTRACE_ATTACH(attach the process at runtime) and got no problem, but now I try with PTRACE_SEIZED and I have some problem to get those system call, I just cannot parse properly my process.

I know that the difference between PTRACE_ATTACH and PTRACE_SEIZED are that with seized I need to stop myself the process(I use PTRACE_INTERRUPT for that).

Below is my code: all printf and if (i == 3) break; after the while(1) are for debug purpose.

So what I'm simply trying to do is to parse my program by attaching my process with PTRACE_SEIZED request (from ptrace function) and extract all system calls(orig_rax register) done (more particularly isolate those done with my execl function,which call /bin/ls, in my main).

When I run my code all ptrace_function return 0 and the process received well the stopping signal(WIFSTOPPED(status) == true), but rip register seem not to change (sometimes it change and I get some correct orig_rax value only once and after nothing I get always the same value)

I also tried with PTRACE_SINGLESTEP instead of PTRACE_SYSCALL, and it worked only once in my while(1), after RIP is always the same value.

(I did some research on google and found no example of process parsing with PTRACE_SEIZED, i'm a begginer with ptrace, kernel, signal stuff, so maybe my miscomprehension come from here).

Any help, examples, helpful links are appreciated. I hope I'm clear enough.

Thanks.

```<code>#include <sys/ptrace.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/user.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

int             seized_process(pid_t pid)
{
        int                                             status;
        struct user_regs_struct regs;
        int                                             pt_ret;
        siginfo_t                               siginfo;
        int                                     i = 0;

        pt_ret = ptrace(PTRACE_SEIZE, pid, NULL, NULL);
        printf("PTRACE_SEIZE ret: %d\n", pt_ret);
        printf("parent :%d \n", pid);

        while (1) {
                if (i == 3)
                        break;
                pt_ret = ptrace(PTRACE_INTERRUPT, pid, NULL, NULL);
                printf("PTRACE_INTERRUPT ret: %d\n", pt_ret);
                waitpid(pid, &status, 0);
                printf("waitpid status: %d\n", status);
                if (WIFSTOPPED(status))
                        printf("process received stopping signal(Group-stop)\n");

                pt_ret = ptrace(PTRACE_GETSIGINFO, pid, NULL, &siginfo);
                printf("PTRACE_SIGINFO ret: %d, sig num: %d, si_code: %d \n",
                                pt_ret, siginfo.si_signo, siginfo.si_code);
                pt_ret = ptrace(PTRACE_GETREGS, pid, NULL, &regs);
                printf("PTRACE_GETREGS ret: %d rip %#llx, orig_rax: %#llx,"
                           " rax : %#llx\n", pt_ret, regs.rip, regs.orig_rax,
                           regs.rax);

                pt_ret = ptrace(PTRACE_SYSCALL, pid, NULL,
                                WSTOPSIG(status));
                printf("PTRACE_SYSCALL ret : %d\n", pt_ret);

                if (WIFEXITED(status)) {
                        printf("WIFEXITED(status)\n");
                        break ;
                }
                else if (WSTOPSIG(status)) {
                        printf("WSTOPSIG(status)\n");
                }
                printf("\n---------------------\n");
                i++;
        }
        ptrace(PTRACE_DETACH, pid, NULL, NULL);
}

int main(int argc, char *argv[])
{
        pid_t   child;

        child = fork();
        printf("fork value: %d \n", child);
        if (child == 0) {
                printf("child\n");
                execl("/bin/ls", "ls", NULL);
        }
        else {
                seized_process(child);
        }
    return 0;
}
</code>```

答:
From the ptrace man page ...

Under the section for PTRACE_SEIZE, we have:

Unlike PTRACE_ATTACH, PTRACE_SEIZE does not   stop   the   process.

Under the PTRACE_TRACEME, we have:

For requests other than PTRACE_ATTACH, PTRACE_SEIZE, PTRACE_INTERRUPT, and PTRACE_KILL, the tracee must be stopped.

So, for the tracer to be able to examine the tracee's registers, etc. the tracee must be stopped. But, PTRACE_SEIZE [by itself] doesn't do that.

So, you'd need to use PTRACE_ATTACH or do something else in addition to PTRACE_SEIZE to stop the process before trying to examine its registers or memory.

When you think about it, there isn't much value to getting a snapshot of a process that is running because you'd wouldn't get an atomic view of it. You'd be "racing" against it [just like two threads racing on a global value]. That is, (e.g.) you grab eax, then memory, but they might have already changed values between the ptrace calls.

UPDATE:

I know i have to stop my process(tracee), that's why i use: pt_ret = ptrace(PTRACE_INTERRUPT, pid, NULL, NULL);

In your loop, you do PTRACE_INTERRUPT to stop the process. Then, you grab the data, print it, and loop.

But, in your loop, you never do anything to resume the tracee (e.g. PTRACE_CONT), so once the first iteration of your loop is done, the traced process remains stopped. It only resumes after you exit your loop and do the PTRACE_DETACH.

UPDATE #2:

Yes. PTRACE_SYSCALL will resume the traced process. But, the tracer's ptrace call will return immediately. Then, at the loop top, you do another PTRACE_INTERRUPT.

This means that the traced process will be scheduled to run, but might get stopped [again] before it gets the chance to run. (i.e. the tracer and tracee are "racing"). This is probably close to what you're seeing.

Also, I'd increase the number of iterations in the tracer as 3 is a bit small to see much.

Try doing the PTRACE_INTERRUPT before the loop. This makes PTRACE_SEIZE followed by PTRACE_INTERRUPT the moral equivalent of PTRACE_ATTACH.

Then, the loop of: waitpid, print, PTRACE_SYSCALL should work without racing. Having PTRACE_INTERRUPT in the same loop as PTRACE_SYSCALL [sort of] defeats the purpose of PTRACE_SYSCALL.

Using PTRACE_INTERRUPT [after the initial one] only makes sense if you do PTRACE_CONT.

However, when doing PTRACE_SYSCALL, it might make sense to loop on the waitpid with WNOHANG. If you don't get a stop within a reasonable amount of time, that means the target isn't doing any syscalls. At that point, you might issue the PTRACE_INTERRUPT then, to force the stop so you can examine state.

With PTRACE_INTERRUPT above the loop, try PTRACE_SINGLESTEP to reduce the granularity.

ls is a bit opaque as far as single stepping goes (e.g. you'd probably have to install the debuginfo package to get a symbol table).

Try writing a simple target/tracee program where you precisely control the behavior. You can generate a full disassembly of it. And, then match the addresses against the rip values you get back from single step tracing.

Body:
I'm playing with ptrace and trying to get register system calls value(orig_rax) of my process, I have no problem doing it with PTRACE_TRACEME request(tracer/tracee), then I tried with PTRACE_ATTACH(attach the process at runtime) and got no problem, but now I try with PTRACE_SEIZED and I have some problem to get those system call, I just cannot parse properly my process.

I know that the difference between PTRACE_ATTACH and PTRACE_SEIZED are that with seized I need to stop myself the process(I use PTRACE_INTERRUPT for that).

Below is my code: all printf and if (i == 3) break; after the while(1) are for debug purpose.

So what I'm simply trying to do is to parse my program by attaching my process with PTRACE_SEIZED request (from ptrace function) and extract all system calls(orig_rax register) done (more particularly isolate those done with my execl function,which call /bin/ls, in my main).

When I run my code all ptrace_function return 0 and the process received well the stopping signal(WIFSTOPPED(status) == true), but rip register seem not to change (sometimes it change and I get some correct orig_rax value only once and after nothing I get always the same value)

I also tried with PTRACE_SINGLESTEP instead of PTRACE_SYSCALL, and it worked only once in my while(1), after RIP is always the same value.

(I did some research on google and found no example of process parsing with PTRACE_SEIZED, i'm a begginer with ptrace, kernel, signal stuff, so maybe my miscomprehension come from here).

Any help, examples, helpful links are appreciated. I hope I'm clear enough.

Thanks.

#include <sys/ptrace.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/user.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

int             seized_process(pid_t pid)
{
        int                                             status;
        struct user_regs_struct regs;
        int                                             pt_ret;
        siginfo_t                               siginfo;
        int                                     i = 0;

        pt_ret = ptrace(PTRACE_SEIZE, pid, NULL, NULL);
        printf("PTRACE_SEIZE ret: %d\n", pt_ret);
        printf("parent :%d \n", pid);

        while (1) {
                if (i == 3)
                        break;
                pt_ret = ptrace(PTRACE_INTERRUPT, pid, NULL, NULL);
                printf("PTRACE_INTERRUPT ret: %d\n", pt_ret);
                waitpid(pid, &status, 0);
                printf("waitpid status: %d\n", status);
                if (WIFSTOPPED(status))
                        printf("process received stopping signal(Group-stop)\n");

                pt_ret = ptrace(PTRACE_GETSIGINFO, pid, NULL, &siginfo);
                printf("PTRACE_SIGINFO ret: %d, sig num: %d, si_code: %d \n",
                                pt_ret, siginfo.si_signo, siginfo.si_code);
                pt_ret = ptrace(PTRACE_GETREGS, pid, NULL, &regs);
                printf("PTRACE_GETREGS ret: %d rip %#llx, orig_rax: %#llx,"
                           " rax : %#llx\n", pt_ret, regs.rip, regs.orig_rax,
                           regs.rax);

                pt_ret = ptrace(PTRACE_SYSCALL, pid, NULL,
                                WSTOPSIG(status));
                printf("PTRACE_SYSCALL ret : %d\n", pt_ret);

                if (WIFEXITED(status)) {
                        printf("WIFEXITED(status)\n");
                        break ;
                }
                else if (WSTOPSIG(status)) {
                        printf("WSTOPSIG(status)\n");
                }
                printf("\n---------------------\n");
                i++;
        }
        ptrace(PTRACE_DETACH, pid, NULL, NULL);
}

int main(int argc, char *argv[])
{
        pid_t   child;

        child = fork();
        printf("fork value: %d \n", child);
        if (child == 0) {
                printf("child\n");
                execl("/bin/ls", "ls", NULL);
        }
        else {
                seized_process(child);
        }
    return 0;
}


问:
How to search this pattern in vim?
```<code>/'text': '.+'
</code>```

In VIM, I want to match up to 'abc' and 'a' from 'text' in two cases:

```<code>'text': 'abc', 'url': 'http...'
'text': 'a', 'title': 'dog'
</code>```

I want to match at least one character in the single quote after the colon. This doesn't seem to work.

I got it. This worked!

```<code>/'brand': '[^']\+'
</code>```

答:
The reason this isn't working is because the + atom must be escaped to have a special meaning in vim's flavor of regex. Right now this means anything followed by a literal plus. But when escaped, it means at least one, but as many as possible. So you'd want this:

```<code>/'text': '.\+'
</code>```

However, this creates a new problem. The .+ will match as many characters as possible, including the single quotes. So it ends up matching

```<code>abc', 'url': 'http...'
</code>```

Instead of

```<code>abc'
</code>```

So you want to use the non-greedy equivalent of + which is \{-1,}. Try this:

```<code>/'text': '.\{-1,}'
</code>```

Of course, you could also turn on the magic option and do this:

```<code>/\v'text': '.{-1,}'
</code>```

A nice overview on vim regex can be found at vimregex.com. I use it all the time.

Title: How to search this pattern in vim?

Body:
/'text': '.+'

In VIM, I want to match up to 'abc' and 'a' from 'text' in two cases:

'text': 'abc', 'url': 'http...'
'text': 'a', 'title': 'dog'

I want to match at least one character in the single quote after the colon. This doesn't seem to work.

I got it. This worked!

/'brand': '[^']\+'

Body:
The reason this isn't working is because the + atom must be escaped to have a special meaning in vim's flavor of regex. Right now this means anything followed by a literal plus. But when escaped, it means at least one, but as many as possible. So you'd want this:

/'text': '.\+'

However, this creates a new problem. The .+ will match as many characters as possible, including the single quotes. So it ends up matching

abc', 'url': 'http...'

Instead of

abc'

So you want to use the non-greedy equivalent of + which is \{-1,}. Try this:

/'text': '.\{-1,}'

Of course, you could also turn on the magic option and do this:

/\v'text': '.{-1,}'

A nice overview on vim regex can be found at vimregex.com. I use it all the time.


问:
Rails Active Model Serializer - Adding nested attributes to 2nd level model
I have three models namely Invoice, InvoiceDetail and Product.
An Invoice has many InvoiceDetails and an InvoiceDetails belongs to Invoice and Product

I have serializers defined for all the three models respectively but when I'm fetch invoice, I'm not able to fetch Product attributes.

Invoice Model :

```<code> class Invoice < ApplicationRecord
  has_many :invoiceDetails, inverse_of: :invoice
  belongs_to :customer
  accepts_nested_attributes_for :invoiceDetails
end
</code>```

InvoiceDetai Model

```<code> class InvoiceDetail < ApplicationRecord
  belongs_to :invoice
  belongs_to :product
end
</code>```

Product Model

```<code>class Product < ApplicationRecord
  belongs_to :company
  belongs_to :category
  belongs_to :user
end
</code>```

Serializers

```<code>    class InvoiceSerializer < ActiveModel::Serializer
  attributes :id, :total_amount, :balance_amount, :created_at
  belongs_to :customer
  has_many :invoiceDetails
end

class InvoiceDetailSerializer < ActiveModel::Serializer
  attributes :id, :quantity, :discount, :subtotal
  belongs_to :product
end

class ProductSerializer < ActiveModel::Serializer
  attributes :id, :name, :mrp, :sp, :cp, :stocks, :isPublished
  has_one :category
end
</code>```

When I fetch an Invoice :
The JSON output does not include product attributes.

```<code>[
    {
        "id": 3,
        "total_amount": 450,
        "balance_amount": 350,
        "created_at": "2017-06-27T17:02:20.000Z",
        "customer": {
            "id": 4,
            "company_id": 1,
            "name": "vivek",
            "isActive": true,
            "created_at": "2017-06-27T14:35:50.000Z",
            "updated_at": "2017-06-27T14:35:50.000Z",
            "mobile": 12345678,
            "address": "test",
            "pan_number": null,
            "tin_number": null,
            "party_name": "xyz"
        },
        "invoiceDetails": [
            {
                "id": 4,
                "quantity": 1,
                "discount": 0,
                "subtotal": 150
            },
            {
                "id": 5,
                "quantity": 1,
                "discount": 0,
                "subtotal": 300
            }
        ]
    }
]
</code>```

答:
AMS doesn't include associations of associations - it only goes 1 level deep. There are ways around this:

Use include in your controllers (docs)

Use a workaround like this one - I'm currently using it successfully in production

Body:
I have three models namely Invoice, InvoiceDetail and Product.
An Invoice has many InvoiceDetails and an InvoiceDetails belongs to Invoice and Product

I have serializers defined for all the three models respectively but when I'm fetch invoice, I'm not able to fetch Product attributes.

Invoice Model :

 class Invoice < ApplicationRecord
  has_many :invoiceDetails, inverse_of: :invoice
  belongs_to :customer
  accepts_nested_attributes_for :invoiceDetails
end

InvoiceDetai Model

 class InvoiceDetail < ApplicationRecord
  belongs_to :invoice
  belongs_to :product
end

Product Model

class Product < ApplicationRecord
  belongs_to :company
  belongs_to :category
  belongs_to :user
end

Serializers

    class InvoiceSerializer < ActiveModel::Serializer
  attributes :id, :total_amount, :balance_amount, :created_at
  belongs_to :customer
  has_many :invoiceDetails
end

class InvoiceDetailSerializer < ActiveModel::Serializer
  attributes :id, :quantity, :discount, :subtotal
  belongs_to :product
end

class ProductSerializer < ActiveModel::Serializer
  attributes :id, :name, :mrp, :sp, :cp, :stocks, :isPublished
  has_one :category
end

When I fetch an Invoice :
The JSON output does not include product attributes.

[
    {
        "id": 3,
        "total_amount": 450,
        "balance_amount": 350,
        "created_at": "2017-06-27T17:02:20.000Z",
        "customer": {
            "id": 4,
            "company_id": 1,
            "name": "vivek",
            "isActive": true,
            "created_at": "2017-06-27T14:35:50.000Z",
            "updated_at": "2017-06-27T14:35:50.000Z",
            "mobile": 12345678,
            "address": "test",
            "pan_number": null,
            "tin_number": null,
            "party_name": "xyz"
        },
        "invoiceDetails": [
            {
                "id": 4,
                "quantity": 1,
                "discount": 0,
                "subtotal": 150
            },
            {
                "id": 5,
                "quantity": 1,
                "discount": 0,
                "subtotal": 300
            }
        ]
    }
]


问:
Add to basket ecommerce function without using GTM. Will the following act as expected?
I've been tasked with hard-coding enhanced ecommerce tracking to a website (without the use of any tag management). The task is to simple include 'add to basket'.

It's expected that I define the data fields with some variables, rather than a string.

So, given this web page, would the following script pull the relevant data I'm expecting? (SKU, Product name, price and quantity selected)

// Called when a product is added to a shopping cart.
function addToCart(product) {
  ga('ec:addProduct', {
     'id': document.getElementsByClassName(‘sku’).text,
     'name’:  document.getElementsByClassName('pdHero-name h4’).text,
     'price’:  document.getElementById('salePrice').text,
     'quantity’:  document.getElementByClassName(‘oakley-custom-selectInner’).text
     });
  ga('ec:setAction', 'add');
  ga('send', 'event', 'UX', 'click', 'add to cart');     // Send data using an event.
}```

答:
All of your snippets above return errors when I run them on the page, so I would make the stab that they do not currently work.

The easiest way to confirm is to open the webpage in your web browser, and then try running the snippets in a javascript console (e.g. cmd+alt+j in Chrome for Mac).

If you can, it is almost certainly better to scrape by id or by name, because these are less likely to change for frivolous reasons - class is primarily for style and so it is very likely to change when the page style does.

Class name and name refer to different parts of the html element:

```<code><div class="bold" name="first" id="firstId">here is some value</div>
<div class="bold" name="second" id="secondId">here is a second value</div>
</code>```

getElementsByClassName('bold') checks for class=, and would return both of the divs above in a list

getElementsByName('first') checks for name=, and would return only the first (but in a list, because there theoretically could be more than one element with that name)

getElementById('secondId') checks for id=, and would return only the second.

In the case of the first two functions, you'll always need to access the first element before accessing any other properties, e.g. getElementsByName('first')[0].innerText, but note this will raise an exception if there are no elements in the page with that name.

Another point of caution: it looks like a bunch of the quotes in your code block have been replaced by smart-quotes, which will not work if you use them in your real code (e.g. ‘ or ’ instead of '). If you're working on a Mac I would recommend turning off smart quotes altogether.

Going deeper into the question is probably too specific to be useful for Stack Overflow, but if you have any particular difficulty with a field that might be useful to post as a separate question.

Body:
All of your snippets above return errors when I run them on the page, so I would make the stab that they do not currently work.

The easiest way to confirm is to open the webpage in your web browser, and then try running the snippets in a javascript console (e.g. cmd+alt+j in Chrome for Mac).

If you can, it is almost certainly better to scrape by id or by name, because these are less likely to change for frivolous reasons - class is primarily for style and so it is very likely to change when the page style does.

Class name and name refer to different parts of the html element:

<div class="bold" name="first" id="firstId">here is some value</div>
<div class="bold" name="second" id="secondId">here is a second value</div>

getElementsByClassName('bold') checks for class=, and would return both of the divs above in a list

getElementsByName('first') checks for name=, and would return only the first (but in a list, because there theoretically could be more than one element with that name)

getElementById('secondId') checks for id=, and would return only the second.

In the case of the first two functions, you'll always need to access the first element before accessing any other properties, e.g. getElementsByName('first')[0].innerText, but note this will raise an exception if there are no elements in the page with that name.

Another point of caution: it looks like a bunch of the quotes in your code block have been replaced by smart-quotes, which will not work if you use them in your real code (e.g. ‘ or ’ instead of '). If you're working on a Mac I would recommend turning off smart quotes altogether.

Going deeper into the question is probably too specific to be useful for Stack Overflow, but if you have any particular difficulty with a field that might be useful to post as a separate question.


问:
PHP: Explode CSS selectors and compare with a list
I got an Object of Simple HTML DOM, which I can use to gather some information.

To get the tag of an element I can use:

$element->parent()->tag();

The result is a string like span or div.

To get the attributes I am using

$element->parent()->getAllAttributes();

A possible result is

["id"]=> string(4) "huhu" ["class"]=> string(5) "heyho"

or just

["id"]=> string(4) "huhu"

On the other side I got an array with elements like those:

```<code>array(11) { [0]=> string(2) "em" [1]=> string(5) "style" [2]=> string(1) "a" [3]=> string(3) "img" [4]=> string(4) "code" [5]=> string(3) "pre" [6]=> string(15) "span.helloworld" [7]=> string(2) "h1" [8]=> string(2) "h2" [9]=> string(2) "h3" [10]=> string(6) "button" } array(11) { [0]=> string(2) "em" [1]=> string(5) "style" [2]=> string(1) "a" [3]=> string(3) "img" [4]=> string(4) "code" [5]=> string(3) "pre" [6]=> string(15) "span.helloworld" [7]=> string(2) "h1" [8]=> string(2) "h2" [9]=> string(2) "h3" [10]=> string(6) "button" } array(11) { [0]=> string(2) "em" [1]=> string(5) "style" [2]=> string(1) "a" [3]=> string(3) "img" [4]=> string(4) "code" [5]=> string(3) "pre" [6]=> string(15) "span.helloworld" [7]=> string(2) "h1" [8]=> string(2) "h2" [9]=> string(2) "h3" [10]=> string(6) "button" } array(11) { [0]=> string(2) "em" [1]=> string(5) "style" [2]=> string(1) "a" [3]=> string(3) "img" [4]=> string(4) "code" [5]=> string(3) "pre" [6]=> string(15) "span.helloworld" [7]=> string(2) "h1" [8]=> string(2) "h2" [9]=> string(2) "h3" [10]=> string(6) "button" } array(11) { [0]=> string(2) "em" [1]=> string(5) "style" [2]=> string(1) "a" [3]=> string(3) "img" [4]=> string(4) "code" [5]=> string(3) "pre" [6]=> string(15) "span.helloworld" [7]=> string(2) "h1" [8]=> string(2) "h2" [9]=> string(2) "h3" [10]=> string(6) "button" } array(11) { [0]=> string(2) "em" [1]=> string(5) "style" [2]=> string(1) "a" [3]=> string(3) "img" [4]=> string(4) "code" [5]=> string(3) "pre" [6]=> string(15) "span.helloworld" [7]=> string(2) "h1" [8]=> string(2) "h2" [9]=> string(2) "h3" [10]=> string(6) "button" } array(11) { [0]=> string(2) "em" [1]=> string(5) "style" [2]=> string(1) "a" [3]=> string(3) "img" [4]=> string(4) "code" [5]=> string(3) "pre" [6]=> string(15) "span.helloworld" [7]=> string(2) "h1" [8]=> string(2) "h2" [9]=> string(2) "h3" [10]=> string(6) "button" } array(11) { [0]=> string(2) "em" [1]=> string(5) "style" [2]=> string(1) "a" [3]=> string(3) "img" [4]=> string(4) "code" [5]=> string(3) "pre" [6]=> string(15) "span.helloworld" [7]=> string(2) "h1" [8]=> string(2) "h2" [9]=> string(2) "h3" [10]=> string(6) "button" } array(11) { [0]=> string(2) "em" [1]=> string(5) "style" [2]=> string(1) "a" [3]=> string(3) "img" [4]=> string(4) "code" [5]=> string(3) "pre" [6]=> string(15) "span.helloworld" [7]=> string(2) "h1" [8]=> string(2) "h2" [9]=> string(2) "h3" [10]=> string(6) "button" }
</code>```

Now I would like to do something, only if the tag (and, if given, the attributes) are matching.

The first thing is easy:

```<code>if ( in_array( $element->parent()->tag, $excludedParents ) { ... }
</code>```

The second thing is a problem, because I would have to split up span.helloworld and compare the tag and the attributes.

Next thing is: It should be possible with other css-like selectors, too (just like span#id).

To give you a full example:

The html-content looks like this:

```<code><article class="uk-article uk-text-center">
    <p><span class="helloworld">Lorem ipsum dolor</span> sit amet <span id="huhu" class="heyho">consectetur
</article>
</code>```

Now I am looping through all text elements:

```<code>    foreach ( $dom->find( 'text' ) as $element ) {
        if ( !in_array( $element->parent()->tag, $excluded ) ) {
                $element->innertext = "test";
        }
    }

    return $dom->save();
</code>```

Alright. Let's have a look at the $excluded:

dump($excluded);:

```<code>array:12 [▼
  0 => "em"
  1 => "style"
  2 => "a"
  3 => "img"
  4 => "code"
  5 => "pre"
  6 => "h1"
  7 => "h2"
  8 => "h3"
  9 => "button"
  10 => "ul"
  11 => "span.helloworld"
]
</code>```

Now unfortunately the test if ( !in_array( $element->parent()->tag, $excluded ) ) does only work on real tags. But not on "jQuery-like" selectors like span.helloworld.

The problem is: The class/id/other attributes are saved this way:

dump($element->parent()->getAllAttributes());:

```<code>array:1 [▼
  "class" => "uk-article uk-text-center"
]
</code>```

or

```<code>array:1 [▼
  "class" => "helloworld"
]
</code>```

or

```<code>array:2 [▼
  "id" => "huhu"
  "class" => "heyho"
]
</code>```

This tells me, that I would have to "split up" the selector and check if it is a class-selector, an id-selector, ... .

Any idea how to solve this?

答:
I think I see what you  mean. You would have to go up 2 and check if the children match the css. Something like:

```<code>foreach ( $dom->find( 'text' ) as $element ) {
  foreach($excluded as $css){
    foreach($element->parent->parent->find("> $css") as $parent){ // check children of gp
      if($parent == $element->parent) continue(3);
    }
  }
  if ( !in_array( $element->parent()->tag, $excluded ) ) {
    $element->innertext = "test";
  }
}
</code>```

unfortunately I don't think the simple-html-dom child selector (>) is reliable so you might have some problems.

Body:
I got an Object of Simple HTML DOM, which I can use to gather some information.

To get the tag of an element I can use:

$element->parent()->tag();

The result is a string like span or div.

To get the attributes I am using

$element->parent()->getAllAttributes();

A possible result is

["id"]=> string(4) "huhu" ["class"]=> string(5) "heyho"

or just

["id"]=> string(4) "huhu"

On the other side I got an array with elements like those:

array(11) { [0]=> string(2) "em" [1]=> string(5) "style" [2]=> string(1) "a" [3]=> string(3) "img" [4]=> string(4) "code" [5]=> string(3) "pre" [6]=> string(15) "span.helloworld" [7]=> string(2) "h1" [8]=> string(2) "h2" [9]=> string(2) "h3" [10]=> string(6) "button" } array(11) { [0]=> string(2) "em" [1]=> string(5) "style" [2]=> string(1) "a" [3]=> string(3) "img" [4]=> string(4) "code" [5]=> string(3) "pre" [6]=> string(15) "span.helloworld" [7]=> string(2) "h1" [8]=> string(2) "h2" [9]=> string(2) "h3" [10]=> string(6) "button" } array(11) { [0]=> string(2) "em" [1]=> string(5) "style" [2]=> string(1) "a" [3]=> string(3) "img" [4]=> string(4) "code" [5]=> string(3) "pre" [6]=> string(15) "span.helloworld" [7]=> string(2) "h1" [8]=> string(2) "h2" [9]=> string(2) "h3" [10]=> string(6) "button" } array(11) { [0]=> string(2) "em" [1]=> string(5) "style" [2]=> string(1) "a" [3]=> string(3) "img" [4]=> string(4) "code" [5]=> string(3) "pre" [6]=> string(15) "span.helloworld" [7]=> string(2) "h1" [8]=> string(2) "h2" [9]=> string(2) "h3" [10]=> string(6) "button" } array(11) { [0]=> string(2) "em" [1]=> string(5) "style" [2]=> string(1) "a" [3]=> string(3) "img" [4]=> string(4) "code" [5]=> string(3) "pre" [6]=> string(15) "span.helloworld" [7]=> string(2) "h1" [8]=> string(2) "h2" [9]=> string(2) "h3" [10]=> string(6) "button" } array(11) { [0]=> string(2) "em" [1]=> string(5) "style" [2]=> string(1) "a" [3]=> string(3) "img" [4]=> string(4) "code" [5]=> string(3) "pre" [6]=> string(15) "span.helloworld" [7]=> string(2) "h1" [8]=> string(2) "h2" [9]=> string(2) "h3" [10]=> string(6) "button" } array(11) { [0]=> string(2) "em" [1]=> string(5) "style" [2]=> string(1) "a" [3]=> string(3) "img" [4]=> string(4) "code" [5]=> string(3) "pre" [6]=> string(15) "span.helloworld" [7]=> string(2) "h1" [8]=> string(2) "h2" [9]=> string(2) "h3" [10]=> string(6) "button" } array(11) { [0]=> string(2) "em" [1]=> string(5) "style" [2]=> string(1) "a" [3]=> string(3) "img" [4]=> string(4) "code" [5]=> string(3) "pre" [6]=> string(15) "span.helloworld" [7]=> string(2) "h1" [8]=> string(2) "h2" [9]=> string(2) "h3" [10]=> string(6) "button" } array(11) { [0]=> string(2) "em" [1]=> string(5) "style" [2]=> string(1) "a" [3]=> string(3) "img" [4]=> string(4) "code" [5]=> string(3) "pre" [6]=> string(15) "span.helloworld" [7]=> string(2) "h1" [8]=> string(2) "h2" [9]=> string(2) "h3" [10]=> string(6) "button" }

Now I would like to do something, only if the tag (and, if given, the attributes) are matching.

The first thing is easy:

if ( in_array( $element->parent()->tag, $excludedParents ) { ... }

The second thing is a problem, because I would have to split up span.helloworld and compare the tag and the attributes.

Next thing is: It should be possible with other css-like selectors, too (just like span#id).

To give you a full example:

The html-content looks like this:

Lorem ipsum dolor sit amet consectetur

Now I am looping through all text elements:

    foreach ( $dom->find( 'text' ) as $element ) {
        if ( !in_array( $element->parent()->tag, $excluded ) ) {
                $element->innertext = "test";
        }
    }

    return $dom->save();

Alright. Let's have a look at the $excluded:

dump($excluded);:

array:12 [▼
  0 => "em"
  1 => "style"
  2 => "a"
  3 => "img"
  4 => "code"
  5 => "pre"
  6 => "h1"
  7 => "h2"
  8 => "h3"
  9 => "button"
  10 => "ul"
  11 => "span.helloworld"
]

Now unfortunately the test if ( !in_array( $element->parent()->tag, $excluded ) ) does only work on real tags. But not on "jQuery-like" selectors like span.helloworld.

The problem is: The class/id/other attributes are saved this way:

dump($element->parent()->getAllAttributes());:

array:1 [▼
  "class" => "uk-article uk-text-center"
]

or

array:1 [▼
  "class" => "helloworld"
]

or

array:2 [▼
  "id" => "huhu"
  "class" => "heyho"
]

This tells me, that I would have to "split up" the selector and check if it is a class-selector, an id-selector, ... .

Any idea how to solve this?

Body:
I think I see what you  mean. You would have to go up 2 and check if the children match the css. Something like:

foreach ( $dom->find( 'text' ) as $element ) {
  foreach($excluded as $css){
    foreach($element->parent->parent->find("> $css") as $parent){ // check children of gp
      if($parent == $element->parent) continue(3);
    }
  }
  if ( !in_array( $element->parent()->tag, $excluded ) ) {
    $element->innertext = "test";
  }
}

unfortunately I don't think the simple-html-dom child selector (>) is reliable so you might have some problems.


问:
Why isn't contenteditable working?
I'm trying to get contenteditable to work on a style element but it doesn't seem to be changing anything and the other styles dont seem to be being applied</p>

```<code>  <style contenteditable="true" style="display: block; width: 500px; height: 500px; border: 1px solid black;">

  </style>
</code>```

答:
I tried this it's working.

```<code><style contenteditable="true" style="display: block; width: 500px; height: 500px; border: 1px solid black;">

  </style>
<div class="x"></div>
</code>```

https://codepen.io/sefalette-1472316262/pen/KqxwVY

Title: Why isn't contenteditable working?

Body:
I tried this it's working.

<style contenteditable="true" style="display: block; width: 500px; height: 500px; border: 1px solid black;">

  </style>
<div class="x"></div>

https://codepen.io/sefalette-1472316262/pen/KqxwVY


问:
How to implement a memory heap
Wasn't exactly sure how to phrase the title, but the question is:

I've heard of programmers allocating a large section of contiguous memory at the start of a program and then dealing it out as necessary. This is, in contrast to simply going to the OS every time memory is needed.
I've heard that this would be faster because it would avoid the cost of asking the OS for contiguous blocks of memory constantly.

I believe the JVM does just this, maintaining its own section of memory and then allocating objects from that.

My question is, how would one actually implement this?

答:
You allocate a chunk of memory at the beginning of the program large enough to sustain its need. Then you have to override new and/or malloc, delete and/or free to return memory from/to this buffer.

When implementing this kind of solution, you need to write your own allocator(to source from the chunk) and you may end up using more than one allocator which is often why you allocate a memory pool in the first place.

Default memory allocator is a good all around allocator but is not the best for all allocation needs. For example, if you know you'll be allocating a lot of object for a particular size, you may define an allocator that allocates fixed size buffer and pre-allocate more than one to gain some efficiency.

Title: How to implement a memory heap

ContentLicense: CC BY-SA 2.5


问:
Why bootstrap *multiple* Angular modules to a *single* element
The angular documentation for the angular.bootstrap(...) method says the second argument is:

...an array of modules to load into the application. Each item in the array should be the name of a predefined module or a (DI annotated)

I had never seen Angular code which passes a more than one module in to be boostrapped to the same DOM element... Why would you want to do that? Angular tutorials don't provide an example. So I found this example on StackOverflow. This example bootstraps both peopleApp and thermostatApp to the document:

```<code>angular.bootstrap(document, ['peopleApp','thermostatApp']);
</code>```

What happens if those apps have the same name for a controller? Like MyCtrl? Which definition is respected?

How is boostrapping multiple modules; different than creating a new ConsolidatedModule, which has dependencies to the one or more modules you would've boostrapped, and then just bootstrapping the single ConsolidatedModule? i.e.

```<code>angular.module('ConsolidatedModule', ['peopleApp', 'thermostatApp']);
angular.bootstrap(document, ['ConsolidatedModule'])
</code>```

To be clear, I'm not talking about bootstrapping separate apps to separate DOM elements. (also shown here)

Other anecdotal evidence that makes me confused about this:

You can't shouldn't (?) bootstrap an app within another already bootstrap'd app (... because

"traversing it's way through the DOM and setting up scope bindings and executing directive linking functions all the way through. If you do that twice, you're going to run into problems."

-- and yet, bootstrapping the same element with two modules won't run into problems?)

In Angular2, platformBrowserDynamic.bootstrapModule(...) is singular; implies it only accepts a single argument ( I couldn't find the API), so I'm even more confused what it means in angular  1.* to bootstrap multiple modules to the same DOM node.

答:
There's no difference between

```<code>angular.module('ConsolidatedModule', ['peopleApp', 'thermostatApp']);
angular.bootstrap(document, ['ConsolidatedModule'])
</code>```

and

```<code>angular.bootstrap(document, ['peopleApp', 'thermostatApp'])
</code>```

except unneeded ConsolidatedModule module that is created in the first case. Only 1 injector is created, and bootstrapping with multiple modules has nothing to do with multiple bootstrapping.

The second argument allows to provide a list of modules dynamically. I.e.

```<code>const modulesList = ['foo'];

if (ENV_BAR)
  modulesList.push('bar');

angular.bootstrap(document, modulesList);
</code>```

Body:
The angular documentation for the angular.bootstrap(...) method says the second argument is:

...an array of modules to load into the application. Each item in the array should be the name of a predefined module or a (DI annotated)

I had never seen Angular code which passes a more than one module in to be boostrapped to the same DOM element... Why would you want to do that? Angular tutorials don't provide an example. So I found this example on StackOverflow. This example bootstraps both peopleApp and thermostatApp to the document:

angular.bootstrap(document, ['peopleApp','thermostatApp']);

What happens if those apps have the same name for a controller? Like MyCtrl? Which definition is respected?

How is boostrapping multiple modules; different than creating a new ConsolidatedModule, which has dependencies to the one or more modules you would've boostrapped, and then just bootstrapping the single ConsolidatedModule? i.e.

angular.module('ConsolidatedModule', ['peopleApp', 'thermostatApp']);
angular.bootstrap(document, ['ConsolidatedModule'])

To be clear, I'm not talking about bootstrapping separate apps to separate DOM elements. (also shown here)

Other anecdotal evidence that makes me confused about this:

You can't shouldn't (?) bootstrap an app within another already bootstrap'd app (... because

"traversing it's way through the DOM and setting up scope bindings and executing directive linking functions all the way through. If you do that twice, you're going to run into problems."

-- and yet, bootstrapping the same element with two modules won't run into problems?)

In Angular2, platformBrowserDynamic.bootstrapModule(...) is singular; implies it only accepts a single argument ( I couldn't find the API), so I'm even more confused what it means in angular  1.* to bootstrap multiple modules to the same DOM node.

Body:
There's no difference between

angular.module('ConsolidatedModule', ['peopleApp', 'thermostatApp']);
angular.bootstrap(document, ['ConsolidatedModule'])

and

angular.bootstrap(document, ['peopleApp', 'thermostatApp'])

except unneeded ConsolidatedModule module that is created in the first case. Only 1 injector is created, and bootstrapping with multiple modules has nothing to do with multiple bootstrapping.

The second argument allows to provide a list of modules dynamically. I.e.

const modulesList = ['foo'];

if (ENV_BAR)
  modulesList.push('bar');

angular.bootstrap(document, modulesList);


问:
java .get(int index) getting just one value, get(0) or get(1) returns correct value but only .get(1) is saved to database
My array has a size of 3 and i want to save all three to my database however, only one keeps adding. I'm using .get(int index). Here is my code

```<code>    Sales sales= new Sales();
    for(int i = 0; i < drugname.size(); i++) {
        sales.setDrugcategory(drugcategory);
        sales.setQuantityrequested(quantityrequested);
        sales.setTotal(total);
        sales.setTotalbill(totalbill);
        System.out.println(drugname.size());
        System.out.println(i);
        sales.setDrugname(drugname.get(i));
        sales.setPrice(price.get(i));
        }
</code>```

Am I getting it wrong somewhere?
These are my getter and setter methods

```<code>@Entity
public class Sales {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
public String drugcategory;
public String drugname;
public String quantityrequested;
public float price;
public String total;
public String totalbill;
public String dateofsale;

public void setPrice(float price) {
    this.price = price;
}

public String getDateofsale() {
    return dateofsale;
}

public void setDateofsale(String dateofsale) {
    this.dateofsale = dateofsale;
}

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public String getDrugcategory() {
    return drugcategory;
}

public void setDrugcategory(String drugcategory) {
    this.drugcategory = drugcategory;
}

public String getDrugname() {
    return drugname;
}

public void setDrugname(String drugname) {
    this.drugname = drugname;
}

public String getQuantityrequested() {
    return quantityrequested;
}

public void setQuantityrequested(String quantityrequested) {
    this.quantityrequested = quantityrequested;
}

public String getTotal() {
    return total;
}

public void setTotal(String total) {
    this.total = total;
}

public String getTotalbill() {
    return totalbill;
}

public void setTotalbill(String totalbill) {
    this.totalbill = totalbill;
}
}
</code>```

答:
You are modifying the same object. Move creation of the object into the loop.

```<code>for(int i = 0; i < drugname.size(); i++) {
    Sales sales = new Sales();
    sales.setDrugcategory(drugcategory);
    sales.setQuantityrequested(quantityrequested);
    sales.setTotal(total);
    sales.setTotalbill(totalbill);
    System.out.println(drugname.size());
    System.out.println(i);
    sales.setDrugname(drugname.get(i));
    sales.setPrice(price.get(i));
}
</code>```

Also try to use camel case in names so instead of drugname use drugName, it makes code easier to read :-)

Body:
My array has a size of 3 and i want to save all three to my database however, only one keeps adding. I'm using .get(int index). Here is my code

    Sales sales= new Sales();
    for(int i = 0; i < drugname.size(); i++) {
        sales.setDrugcategory(drugcategory);
        sales.setQuantityrequested(quantityrequested);
        sales.setTotal(total);
        sales.setTotalbill(totalbill);
        System.out.println(drugname.size());
        System.out.println(i);
        sales.setDrugname(drugname.get(i));
        sales.setPrice(price.get(i));
        }

Am I getting it wrong somewhere?
These are my getter and setter methods

@Entity
public class Sales {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
public String drugcategory;
public String drugname;
public String quantityrequested;
public float price;
public String total;
public String totalbill;
public String dateofsale;

public void setPrice(float price) {
    this.price = price;
}

public String getDateofsale() {
    return dateofsale;
}

public void setDateofsale(String dateofsale) {
    this.dateofsale = dateofsale;
}

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public String getDrugcategory() {
    return drugcategory;
}

public void setDrugcategory(String drugcategory) {
    this.drugcategory = drugcategory;
}

public String getDrugname() {
    return drugname;
}

public void setDrugname(String drugname) {
    this.drugname = drugname;
}

public String getQuantityrequested() {
    return quantityrequested;
}

public void setQuantityrequested(String quantityrequested) {
    this.quantityrequested = quantityrequested;
}

public String getTotal() {
    return total;
}

public void setTotal(String total) {
    this.total = total;
}

public String getTotalbill() {
    return totalbill;
}

public void setTotalbill(String totalbill) {
    this.totalbill = totalbill;
}
}

Body:
You are modifying the same object. Move creation of the object into the loop.

for(int i = 0; i < drugname.size(); i++) {
    Sales sales = new Sales();
    sales.setDrugcategory(drugcategory);
    sales.setQuantityrequested(quantityrequested);
    sales.setTotal(total);
    sales.setTotalbill(totalbill);
    System.out.println(drugname.size());
    System.out.println(i);
    sales.setDrugname(drugname.get(i));
    sales.setPrice(price.get(i));
}

Also try to use camel case in names so instead of drugname use drugName, it makes code easier to read :-)


问:
Deleting element in JavaScript or JQuery
I have two view pages. On both pages I have a list of items with a picture of a star next to it. On the 1st page, I can click the star and it will turn blue or gray. On the 2nd page, if the star is blue and I click on it I want to delete the parent div associated it. It does delete it when I reload the whole page but doesn't delete it immediately. How can I delete it from the page immediately and without clicking the reload button?

This is in my result.html.erb where I want to delete the parent div. To be clear, when I click on the star associated with the diamond div, I want to delete that whole div and leave the pearl div alone.

```<code><div id="result">
  <div class="diamond">
    <a target="_blank" href="www.website.com">diamond</a>
    <img class="star-pic" src="/assets/star-blue.png" alt="star pic">
  </div>
  <div class="pearl">
    <a target="_blank" href="www.website.com">pearl</a>
    <img class="star-pic" src="/assets/star-blue.png" alt="star pic">
  </div>
</div>
</code>```

This is in my application.js

```<code>var favoriteGems = JSON.parse(localStorage.getItem("gems")) || []

function changeStar(){
  if($(this).attr("src") == "/assets/star-gray.png"){
    $(this).attr("src", "/assets/star-blue.png")
    favoriteGems.push($(this).closest("div").first().text().replace(/\s+/g, ''))
    localStorage.setItem("gems", JSON.stringify(favoriteGems))
  }
  else if ($(this).attr("src") == "/assets/star-blue.png"){
    $(this).attr("src", "/assets/star-gray.png")
    favoriteGems = favoriteGems.filter(item => item !== $(this).closest("div").first().text().replace(/\s+/g, ''))
    localStorage.setItem("gems", JSON.stringify(favoriteGems))
    $("#result").remove("."+item)
    $("#result").show()
  }
}

$(".star-pic").on("click", changeStar)
</code>```

I've tried

```<code>$("#result").remove("."+item)
location.reload()
</code>```

and that doesn't work either.

Any guidance would be greatly appreciated.

答:
To be sincere this looks a bit cryptic, but why not call simply

```<code>$(this).parent().remove();
</code>```

? And clean a bit the html structure & js

```<code><div id="result">
<div class="diamond">
  <a target="_blank" href="www.website.com">diamond</a>
  <img class="star-pic blue-star" src="/assets/star-blue.png" alt="star pic" data-info="diamond">
</div>
<div class="pearl">
  <a target="_blank" href="www.website.com">pearl</a>
  <img class="star-pic blue-star" src="/assets/star-blue.png" alt="star pic" data-info="pearl">
</div>
</div>

var favoriteGems = JSON.parse(localStorage.getItem("gems")) || []

function changeStar(){
  if($(this).hasClass('gray-star')){
    $(this).attr("src", "/assets/star-blue.png");
    $(this).removeClass('grey-star').addClass('blue-star');
    favoriteGems.push($(this).data('info'));
    localStorage.setItem("gems", JSON.stringify(favoriteGems));
  }
  else if ($(this).hasClass('blue-star')){
    $(this).attr("src", "/assets/star-gray.png");
    $(this).removeClass('blue-star').addClass('gray-star');
    favoriteGems = favoriteGems.filter(item => item !== $(this).data('info'));
    localStorage.setItem("gems", JSON.stringify(favoriteGems))
    $(this).parent().remove();
    $("#result").show();
  }
}
</code>```

(and also maybe using a svg path for the star and controlling the color through the css class?)

Body:
I have two view pages. On both pages I have a list of items with a picture of a star next to it. On the 1st page, I can click the star and it will turn blue or gray. On the 2nd page, if the star is blue and I click on it I want to delete the parent div associated it. It does delete it when I reload the whole page but doesn't delete it immediately. How can I delete it from the page immediately and without clicking the reload button?

This is in my result.html.erb where I want to delete the parent div. To be clear, when I click on the star associated with the diamond div, I want to delete that whole div and leave the pearl div alone.

    diamond

    pearl

This is in my application.js

var favoriteGems = JSON.parse(localStorage.getItem("gems")) || []

function changeStar(){
  if($(this).attr("src") == "/assets/star-gray.png"){
    $(this).attr("src", "/assets/star-blue.png")
    favoriteGems.push($(this).closest("div").first().text().replace(/\s+/g, ''))
    localStorage.setItem("gems", JSON.stringify(favoriteGems))
  }
  else if ($(this).attr("src") == "/assets/star-blue.png"){
    $(this).attr("src", "/assets/star-gray.png")
    favoriteGems = favoriteGems.filter(item => item !== $(this).closest("div").first().text().replace(/\s+/g, ''))
    localStorage.setItem("gems", JSON.stringify(favoriteGems))
    $("#result").remove("."+item)
    $("#result").show()
  }
}

$(".star-pic").on("click", changeStar)

I've tried

$("#result").remove("."+item)
location.reload()

and that doesn't work either.

Any guidance would be greatly appreciated.

Body:
To be sincere this looks a bit cryptic, but why not call simply

$(this).parent().remove();

? And clean a bit the html structure & js

<div id="result">
<div class="diamond">
  <a target="_blank" href="www.website.com">diamond</a>
  <img class="star-pic blue-star" src="/assets/star-blue.png" alt="star pic" data-info="diamond">
</div>
<div class="pearl">
  <a target="_blank" href="www.website.com">pearl</a>
  <img class="star-pic blue-star" src="/assets/star-blue.png" alt="star pic" data-info="pearl">
</div>
</div>

var favoriteGems = JSON.parse(localStorage.getItem("gems")) || []

function changeStar(){
  if($(this).hasClass('gray-star')){
    $(this).attr("src", "/assets/star-blue.png");
    $(this).removeClass('grey-star').addClass('blue-star');
    favoriteGems.push($(this).data('info'));
    localStorage.setItem("gems", JSON.stringify(favoriteGems));
  }
  else if ($(this).hasClass('blue-star')){
    $(this).attr("src", "/assets/star-gray.png");
    $(this).removeClass('blue-star').addClass('gray-star');
    favoriteGems = favoriteGems.filter(item => item !== $(this).data('info'));
    localStorage.setItem("gems", JSON.stringify(favoriteGems))
    $(this).parent().remove();
    $("#result").show();
  }
}

(and also maybe using a svg path for the star and controlling the color through the css class?)


问:
How to keep Python from treating string like HTML in web2py?
I'm working in web2py and I'm trying to print out html code from the controller, which is written in python. The issue is even when I write the html in a string in python, the page is rendering this string as it would normal html. This seems like there would be a simple fix, but I have not been able to find an answer. Here is the specific code.

```<code>  return ('Here is the html I'm trying to show: <img src= {0}>'.format(x))
</code>```

The resulting page shows "Here is the html I'm trying to show: " and then the rest is blank. If I inspect the page the rest of the code is still there, which means it is being read, just not displayed. So I just need a way to keep the html that is in the string from being interpreted as html. Any ideas?

答:
I take it you are trying to view this string in a web browser.

To take the raw html and not have the browser render it, you can wrap it in <xmp> tags:

```<code>return ("Here is the html I'm trying to show: <xmp><img src= {0}></xmp>".format(x))
</code>```

Body:
I'm working in web2py and I'm trying to print out html code from the controller, which is written in python. The issue is even when I write the html in a string in python, the page is rendering this string as it would normal html. This seems like there would be a simple fix, but I have not been able to find an answer. Here is the specific code.

  return ('Here is the html I'm trying to show: '.format(x))

The resulting page shows "Here is the html I'm trying to show: " and then the rest is blank. If I inspect the page the rest of the code is still there, which means it is being read, just not displayed. So I just need a way to keep the html that is in the string from being interpreted as html. Any ideas?

Body:
I take it you are trying to view this string in a web browser.

To take the raw html and not have the browser render it, you can wrap it in <xmp> tags:

return ("Here is the html I'm trying to show: <xmp><img src= {0}></xmp>".format(x))


问:
Plotting a 2d contour plot in python with sparse data
I have some output data from an ocean circulation model (MITgcm). It is an idealised channel (Cartesian) so the geometry is not confusing, luckily.

I'd like to plot some of the fields (velocity, temperature etc.) in the y-z plane. The simulation domain involves 30 vertical layers where each layer is an 800x400 y-x grid. I have each of the fields stored in numpy arrays with shape (30, 800, 400) going z,y,x respectively.

I can easily plot x-y plane slices for the 30 vertical levels. I can do this using matplotlib's contourf or imshow and changing the extent to the correct physical values in km.

The problem is that the vertical layers are unevenly spaced. I have the grid data for Z which tells me what physical depth (in metres) each of the layers corresponds to.

Z is: [-5.  -15.  -25.    -36.    -49.    -65.    -84.   -105.5  -130.5 -159.5  -192.5  -230. -273.   -322.5  -379.   -443.   -515.   -596. -688. -792. -909.5 -1042.5 -1192.5 -1362.  -1553.5 -1770.  -2015.
 -2285.  -2565.  -2845.]

I tried to get round this by creating an empty matrix with 2985 (as the full domain depth is 2985m) 'vertical' layers, and inputting the y-data at the corresponding positions for the 30 layers as given by Z above (here yz_zonal is a (30,800) matrix of data values):

```<code>yz_matrix = np.empty((2985, 800)) #empty matrix for yz-plane data, vertical extent is 2985 (m)

for i in range(len(Z)):
     yz_matrix[round(-Z[i])] = yz_zonal[i] #set matrix values to correct depths
</code>```

Then if I try to plot yz_matrix using matplotlib's imshow, by doing:

```<code>fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_xlabel('y (km)')
ax.set_ylabel('z (m)')
yzplot = ax.imshow(yz_matrix, aspect='auto', interpolation='gaussian', cmap='inferno', extent=[0,2000,-2985,0])
plt.colorbar(yzplot)
</code>```

I just get this figure:BAD y-z plot of velocity data

There are 30 strips of data values at the correct physical z positions, but there's a whole load of zeros in between them. I only want to interpolate the data in between the 30 strips and ignore all of the other points.

It would be brilliant if anyone could sort this out for me. Thanks in advance!

Peter

答:
You may directly plot the yz_matrix as a pcolormesh, giving a meshgrid of the z and y data as coordinates. This would lead to different sized cells which extent up to next value in z. See left picture below.

You may also interpolate your data on a new finer grid. To this end, scipy.interpolate.griddata may be used.

```<code>import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import griddata

z = np.array([-5.,-15.,-25.,-36.,-49.,-65.,-84.,-105.5,-130.5,-159.5,-192.5,
              -230.,-273.,-322.5,-379.,-443.,-515.,-596.,-688.,-792.,-909.5,
              -1042.5,-1192.5,-1362.,-1553.5,-1770.,-2015.,-2285.,-2565.,-2845.])
y = np.arange(0,100)
yz_matrix = np.cumsum(np.random.rand(len(z), len(y)), axis=0)

fig, (ax, ax2) = plt.subplots(ncols=2)

# plot raw data as pcolormesh
Y,Z = np.meshgrid(y,z[::-1])
ax.pcolormesh(Y,Z, yz_matrix, cmap='inferno')
ax.set_title("pcolormesh data")

# now interpolate data to new grid
zi = np.arange(-2845,-5)
YI,ZI = np.meshgrid(y,zi)
points = np.c_[Y.flatten(),Z.flatten()]

interp = griddata(points, yz_matrix.flatten(), (YI,ZI), method='linear')

ax2.pcolormesh(YI,ZI, interp, cmap='inferno')
ax2.set_title("pcolormesh interpolated")

plt.show()
</code>```

Body:
I have some output data from an ocean circulation model (MITgcm). It is an idealised channel (Cartesian) so the geometry is not confusing, luckily.

I'd like to plot some of the fields (velocity, temperature etc.) in the y-z plane. The simulation domain involves 30 vertical layers where each layer is an 800x400 y-x grid. I have each of the fields stored in numpy arrays with shape (30, 800, 400) going z,y,x respectively.

I can easily plot x-y plane slices for the 30 vertical levels. I can do this using matplotlib's contourf or imshow and changing the extent to the correct physical values in km.

The problem is that the vertical layers are unevenly spaced. I have the grid data for Z which tells me what physical depth (in metres) each of the layers corresponds to.

Z is: [-5.  -15.  -25.    -36.    -49.    -65.    -84.   -105.5  -130.5 -159.5  -192.5  -230. -273.   -322.5  -379.   -443.   -515.   -596. -688. -792. -909.5 -1042.5 -1192.5 -1362.  -1553.5 -1770.  -2015.
 -2285.  -2565.  -2845.]

I tried to get round this by creating an empty matrix with 2985 (as the full domain depth is 2985m) 'vertical' layers, and inputting the y-data at the corresponding positions for the 30 layers as given by Z above (here yz_zonal is a (30,800) matrix of data values):

yz_matrix = np.empty((2985, 800)) #empty matrix for yz-plane data, vertical extent is 2985 (m)

for i in range(len(Z)):
     yz_matrix[round(-Z[i])] = yz_zonal[i] #set matrix values to correct depths

Then if I try to plot yz_matrix using matplotlib's imshow, by doing:

fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_xlabel('y (km)')
ax.set_ylabel('z (m)')
yzplot = ax.imshow(yz_matrix, aspect='auto', interpolation='gaussian', cmap='inferno', extent=[0,2000,-2985,0])
plt.colorbar(yzplot)

I just get this figure:BAD y-z plot of velocity data

There are 30 strips of data values at the correct physical z positions, but there's a whole load of zeros in between them. I only want to interpolate the data in between the 30 strips and ignore all of the other points.

It would be brilliant if anyone could sort this out for me. Thanks in advance!

Peter

Body:
You may directly plot the yz_matrix as a pcolormesh, giving a meshgrid of the z and y data as coordinates. This would lead to different sized cells which extent up to next value in z. See left picture below.

You may also interpolate your data on a new finer grid. To this end, scipy.interpolate.griddata may be used.

import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import griddata

z = np.array([-5.,-15.,-25.,-36.,-49.,-65.,-84.,-105.5,-130.5,-159.5,-192.5,
              -230.,-273.,-322.5,-379.,-443.,-515.,-596.,-688.,-792.,-909.5,
              -1042.5,-1192.5,-1362.,-1553.5,-1770.,-2015.,-2285.,-2565.,-2845.])
y = np.arange(0,100)
yz_matrix = np.cumsum(np.random.rand(len(z), len(y)), axis=0)

fig, (ax, ax2) = plt.subplots(ncols=2)

# plot raw data as pcolormesh
Y,Z = np.meshgrid(y,z[::-1])
ax.pcolormesh(Y,Z, yz_matrix, cmap='inferno')
ax.set_title("pcolormesh data")

# now interpolate data to new grid
zi = np.arange(-2845,-5)
YI,ZI = np.meshgrid(y,zi)
points = np.c_[Y.flatten(),Z.flatten()]

interp = griddata(points, yz_matrix.flatten(), (YI,ZI), method='linear')

ax2.pcolormesh(YI,ZI, interp, cmap='inferno')
ax2.set_title("pcolormesh interpolated")

plt.show()