问:
Can't login through Django's Admin page
I have already created a custom user model for profiling and Authentication, however it doesn't seem to authenticate the password. I tried numerous times on changing it and even confirmed it on shell but it still doesn't go through on Django Admin.

Here is my models.py:

```<code>from django.db import models
from django.contrib.auth.models import (
    BaseUserManager, AbstractBaseUser
)

# Create your models here.

class UserManager(BaseUserManager):
    def create_user(self, email, password=None, user_type=None, is_superuser=False, is_pqa=False, is_staff=False, is_admin=False, is_test_lead=False, is_test_manager=False, is_active=True):
        if not email:
            raise ValueError("User must have an email address!")
        if not password:
            raise ValueError("User must have a password!")
        user_obj = self.model(
            email=self.normalize_email(email)
        )
        user_obj.set_password(password)
        user_obj.user_type = user_type
        user_obj.ad = is_admin
        user_obj.superuser = is_superuser
        user_obj.tm = is_test_manager
        user_obj.pqa = is_pqa
        user_obj.tl = is_test_lead
        user_obj.active = is_active
        user_obj.save(using=self._db)
        return user_obj

    def create_pqa(self, email, password=None):
        user = self.create_user(
            email,
            password=password,
            is_pqa=True,
            is_staff=True,
            user_type=1
        )
        return user

    def create_staff(self, email, password=None):
        user = self.create_user(
            email,
            password=password,
            is_staff=True,
            user_type=2
        )
        return user

    def create_test_lead(self, email, password=None):
        user = self.create_user(
            email,
            password=password,
            is_test_lead=True,
            is_staff=True,
            user_type=3
        )
        return user

    def create_test_manager(self, email, password=None):
        user = self.create_user(
            email,
            password=password,
            is_test_manager=True,
            is_staff=True,
            user_type=4
        )
        return user

    def create_superuser(self, email, password=None):
        user = self.create_user(
            email,
            password=password,
            is_admin=True,
            is_superuser=True,
            is_staff=True,
            user_type=5
        )
        return user

class User(AbstractBaseUser):
    USER_TYPE_CHOICES = (
        (1, 'pqa'),
        (2, 'tester'),
        (3, 'test_lead'),
        (4, 'test_manager'),
        (5, 'admin'),
    )
    email = models.EmailField(max_length=255, unique=True)
    full_name = models.CharField(max_length=255, blank=True, null=True)
    active = models.BooleanField(default=True)
    birth_date = models.DateField(null=True, blank=True)
    hire_date = models.DateField(null=True, blank=True)
    user_type = models.PositiveSmallIntegerField(choices=USER_TYPE_CHOICES)
    ad = models.BooleanField(default=False)  # superuser/admin
    # non-superuser but with Team Manager Privilages
    tm = models.BooleanField(default=False)
    # non-superuser but with PQA Privilages
    pqa = models.BooleanField(default=False)
    ts = models.BooleanField(default=False)  # non-superuser
    # non-superuser but with TL Privilages
    tl = models.BooleanField(default=False)
    superuser = models.BooleanField(default=False)
    timestamp = models.DateTimeField(auto_now_add=True)

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []

    objects = UserManager()

    def __str__(self):
        return self.full_name

    def get_full_name(self):
        return self.full_name

    def get_short_name(self):
        return self.full_name

    @property
    def is_pqa(self):
        return self.pqa

    @property
    def is_staff(self):
        return self.ts

    @property
    def is_test_lead(self):
        return self.tl

    @property
    def is_test_manager(self):
        return self.tm

    @property
    def is_admin(self):
        return self.ad

    @property
    def is_active(self):
        return self.active

    @property
    def is_superuser(self):
        return self.superuser
</code>```

And here is my settings.py:

```<code>"""
Django settings for ceres project.

Generated by 'django-admin startproject' using Django 3.0.3.

For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '@3xm&$=ky!sq2_i$-9cd%48ork1l$1y-+e__g_4d!+3*2ssli-'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = [
    'profiles.apps.ProfilesConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

AUTH_USER_MODEL = 'profiles.User'  # Custom model

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'ceres.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'ceres.wsgi.application'

# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

# Password validation
# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/

STATIC_URL = '/static/'
</code>```

I really would appreciate if someone would point me at the right direction for this, since I'm at a loss. Thanks in advance!

答:
Create a new superuser by

```<code>python manage.py createsuperuser
</code>```

you will be able to login

Title: Can't login through Django's Admin page

Body:
I have already created a custom user model for profiling and Authentication, however it doesn't seem to authenticate the password. I tried numerous times on changing it and even confirmed it on shell but it still doesn't go through on Django Admin.

Here is my models.py:

from django.db import models
from django.contrib.auth.models import (
    BaseUserManager, AbstractBaseUser
)

# Create your models here.

class UserManager(BaseUserManager):
    def create_user(self, email, password=None, user_type=None, is_superuser=False, is_pqa=False, is_staff=False, is_admin=False, is_test_lead=False, is_test_manager=False, is_active=True):
        if not email:
            raise ValueError("User must have an email address!")
        if not password:
            raise ValueError("User must have a password!")
        user_obj = self.model(
            email=self.normalize_email(email)
        )
        user_obj.set_password(password)
        user_obj.user_type = user_type
        user_obj.ad = is_admin
        user_obj.superuser = is_superuser
        user_obj.tm = is_test_manager
        user_obj.pqa = is_pqa
        user_obj.tl = is_test_lead
        user_obj.active = is_active
        user_obj.save(using=self._db)
        return user_obj

    def create_pqa(self, email, password=None):
        user = self.create_user(
            email,
            password=password,
            is_pqa=True,
            is_staff=True,
            user_type=1
        )
        return user

    def create_staff(self, email, password=None):
        user = self.create_user(
            email,
            password=password,
            is_staff=True,
            user_type=2
        )
        return user

    def create_test_lead(self, email, password=None):
        user = self.create_user(
            email,
            password=password,
            is_test_lead=True,
            is_staff=True,
            user_type=3
        )
        return user

    def create_test_manager(self, email, password=None):
        user = self.create_user(
            email,
            password=password,
            is_test_manager=True,
            is_staff=True,
            user_type=4
        )
        return user

    def create_superuser(self, email, password=None):
        user = self.create_user(
            email,
            password=password,
            is_admin=True,
            is_superuser=True,
            is_staff=True,
            user_type=5
        )
        return user

class User(AbstractBaseUser):
    USER_TYPE_CHOICES = (
        (1, 'pqa'),
        (2, 'tester'),
        (3, 'test_lead'),
        (4, 'test_manager'),
        (5, 'admin'),
    )
    email = models.EmailField(max_length=255, unique=True)
    full_name = models.CharField(max_length=255, blank=True, null=True)
    active = models.BooleanField(default=True)
    birth_date = models.DateField(null=True, blank=True)
    hire_date = models.DateField(null=True, blank=True)
    user_type = models.PositiveSmallIntegerField(choices=USER_TYPE_CHOICES)
    ad = models.BooleanField(default=False)  # superuser/admin
    # non-superuser but with Team Manager Privilages
    tm = models.BooleanField(default=False)
    # non-superuser but with PQA Privilages
    pqa = models.BooleanField(default=False)
    ts = models.BooleanField(default=False)  # non-superuser
    # non-superuser but with TL Privilages
    tl = models.BooleanField(default=False)
    superuser = models.BooleanField(default=False)
    timestamp = models.DateTimeField(auto_now_add=True)

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []

    objects = UserManager()

    def __str__(self):
        return self.full_name

    def get_full_name(self):
        return self.full_name

    def get_short_name(self):
        return self.full_name

    @property
    def is_pqa(self):
        return self.pqa

    @property
    def is_staff(self):
        return self.ts

    @property
    def is_test_lead(self):
        return self.tl

    @property
    def is_test_manager(self):
        return self.tm

    @property
    def is_admin(self):
        return self.ad

    @property
    def is_active(self):
        return self.active

    @property
    def is_superuser(self):
        return self.superuser

And here is my settings.py:

"""
Django settings for ceres project.

Generated by 'django-admin startproject' using Django 3.0.3.

For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '@3xm&$=ky!sq2_i$-9cd%48ork1l$1y-+e__g_4d!+3*2ssli-'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = [
    'profiles.apps.ProfilesConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

AUTH_USER_MODEL = 'profiles.User'  # Custom model

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'ceres.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'ceres.wsgi.application'

# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

# Password validation
# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/

STATIC_URL = '/static/'

I really would appreciate if someone would point me at the right direction for this, since I'm at a loss. Thanks in advance!

Body:
Create a new superuser by

python manage.py createsuperuser

you will be able to login


来源: stackexchange

问:
Values are not appending
```<code>    import UIKit

class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {

    var array = [Product]()

    @IBOutlet weak var tableview: UITableView!
    override func viewDidLoad() {
        super.viewDidLoad()

        self.tableview.delegate = self
        self.tableview.dataSource = self

        array.append(Product.init(image: UIImage(named: "a1")!))
        array.append(Product.init(image: UIImage(named: "a2")!))
        array.append(Product.init(image: UIImage(named: "a3")!))
        // Do any additional setup after loading the view.
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        array.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! TableViewCell

        cell.imageview.image = array[indexPath.row].image

        return cell
    }

}
</code>```

This is viewController

```<code>import UIKit

class TableViewCell: UITableViewCell {

    @IBOutlet weak var imageview: UIImageView!
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

}
</code>```

This is tableviewcell

```<code>import UIKit

class Product
{
    var image: UIImage

    init(image: UIImage) {

        self.image = image
    }
}
</code>```

This is class

I am creating a tableview using class like arraylist i have do this code when i run application it will be crash and getting hread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value this error it means that values are null so i want to fix how to fix why values are not appending

答:
using storage_path()

```<code><img src="{{storage_path().'app/public/images/'.$category->thumbnail}}" width="100" height="100" />
</code>```

and if you linked storage path with public path like Link

```<code>php artisan storage:link

<img src="{{asset('storage/images/'.$category->thumbnail)}}" width="100" height="100" />
</code>```

ContentLicense: CC BY-SA 4.0

Title: Values are not appending

Body:
    import UIKit

class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {

    var array = [Product]()

    @IBOutlet weak var tableview: UITableView!
    override func viewDidLoad() {
        super.viewDidLoad()

        self.tableview.delegate = self
        self.tableview.dataSource = self

        array.append(Product.init(image: UIImage(named: "a1")!))
        array.append(Product.init(image: UIImage(named: "a2")!))
        array.append(Product.init(image: UIImage(named: "a3")!))
        // Do any additional setup after loading the view.
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        array.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! TableViewCell

        cell.imageview.image = array[indexPath.row].image

        return cell
    }

}

This is viewController

import UIKit

class TableViewCell: UITableViewCell {

    @IBOutlet weak var imageview: UIImageView!
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

}

This is tableviewcell

import UIKit

class Product
{
    var image: UIImage

    init(image: UIImage) {

        self.image = image
    }
}

This is class

I am creating a tableview using class like arraylist i have do this code when i run application it will be crash and getting hread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value this error it means that values are null so i want to fix how to fix why values are not appending

Body:
using storage_path()

<img src="{{storage_path().'app/public/images/'.$category->thumbnail}}" width="100" height="100" />

and if you linked storage path with public path like Link

php artisan storage:link

<img src="{{asset('storage/images/'.$category->thumbnail)}}" width="100" height="100" />


问:
How can I match the two dataframe and get the following result?
I have the following dataframe:
payment is the line of payment name with value

```<code>payment = pd.DataFrame({'Payment':["payment1","payment2","payment3"],'Value':[100,200,300]})

Payment     Value
payment1    100
payment2    200
payment3    300
</code>```

and project_cost is the line of project name with their cost

```<code>project_cost = pd.DataFrame({'Project':["Project1","Project2","Project3"],'Cost':[200,300,400]})

Project        Cost
Project1       200
Project2       300
Project3       400
</code>```

I basically want to match the payment with the project.

How can I get the following dataframe?

```<code>Project     Cost      Payment
Project1     100      payment1
Project1     100      payment2
Project2     100      payment2
Project2     200      payment3
Project3     100      payment3
Project3     300
</code>```

The last row of payment left empty because there is a deficit of payment to pay the project.

Is there anything I can do in the pandas to get this result?
Thanks a lot

The following is the logic of my dataframe:

The payment is broken down to match with the project.

答:
The following seems to work for the sample data. You should check it a little more. The idea is that you compute the accumulation (cumsum) of the costs and the payments. Then you can sort them increasingly and try to propagate the Payment and Project accordingly.

```<code>project_cost['accum'] = project_cost['Cost'].cumsum()
payment['accum'] = payment['Value'].cumsum()

(payment.merge(project_cost, on='accum', how='outer')
    .sort_values('accum')
    .bfill()
)
</code>```

Output:

```<code>    Payment  Value  accum   Project   Cost
0  payment1  100.0    100  Project1  200.0
3  payment2  200.0    200  Project1  200.0
1  payment2  200.0    300  Project2  300.0
4  payment3  300.0    500  Project2  300.0
2  payment3  300.0    600  Project3  400.0
5       NaN    NaN    900  Project3  400.0
</code>```

Body:
I have the following dataframe:
payment is the line of payment name with value

payment = pd.DataFrame({'Payment':["payment1","payment2","payment3"],'Value':[100,200,300]})

Payment     Value
payment1    100
payment2    200
payment3    300

and project_cost is the line of project name with their cost

project_cost = pd.DataFrame({'Project':["Project1","Project2","Project3"],'Cost':[200,300,400]})

Project        Cost
Project1       200
Project2       300
Project3       400

I basically want to match the payment with the project.

How can I get the following dataframe?

Project     Cost      Payment
Project1     100      payment1
Project1     100      payment2
Project2     100      payment2
Project2     200      payment3
Project3     100      payment3
Project3     300

The last row of payment left empty because there is a deficit of payment to pay the project.

Is there anything I can do in the pandas to get this result?
Thanks a lot

The following is the logic of my dataframe:

The payment is broken down to match with the project.

Body:
The following seems to work for the sample data. You should check it a little more. The idea is that you compute the accumulation (cumsum) of the costs and the payments. Then you can sort them increasingly and try to propagate the Payment and Project accordingly.

project_cost['accum'] = project_cost['Cost'].cumsum()
payment['accum'] = payment['Value'].cumsum()

(payment.merge(project_cost, on='accum', how='outer')
    .sort_values('accum')
    .bfill()
)

Output:

    Payment  Value  accum   Project   Cost
0  payment1  100.0    100  Project1  200.0
3  payment2  200.0    200  Project1  200.0
1  payment2  200.0    300  Project2  300.0
4  payment3  300.0    500  Project2  300.0
2  payment3  300.0    600  Project3  400.0
5       NaN    NaN    900  Project3  400.0


问:
How do i type file name and press enter for uploading file while using selenium
first week coding. I am creating a programme in python to automatically upload invoices into a job management system. I am using selenium to navigate through webpages and click upload. i am prompt with the upload file box and all i want to do is type the file name and press enter.

The upload file box opens and is ready for me to type how do i do this then carry on using selenium?

答:
You have to find <input type="file"> and use sendkeys("/path/filename") without click() on this element. And later click button which sends it.

```<code>import selenium.webdriver

driver = selenium.webdriver.Firefox()
driver.get('http://the-internet.herokuapp.com/upload')

filename = '/full/path/to/file'

driver.find_element_by_id('file-upload').send_keys(filename)
driver.find_element_by_id('file-submit').click()
</code>```

Body:
You have to find <input type="file"> and use sendkeys("/path/filename") without click() on this element. And later click button which sends it.

import selenium.webdriver

driver = selenium.webdriver.Firefox()
driver.get('http://the-internet.herokuapp.com/upload')

filename = '/full/path/to/file'

driver.find_element_by_id('file-upload').send_keys(filename)
driver.find_element_by_id('file-submit').click()


问:
Is the natural replacement for Spark (Direct) Streaming either Spark Structured Streaming or Kafka Streams?
Over the past few years we have developed quite some Spark Streaming (Direct API) applications that are reading or writing to/from Kafka, IBM MQ, Hive, HBase, HDFS, and others on our Cloudera Platform. Now that the Direct API of Spark Streaming (we currently have version 2.3.2) is deprecated and we recently added the Confluent platform (comes with Kafka 2.2.0) to our project we plan to migrate these applications.

What is the natural replacement of our Spark Streaming applications? Should we migrate to Spark Structured Streaming or rather to Kafka Streams?

I personally do not have any experience with both frameworks but in my view Spark Structured Streaming seems to be the natural choice. Our code base is mainly written in Scala which could be also used for the Structured API. Kafka Streams has a few limitations with Scala. Although we might loose some flexibility by leaving the low level API of RDDs and moving to a higher level of DataFrames we could build on our knowledge with Spark.

On the other side there is Kafka Streams which is probably the best choice when it comes to processing data between Kafka topics which is our main use case. And looking at all the Kafka Connectors that come with Confluent the other uses cases can be served as well.

答:
You currently have some Spark scheduler, therefore you can use Structured Streaming, which is binary compatible with the old Streaming API.

If you're using Mesos or k8s, then putting Kafka Streams apps in Docker and running those is easier to scale, monitor and configure than Spark, IMO since it acts as any other Docker container in those systems, so you build a pattern around everything

Kafka Streams... is probably the best choice when it comes to processing data between Kafka topics

True.

Kafka Streams has a few limitations with Scala.

I think you might want to keep reading that section

The Kafka Streams DSL for Scala library is a wrapper over the existing Java APIs for Kafka Streams DSL that addresses the concerns raised

Of course you could always use Kotlin to interop better with the Java API


问:
Adding the result of separate results
Thanks in advance for any replies. I am new to JavaScript and have got this far in calculating 2 results that I require. My question is how do I add both results together?

Please see first result below:

```<code>$(document).ready(function() {
    function checkSum(e) {
        var result = 0;
        $(".checksum").each(function() {
            var i = 0;
            if ($(this).val() != "") {
                i = parseFloat($(this).val());
            }

            result = result + i;
        });
        $("#resultsum").html(result * 60.60);
    }

    checkSum();
    $(".checksum").bind("keyup", checkSum);

});
</code>```

and this is the second:

```<code>$(document).ready(function() {

    function checkSum2(e) {
        var result2 = 0;
        $(".checksum2").each(function() {
            var j = 0;
            if ($(this).val() != "") {
                j = parseFloat($(this).val());
            }

            result2 = result2 + j;
        });
        $("#resultsum2").html(result2 * 14.88);
    }
    checkSum2();
    $(".checksum2").bind("keyup", checkSum2);

});
</code>```

答:
I've combined your snippets in to one to remove the redundant code you have. This approach will allow you to add more checksums in future (.checksum3?) and also makes sure your calculation logic is same for all.

The result is calculated in to new element whenever any of the checksums change. Try the snippet below:

// function to calculate checksum
// used for both individual results as well as for total
function calcChecksum(elements) {
  let result = 0;
  elements.each( function(index, ele) {
      result = result + (parseFloat($(ele).val()) || 0)
  });
  return result;
}

// update total result
function updateTotal() {
  let total = calcChecksum($('.result'));
  $('#resultsum_total').val(total);
}

$(document).ready(function() {
  // generate function for each set of checksum inputs
  function genCheckSumFn(inputSel, outputSel, multiplier) {
    return () => {
      const result = calcChecksum($(inputSel));
      $(outputSel).val(result * multiplier);
      updateTotal();
    }
  }

    //checkSum bindings
    $(".checksum").bind("keyup",
      genCheckSumFn('.checksum','#resultsum',60.60)
    );

    $(".checksum2").bind("keyup",
      genCheckSumFn('.checksum2','#resultsum2',14.88)
    );

    // trigger initial calculation
    $(".checksum").trigger('keyup');
    $(".checksum2").trigger('keyup');
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.checksum,
.checksum2{
 display: block;
}

.box {
  padding:10px 0px;
}

.box div {
  margin-top:5px;
}

.box.results input {
 color: #FFA500;
 border:0px;
 font-size: 14px;
}</code>```

  Checksum
  <input class="checksum" value="10">
  <input class="checksum" value="5">
  Checksum(2)
  <input class="checksum2" value="20">
  <input class="checksum2" value="15">

 Resultsum:
  <input id="resultsum" class="result" readonly>

 Resultsum(2):
  <input id="resultsum2" class="result" readonly>

 Resultsum(Total): <input id="resultsum_total" readonly>

```

Title: Adding the result of separate results

Body:
Thanks in advance for any replies. I am new to JavaScript and have got this far in calculating 2 results that I require. My question is how do I add both results together?

Please see first result below:

$(document).ready(function() {
    function checkSum(e) {
        var result = 0;
        $(".checksum").each(function() {
            var i = 0;
            if ($(this).val() != "") {
                i = parseFloat($(this).val());
            }

            result = result + i;
        });
        $("#resultsum").html(result * 60.60);
    }

    checkSum();
    $(".checksum").bind("keyup", checkSum);

});

and this is the second:

$(document).ready(function() {

    function checkSum2(e) {
        var result2 = 0;
        $(".checksum2").each(function() {
            var j = 0;
            if ($(this).val() != "") {
                j = parseFloat($(this).val());
            }

            result2 = result2 + j;
        });
        $("#resultsum2").html(result2 * 14.88);
    }
    checkSum2();
    $(".checksum2").bind("keyup", checkSum2);

});

Body:
I've combined your snippets in to one to remove the redundant code you have. This approach will allow you to add more checksums in future (.checksum3?) and also makes sure your calculation logic is same for all.

The result is calculated in to new element whenever any of the checksums change. Try the snippet below:

// function to calculate checksum
// used for both individual results as well as for total
function calcChecksum(elements) {
  let result = 0;
  elements.each( function(index, ele) {
      result = result + (parseFloat($(ele).val()) || 0)
  });
  return result;
}

// update total result
function updateTotal() {
  let total = calcChecksum($('.result'));
  $('#resultsum_total').val(total);
}

$(document).ready(function() {
  // generate function for each set of checksum inputs
  function genCheckSumFn(inputSel, outputSel, multiplier) {
    return () => {
      const result = calcChecksum($(inputSel));
      $(outputSel).val(result * multiplier);
      updateTotal();
    }
  }

    //checkSum bindings
    $(".checksum").bind("keyup",
      genCheckSumFn('.checksum','#resultsum',60.60)
    );

    $(".checksum2").bind("keyup",
      genCheckSumFn('.checksum2','#resultsum2',14.88)
    );

    // trigger initial calculation
    $(".checksum").trigger('keyup');
    $(".checksum2").trigger('keyup');
});

.checksum,
.checksum2{
 display: block;
}

.box {
  padding:10px 0px;
}

.box div {
  margin-top:5px;
}

.box.results input {
 color: #FFA500;
 border:0px;
 font-size: 14px;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="box">
  Checksum
  <input class="checksum" value="10">
  <input class="checksum" value="5">
  Checksum(2)
  <input class="checksum2" value="20">
  <input class="checksum2" value="15">
<div>
<div class="box results">
<div> Resultsum:
  <input id="resultsum" class="result" readonly>  </div>
<div> Resultsum(2):
  <input id="resultsum2" class="result" readonly> </div>
<div> Resultsum(Total): <input id="resultsum_total" readonly> </div>
</div>


问:
mysql in clause vs multiple delete with one commit
I have about 100K records that I have to run for the following query:

```<code>delete from users where name in #{String}
</code>```

where the string could be 100K strings of this form: Joe,Kate etc.

For performance is it better to run the above statement or delete one record in a loop with one session.commit(); in the end?

EDITED

There could be only one record for each value

答:
If you can create batches of queries to run then breaking it up into batches would most likely be the fastest:

```<code>delete from users where name in ('name1','name2','name3',.....'nameX');

delete from users where name in ('nameX+1','nameX+2','nameX+3',.....'nameX+X');
</code>```

etc..

If you have the names in a table already you can just do this:

```<code>delete from users where name in (select name from table_with_names_to_be_deleted)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have about 100K records that I have to run for the following query:

delete from users where name in #{String}

where the string could be 100K strings of this form: Joe,Kate etc.

For performance is it better to run the above statement or delete one record in a loop with one session.commit(); in the end?

EDITED

There could be only one record for each value

Body:
If you can create batches of queries to run then breaking it up into batches would most likely be the fastest:

delete from users where name in ('name1','name2','name3',.....'nameX');

delete from users where name in ('nameX+1','nameX+2','nameX+3',.....'nameX+X');

etc..

If you have the names in a table already you can just do this:

delete from users where name in (select name from table_with_names_to_be_deleted)


问:
Mongo's stats not showing on munin
I'm trying to add a MongoDB's plugin to munin. I followed this to install the plugin:

```<code>sudo apt-get install git munin-node
git clone git://github.com/erh/mongo-munin.git /home/ubuntu/mongo-munin
sudo ln -sf /home/ubuntu/mongo-munin/mongo_btree /etc/munin/plugins/mongo_btree
sudo ln -sf /home/ubuntu/mongo-munin/mongo_conn /etc/munin/plugins/mongo_conn
sudo ln -sf /home/ubuntu/mongo-munin/mongo_lock /etc/munin/plugins/mongo_lock
sudo ln -sf /home/ubuntu/mongo-munin/mongo_mem /etc/munin/plugins/mongo_mem
sudo ln -sf /home/ubuntu/mongo-munin/mongo_ops /etc/munin/plugins/mongo_ops
sudo service munin-node restart
</code>```

(from https://ivan-site.com/2013/06/monitoring-mongodb-in-munin-on-ubuntu-1304)

But nothing was sent to munin's server (for Mongo only, all other date from the server are ok on Munin).

Then I found there is an error when runing the plugin:

```<code># sudo -u munin python /usr/share/munin/plugins/mongo_ops
Traceback (most recent call last):
  File "/usr/share/munin/plugins/mongo_ops", line 56, in <module>
    doData()
  File "/usr/share/munin/plugins/mongo_ops", line 33, in doData
    ss = getServerStatus()
  File "/usr/share/munin/plugins/mongo_ops", line 28, in getServerStatus
    raw = urllib2.urlopen(req).read()
  File "/usr/lib/python2.7/urllib2.py", line 126, in urlopen
    return _opener.open(url, data, timeout)
  File "/usr/lib/python2.7/urllib2.py", line 400, in open
    response = self._open(req, data)
  File "/usr/lib/python2.7/urllib2.py", line 418, in _open
    '_open', req)
  File "/usr/lib/python2.7/urllib2.py", line 378, in _call_chain
    result = func(*args)
  File "/usr/lib/python2.7/urllib2.py", line 1207, in http_open
    return self.do_open(httplib.HTTPConnection, req)
  File "/usr/lib/python2.7/urllib2.py", line 1177, in do_open
    raise URLError(err)
urllib2.URLError: <urlopen error [Errno 111] Connection refused>
</code>```

I've checked this question: Munin Mongodb Plugin Not Showing. . .? but the problem is not the same, I'm running pyhton 2, as seen in the output above:

```<code>File "/usr/lib/python2.7/urllib2.py", line 126, in urlopen
</code>```

And so, plugins are active:

```<code># munin-node-configure | grep "mongo"
mongo_btree                | yes   |
mongo_conn                 | yes   |
mongo_lock                 | yes   |
mongo_mem                  | yes   |
mongo_ops                  | yes   |
</code>```

Is it a permission from Mongo? Maybe I need to setup a user for Munin? Do you have any idea how to fix that?

答:
This seems broken or not working when using credentials:

```<code>$ munin-run -d mongo_docs
# Processing plugin configuration from /etc/munin/plugin-conf.d/munin-node
# Setting /rgid/ruid/ to /126/65534/
# Setting /egid/euid/ to /126 126/65534/
# Setting up environment
# Environment MONGO_DB_URI = mongodb://MY_USER:MY_PASSWORD@localhost:27017/admin
# About to run '/etc/munin/plugins/mongo_docs'
Traceback (most recent call last):
  File "/etc/munin/plugins/mongo_docs", line 53, in <module>
    doData()
  File "/etc/munin/plugins/mongo_docs", line 20, in doData
    ss = getServerStatus()
  File "/etc/munin/plugins/mongo_docs", line 14, in getServerStatus
    return c.admin.command('serverStatus', workingSet=True)
  File "/usr/local/lib/python2.7/dist-packages/pymongo/database.py", line 733, in command
    codec_options, session=session, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/pymongo/database.py", line 630, in _command
    client=self.__client)
  File "/usr/local/lib/python2.7/dist-packages/pymongo/pool.py", line 613, in command
    user_fields=user_fields)
  File "/usr/local/lib/python2.7/dist-packages/pymongo/network.py", line 167, in command
    parse_write_concern_error=parse_write_concern_error)
  File "/usr/local/lib/python2.7/dist-packages/pymongo/helpers.py", line 159, in _check_command_response
    raise OperationFailure(msg % errmsg, code, response)
pymongo.errors.OperationFailure: not authorized on admin to execute command { serverStatus: 1, workingSet: true, $db: "admin", $readPreference: { mode: "primaryPreferred" } }
</code>```

But works fine when executing manually:

```<code>$ mongo -u MY_USER admin --eval 'db.serverStatus().metrics.document'
MongoDB shell version v3.6.16
Enter password:
connecting to: mongodb://127.0.0.1:27017/admin?gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("b2d5afa5-8bc9-4ed7-9a6e-a52e8d660876") }
MongoDB server version: 3.6.15
{
    "deleted" : NumberLong(1137),
    "inserted" : NumberLong(342220),
    "returned" : NumberLong(3429651),
    "updated" : NumberLong(1364343)
}
$
</code>```

Probably pymongo bug?

Another two that are failing due to missing keys:

```<code>$ munin-run mongo_btree
Traceback (most recent call last):
  File "/etc/munin/plugins/mongo_btree", line 59, in <module>
    doData()
  File "/etc/munin/plugins/mongo_btree", line 22, in doData
    for k,v in get().iteritems():
  File "/etc/munin/plugins/mongo_btree", line 19, in get
    return getServerStatus()["indexCounters"]
KeyError: 'indexCounters'

$  munin-run mongo_lock
Traceback (most recent call last):
  File "/etc/munin/plugins/mongo_lock", line 52, in <module>
    doData()
  File "/etc/munin/plugins/mongo_lock", line 21, in doData
    print name + ".value " + str( 100 * (getServerStatus()["globalLock"]["lockTime"]/getServerStatus()["globalLock"]["totalTime"]) )
KeyError: 'lockTime'
</code>```

Title: Mongo's stats not showing on munin

Body:
I'm trying to add a MongoDB's plugin to munin. I followed this to install the plugin:

sudo apt-get install git munin-node
git clone git://github.com/erh/mongo-munin.git /home/ubuntu/mongo-munin
sudo ln -sf /home/ubuntu/mongo-munin/mongo_btree /etc/munin/plugins/mongo_btree
sudo ln -sf /home/ubuntu/mongo-munin/mongo_conn /etc/munin/plugins/mongo_conn
sudo ln -sf /home/ubuntu/mongo-munin/mongo_lock /etc/munin/plugins/mongo_lock
sudo ln -sf /home/ubuntu/mongo-munin/mongo_mem /etc/munin/plugins/mongo_mem
sudo ln -sf /home/ubuntu/mongo-munin/mongo_ops /etc/munin/plugins/mongo_ops
sudo service munin-node restart

(from https://ivan-site.com/2013/06/monitoring-mongodb-in-munin-on-ubuntu-1304)

But nothing was sent to munin's server (for Mongo only, all other date from the server are ok on Munin).

Then I found there is an error when runing the plugin:

# sudo -u munin python /usr/share/munin/plugins/mongo_ops
Traceback (most recent call last):
  File "/usr/share/munin/plugins/mongo_ops", line 56, in <module>
    doData()
  File "/usr/share/munin/plugins/mongo_ops", line 33, in doData
    ss = getServerStatus()
  File "/usr/share/munin/plugins/mongo_ops", line 28, in getServerStatus
    raw = urllib2.urlopen(req).read()
  File "/usr/lib/python2.7/urllib2.py", line 126, in urlopen
    return _opener.open(url, data, timeout)
  File "/usr/lib/python2.7/urllib2.py", line 400, in open
    response = self._open(req, data)
  File "/usr/lib/python2.7/urllib2.py", line 418, in _open
    '_open', req)
  File "/usr/lib/python2.7/urllib2.py", line 378, in _call_chain
    result = func(*args)
  File "/usr/lib/python2.7/urllib2.py", line 1207, in http_open
    return self.do_open(httplib.HTTPConnection, req)
  File "/usr/lib/python2.7/urllib2.py", line 1177, in do_open
    raise URLError(err)
urllib2.URLError: <urlopen error [Errno 111] Connection refused>

I've checked this question: Munin Mongodb Plugin Not Showing. . .? but the problem is not the same, I'm running pyhton 2, as seen in the output above:

File "/usr/lib/python2.7/urllib2.py", line 126, in urlopen

And so, plugins are active:

# munin-node-configure | grep "mongo"
mongo_btree                | yes   |
mongo_conn                 | yes   |
mongo_lock                 | yes   |
mongo_mem                  | yes   |
mongo_ops                  | yes   |

Is it a permission from Mongo? Maybe I need to setup a user for Munin? Do you have any idea how to fix that?

Body:
This seems broken or not working when using credentials:

$ munin-run -d mongo_docs
# Processing plugin configuration from /etc/munin/plugin-conf.d/munin-node
# Setting /rgid/ruid/ to /126/65534/
# Setting /egid/euid/ to /126 126/65534/
# Setting up environment
# Environment MONGO_DB_URI = mongodb://MY_USER:MY_PASSWORD@localhost:27017/admin
# About to run '/etc/munin/plugins/mongo_docs'
Traceback (most recent call last):
  File "/etc/munin/plugins/mongo_docs", line 53, in <module>
    doData()
  File "/etc/munin/plugins/mongo_docs", line 20, in doData
    ss = getServerStatus()
  File "/etc/munin/plugins/mongo_docs", line 14, in getServerStatus
    return c.admin.command('serverStatus', workingSet=True)
  File "/usr/local/lib/python2.7/dist-packages/pymongo/database.py", line 733, in command
    codec_options, session=session, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/pymongo/database.py", line 630, in _command
    client=self.__client)
  File "/usr/local/lib/python2.7/dist-packages/pymongo/pool.py", line 613, in command
    user_fields=user_fields)
  File "/usr/local/lib/python2.7/dist-packages/pymongo/network.py", line 167, in command
    parse_write_concern_error=parse_write_concern_error)
  File "/usr/local/lib/python2.7/dist-packages/pymongo/helpers.py", line 159, in _check_command_response
    raise OperationFailure(msg % errmsg, code, response)
pymongo.errors.OperationFailure: not authorized on admin to execute command { serverStatus: 1, workingSet: true, $db: "admin", $readPreference: { mode: "primaryPreferred" } }

But works fine when executing manually:

$ mongo -u MY_USER admin --eval 'db.serverStatus().metrics.document'
MongoDB shell version v3.6.16
Enter password:
connecting to: mongodb://127.0.0.1:27017/admin?gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("b2d5afa5-8bc9-4ed7-9a6e-a52e8d660876") }
MongoDB server version: 3.6.15
{
    "deleted" : NumberLong(1137),
    "inserted" : NumberLong(342220),
    "returned" : NumberLong(3429651),
    "updated" : NumberLong(1364343)
}
$

Probably pymongo bug?

Another two that are failing due to missing keys:

$ munin-run mongo_btree
Traceback (most recent call last):
  File "/etc/munin/plugins/mongo_btree", line 59, in <module>
    doData()
  File "/etc/munin/plugins/mongo_btree", line 22, in doData
    for k,v in get().iteritems():
  File "/etc/munin/plugins/mongo_btree", line 19, in get
    return getServerStatus()["indexCounters"]
KeyError: 'indexCounters'

$  munin-run mongo_lock
Traceback (most recent call last):
  File "/etc/munin/plugins/mongo_lock", line 52, in <module>
    doData()
  File "/etc/munin/plugins/mongo_lock", line 21, in doData
    print name + ".value " + str( 100 * (getServerStatus()["globalLock"]["lockTime"]/getServerStatus()["globalLock"]["totalTime"]) )
KeyError: 'lockTime'


问:
Tasks should show up only if the user has been assigned it
I only want the person who I have assigned the task to see the task in the project module. I don't want other users of the project to see this persons tasks.

However currently any user who has user access rights can see all the tasks even if they were not assigned it.

Is there a work around this ?

答:
My problem was a bit more complex. I wanted to have users who can only their assigned tasks and some who can see the rest, too.

In Odoo 11 I found that the standard project user inherits Employees \ Employee which in turn has the rule Project/Task: employees: follow required for follower-only projects which let users see the other tasks.

What I did:

create a new group -> duplicate of Project / Users

implemented the rule from odony's answer -> ['|',('user_id','=',False),('user_id','=',user.id)]

removed the record rule Project/Task: employees: follow required for follower-only projects from Employees / Employee and added it to Project / Users

Now I can decide who is a project user, who can see all tasks of a project, and who is a worker, who only gets to see tasks assigned to them.


问:
Way to access stack top element to recursively compare if both stack elements are the same
How do I access the top elements of each stack so I can compare them? I used (iTop,i2Top,nTop,n2Top) because I've been testing to make this work but I can't seem to get the right output.
What am I doing wrong?

I assumed this would work, but it's not either. Basically I want to reference the top element of stack, and compare it to the top element of stack2. Then if they are equal, pop them and do the same for the rest of the stack. At the end, if the stack is empty because all elements were the same and got popped, then it's true the stacks are the same. And push back stack 1 and stack 2.
  Thank you

```<code>public Boolean sameStack(StackArray<E> s2) {
            E t1, t2;
            //E iTop = this.items[top];
            //E i2Top= s2.items[top];
            int nTop = this.top; //
            int n2Top= s2.top;  // nTop == n2Top is true even when elements are not equal
            boolean t = true;

            if(this.isEmpty() && s2.isEmpty()) {
                return t;
            }//if
            if(this.top != s2.top) {
                t = false;
                return t;
            }
            if(this.items[top] == s2.items[s2.top]){
                t1 = this.pop();
                t2 = s2.pop();
                t = sameStack(s2);
                push(t1);
                push(t2);
            }
            else{
                t = false;
            }
            return t;
}
</code>```

```<code>public class StackArray<E> {

        private int top=-1;
        private static final int MAX_ITEMS = 10;
        private E items[];

        @SuppressWarnings("unchecked")
        public StackArray() {
            items = (E[]) new Object[MAX_ITEMS];
            System.out.println("Stack Created!");
        }

        public void push(E e) {
            if (isFull()==true) {
            System.out.println("Stack Full!");
            }
            else{
                top=top+1;
                items[top] = e;
            }
        }//Push

        public E pop() {
            if (isEmpty()==true) {
                System.out.println("Stack Empty!");
                }
            else{
              E e = (E) items[top];
              items[top] = null;
              top = top-1;
              return e;
            }
            return null;
        } //pop

        public boolean isFull() {
            if (top == items.length-1) {
                return true;
            }
            return false;
        } //isFull

        public boolean isEmpty(){
            if (top==-1) {
                return true;
            }
            return false;
        }//isEmpty

        @Override
        public String toString()
        {
            System.out.println("Array:");
            System.out.print("{");
            for(int i = 0; i < items.length ;i++) {
                System.out.print(items[i]+" ");
        }
            System.out.print("}");
            return "";
        }//toString

        public Boolean sameStack(StackArray<E> s2) {
            E t1, t2;
            //E iTop = this.items[top];
            //E i2Top= s2.items[top];
            int nTop = this.top; //
            int n2Top= s2.top;  // nTop == n2Top is true even when elements are not equal
            boolean t = true;

            if(this.isEmpty() && s2.isEmpty()) {
                return t;
            }//if

            //This is the part I need to compare the elements
            if(nTop == n2Top) {
                t1 = this.pop()
                t2 = s2.pop();
//              t = sameStack(s2);
//              push(t1);
//              s2.push(t2);
            }
            return t;
        }

        public static void main(String[] args)
        {

            // Code reference for sameStack method
            StackArray<Integer> stack = new StackArray<Integer>();
            StackArray<Integer> stack2 = new StackArray<Integer>();

            stack.push(111);
            stack.push(222);
            stack.push(7177);
//          stack.push(40);
            stack2.push(444);
            stack2.push(555);
            stack2.push(777);
//          stack2.push(40);

            System.out.println(stack);
            System.out.println(stack2);

//          //Calling comparison method
            if (stack.sameStack(stack2) == true) {
                System.out.println("True, both stacks are equal.");
            }//if
            else {
                System.out.println("False, stacks are not equal.");
            }//else
            System.out.println(stack);
            System.out.println(stack2);
        }//main

}//class
</code>```

答:
Just iterate the items array and compare the elements using equals() (not ==).

```<code>public boolean sameStack(StackArray<E> s2) {
    if (this.top != s2.top) {
        return false;
    }
    for (int i = 0; i <= this.top; i++) {
        if (! this.items[i].equals(s2.items[i])) {
            return false;
        }
    }
    return true;
}
</code>```

This works, because any method of StackArray can access private members of StackArray, whether it's the current instance (this) or some other instance (e.g. s2).

Body:
How do I access the top elements of each stack so I can compare them? I used (iTop,i2Top,nTop,n2Top) because I've been testing to make this work but I can't seem to get the right output.
What am I doing wrong?

I assumed this would work, but it's not either. Basically I want to reference the top element of stack, and compare it to the top element of stack2. Then if they are equal, pop them and do the same for the rest of the stack. At the end, if the stack is empty because all elements were the same and got popped, then it's true the stacks are the same. And push back stack 1 and stack 2.
  Thank you

public Boolean sameStack(StackArray<E> s2) {
            E t1, t2;
            //E iTop = this.items[top];
            //E i2Top= s2.items[top];
            int nTop = this.top; //
            int n2Top= s2.top;  // nTop == n2Top is true even when elements are not equal
            boolean t = true;

            if(this.isEmpty() && s2.isEmpty()) {
                return t;
            }//if
            if(this.top != s2.top) {
                t = false;
                return t;
            }
            if(this.items[top] == s2.items[s2.top]){
                t1 = this.pop();
                t2 = s2.pop();
                t = sameStack(s2);
                push(t1);
                push(t2);
            }
            else{
                t = false;
            }
            return t;
}

public class StackArray<E> {

        private int top=-1;
        private static final int MAX_ITEMS = 10;
        private E items[];

        @SuppressWarnings("unchecked")
        public StackArray() {
            items = (E[]) new Object[MAX_ITEMS];
            System.out.println("Stack Created!");
        }

        public void push(E e) {
            if (isFull()==true) {
            System.out.println("Stack Full!");
            }
            else{
                top=top+1;
                items[top] = e;
            }
        }//Push

        public E pop() {
            if (isEmpty()==true) {
                System.out.println("Stack Empty!");
                }
            else{
              E e = (E) items[top];
              items[top] = null;
              top = top-1;
              return e;
            }
            return null;
        } //pop

        public boolean isFull() {
            if (top == items.length-1) {
                return true;
            }
            return false;
        } //isFull

        public boolean isEmpty(){
            if (top==-1) {
                return true;
            }
            return false;
        }//isEmpty

        @Override
        public String toString()
        {
            System.out.println("Array:");
            System.out.print("{");
            for(int i = 0; i < items.length ;i++) {
                System.out.print(items[i]+" ");
        }
            System.out.print("}");
            return "";
        }//toString

        public Boolean sameStack(StackArray<E> s2) {
            E t1, t2;
            //E iTop = this.items[top];
            //E i2Top= s2.items[top];
            int nTop = this.top; //
            int n2Top= s2.top;  // nTop == n2Top is true even when elements are not equal
            boolean t = true;

            if(this.isEmpty() && s2.isEmpty()) {
                return t;
            }//if

            //This is the part I need to compare the elements
            if(nTop == n2Top) {
                t1 = this.pop()
                t2 = s2.pop();
//              t = sameStack(s2);
//              push(t1);
//              s2.push(t2);
            }
            return t;
        }

        public static void main(String[] args)
        {

            // Code reference for sameStack method
            StackArray<Integer> stack = new StackArray<Integer>();
            StackArray<Integer> stack2 = new StackArray<Integer>();

            stack.push(111);
            stack.push(222);
            stack.push(7177);
//          stack.push(40);
            stack2.push(444);
            stack2.push(555);
            stack2.push(777);
//          stack2.push(40);

            System.out.println(stack);
            System.out.println(stack2);

//          //Calling comparison method
            if (stack.sameStack(stack2) == true) {
                System.out.println("True, both stacks are equal.");
            }//if
            else {
                System.out.println("False, stacks are not equal.");
            }//else
            System.out.println(stack);
            System.out.println(stack2);
        }//main

}//class

Body:
Just iterate the items array and compare the elements using equals() (not ==).

public boolean sameStack(StackArray<E> s2) {
    if (this.top != s2.top) {
        return false;
    }
    for (int i = 0; i <= this.top; i++) {
        if (! this.items[i].equals(s2.items[i])) {
            return false;
        }
    }
    return true;
}

This works, because any method of StackArray can access private members of StackArray, whether it's the current instance (this) or some other instance (e.g. s2).


问:
Is there a way of using PayPal sandbox when testing Neto checkout?
I need to test the paypal payment system under Neto ecommerce. I have setup paypal sandbox and it works fine when used directly. It appears that Neto  is hard wired to only connect to "paypal.com" whereas the sandbox needs "sandbox.paypal.com" - I am not at all keen test the Paypal payments live!!   Can anyone confirm this?</p>

答: Yes, you can. Look in Advanced Configuration and search for paypal and you'll see the settings you need to change.


问:
Are Spring/Micronaut repository tests necessary
Hello stackoverflow community.

I had an argument at work regarding if repository tests for spring-data JPA (or the Micronaut version) are necessary at all.

This would be my setup of the application:

@Controller ➡ @Service/@Sigleton ➡ Repository<Entity>

in my service tests I'd use the @ExtendWith(SpringExtension::class) extension (Junit5)

when creating the test setup, I'd @MockBean away other systems I need to call (like REST-APIs) but @Autowire my Repository's.
When setting up my test data I'd simply save my required entities into an H2 in-memory database by using the injected repositories.

This will test my database logic and business logic as well. In case of 100% test coverage I've tested all the database calls which can happen in production.

However what I usually see in projects is that the Repository is mocked away.
To test the custom repository calls there are separate Tests to make sure the repository functions work as expected.

What are your comments on this. Do you prefer the approach without repository mocks or with and why?

答:
I have no experience with Micronaut, but I believe my answer will apply to both of the frameworks:

There are different types of integration tests supported by spring for example.
Basically the fact that you're running a spring context in the test, already means that its more than a unit test. In general the Spring test package is for integration tests.

Now in Spring there are annotations like @DataJpaTest, @WebMvcTest. They create a "slice" of application context loading only necessary beans, and mocking / omitting others. For example, in @WebMvcTest the JPA repositories are anot loaded at all.

You can also create your own slices.

Now If you want to check your rest layer (Controller is defined correctly, request is validated in a proper way, upon the request you're getting a response in a proper format and so forth) you can use @WebMvcTest.

If you want to test that the sql queries are correct - that you can use @DataJpaTest (assuming you work with JPA / Spring Data of course).

Now, If you want to test service logic, sometimes you don't even need an integration test (loading spring context) since you can run a unit test for services and mock out the repository calls or calls to external services if you have those.

Regarding the H2 approach. While people use it for testing their DB layer (SQL queries), sometimes it doesn't work exactly like your database in production. This means that sometimes you can't really run the same SQL query in tests. For these cases I recommend TestContainers project: run the Docker image of your db on startup of the test and stop the image after the test ends.

Update

Based on OP's comment:

lot of the 'mysql query' is already been taken care of by the framework, so why should I explicitly test the repository

This is subjective, but let me put it this way: Tests are a tool to gain a confidence a code for developer first of all.
If the developer wants to be sure that the query behaves as expected then the test is a tool that can help. Specifically regarding Queries: Maybe the query is just wrong, maybe its a native query that should be checked anyway. Maybe there are many queries that run one after another. Its only up to you to decide.

Is it worth it to write Unit tests for services?

Well, this depends on what do the services actually do.
If they run a complicated algorithm that can't be easily checked by integration tests (like service requires various mocks in various cases) then unit tests for services can be done.

Besides, in general, unit tests are way faster than Spring's tests. So (again subjective) my personal rule is: if you can gain the confidence in code with unit test - do it. If you need to check integration - go for integration test.


问:
read laravel object and get data
I am trying to read laravel object and assign  that into a new variable I have no idea to do that please someone help

THIS IS MY FUNCTION

```<code>public function nextToJumpGrs(CompetitionService $competitionService, CachedEventResourceService $cachedEventResourceService, ConfigurationRepositoryInterface $configurationRepository,MarketRepository $marketTypeRepository)
{

   $nextToJump = $cachedEventResourceService->nextToJump();
   $markets=array();

   $config = $configurationRepository->getConfigByName('sports_settings', true);
   $competitions = $competitionService->getCompetitionsByN2JEventResourcesGrs($nextToJump->slice(0, array_get($config, 'next_to_jump_events')));

  return $competitions;
   }

}
</code>```

this is what $competitions return

I want to read those markets[] and products[]  and assign to another variable  please someone help

答:
Just typecast it

```<code>$array = (array) $competitions;
</code>```

Then loop through it

```<code>$markets = [];
$products = [];

foreach($array as $item) {
  dump($item['id']);
  dump($item['name']);
  //...
  foreach($item['events'] as $event) {
    dump($event['id']);
    dump($event['name']);
    //...
    $markets[$item['id']][] = $event['markets'];
    foreach($event['markets'] as $market) {
      dump($market['id']);
      dump($market['name']);
      dump($market['line']);
      //...
    }
    $products[$item['id']][] = $event['products'];
    foreach($event['products'] as $product) {
      dump($product['product_id']);
      dump($product['bet_type']);
      dump($product['product_code']);
      //...
    }
  }
}
</code>```

Title: read laravel object and get data

Body:
I am trying to read laravel object and assign  that into a new variable I have no idea to do that please someone help

THIS IS MY FUNCTION

public function nextToJumpGrs(CompetitionService $competitionService, CachedEventResourceService $cachedEventResourceService, ConfigurationRepositoryInterface $configurationRepository,MarketRepository $marketTypeRepository)
{

   $nextToJump = $cachedEventResourceService->nextToJump();
   $markets=array();

   $config = $configurationRepository->getConfigByName('sports_settings', true);
   $competitions = $competitionService->getCompetitionsByN2JEventResourcesGrs($nextToJump->slice(0, array_get($config, 'next_to_jump_events')));

  return $competitions;
   }

}

this is what $competitions return

I want to read those markets[] and products[]  and assign to another variable  please someone help

Body:
Just typecast it

$array = (array) $competitions;

Then loop through it

$markets = [];
$products = [];

foreach($array as $item) {
  dump($item['id']);
  dump($item['name']);
  //...
  foreach($item['events'] as $event) {
    dump($event['id']);
    dump($event['name']);
    //...
    $markets[$item['id']][] = $event['markets'];
    foreach($event['markets'] as $market) {
      dump($market['id']);
      dump($market['name']);
      dump($market['line']);
      //...
    }
    $products[$item['id']][] = $event['products'];
    foreach($event['products'] as $product) {
      dump($product['product_id']);
      dump($product['bet_type']);
      dump($product['product_code']);
      //...
    }
  }
}


问:
How to display one field from a JSON in node
I have this JSON file:

```<code>[
  {
    _id: 5e4b1213e666de6628044139,
    product: 'air-jordan-1-retro-high-unc-chicago-leather-w'
  },
  {
    _id: 5e4b121de666de662804413a,
    product: 'nike-air-force-1-high-just-don-blue'
  },
  {
    _id: 5e4b1227e666de662804413b,
    product: 'air-jordan-new-beginnings-pack-1-nike-air-ship'
  },
  {
    _id: 5e4b1246e666de662804413c,
    product: 'nike-sb-dunk-low-strangelove-skateboards'
  }
]
</code>```

I'd like to list all of the products all in one string. I noticed i can do docs[1].product but i want to do this for any amount.

I tried to do docs.product but the output is undefined

what i want is:

```<code>air-jordan-1-retro-high-unc-chicago-leather-w
nike-air-force-1-high-just-don-blue
air-jordan-new-beginnings-pack-1-nike-air-ship
nike-sb-dunk-low-strangelove-skateboards
</code>```

答:
Use the map method and join method with required separator.

const data = [
  {
    _id: "5e4b1213e666de6628044139",
    product: "air-jordan-1-retro-high-unc-chicago-leather-w"
  },
  {
    _id: "5e4b121de666de662804413a",
    product: "nike-air-force-1-high-just-don-blue"
  },
  {
    _id: "5e4b1227e666de662804413b",
    product: "air-jordan-new-beginnings-pack-1-nike-air-ship"
  },
  {
    _id: "5e4b1246e666de662804413c",
    product: "nike-sb-dunk-low-strangelove-skateboards"
  }
];

const productsLine = (data, seperator = "\r\n") =>
  data.map(x => x.product).join(seperator);

console.log(productsLine(data));
console.log(productsLine(data, ", "));```

Body:
I have this JSON file:

[
  {
    _id: 5e4b1213e666de6628044139,
    product: 'air-jordan-1-retro-high-unc-chicago-leather-w'
  },
  {
    _id: 5e4b121de666de662804413a,
    product: 'nike-air-force-1-high-just-don-blue'
  },
  {
    _id: 5e4b1227e666de662804413b,
    product: 'air-jordan-new-beginnings-pack-1-nike-air-ship'
  },
  {
    _id: 5e4b1246e666de662804413c,
    product: 'nike-sb-dunk-low-strangelove-skateboards'
  }
]

I'd like to list all of the products all in one string. I noticed i can do docs[1].product but i want to do this for any amount.

I tried to do docs.product but the output is undefined

what i want is:

air-jordan-1-retro-high-unc-chicago-leather-w
nike-air-force-1-high-just-don-blue
air-jordan-new-beginnings-pack-1-nike-air-ship
nike-sb-dunk-low-strangelove-skateboards


问:
React : Uncaught TypeError: Cannot read property 'i' of undefined
I have a problem with my code:

```<code>class Albs extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      i: 0,
      anh: this.props.hinhanh[this.state.i]
    };
    var hinhanh = ["1.png", "2.png", "3.png"];
    this.state.i = this.state.i.bind(this);
  }
  nextPic(){
    this.setState({i: this.state.i++});
  }
  backPic(){
    this.setState({i: this.state.i--});
  }
  render(){
    return(
      <div>
        <img src={this.state.anh}/>
        <br/>
        <button onClick={nextPic}>Next</button>
        <button onClick={backPic}>Back</button>
      </div>
    )
  }
}

ReactDOM.render(
  <Albs/>,
  document.getElementById('root')
);
</code>```

In console it shows: Uncaught TypeError: Cannot read property 'i' of undefined. Reason please?

答:
There are lots of mistakes you made, look at my code and compare yours. Hope you can find the error.

```<code>class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      i: 0
    };
    var hinhanh = ["1.png", "2.png", "3.png"];
    this.nextPic = this.nextPic.bind(this);
    this.backPic = this.backPic.bind(this);
  }

  componentDidMount() {
    this.setState({ anh: this.state.i});
  }

  nextPic() {
    this.setState({ i: this.state.i++ });
    console.log(this.state.i);
  }
  backPic() {
    this.setState({ i: this.state.i-- });
    console.log(this.state.i);
  }
  render(){
    return(
      <div>
        <img src={this.state.anh}/>
        <br/>
        <button onClick={this.nextPic}>Next</button>
        <button onClick={this.backPic}>Back</button>
      </div>
    )
  }
}
</code>```

You can define state property immediately into state like this this.state = { i: 0, j: this.state.i}, herejis undefined. So you need to use life cycle methodcomponentDidMounttosetState`.

You need to bind your functions, otherwise you need to use arrow function like this, nextPic = () => {//function defination}

Body:
I have a problem with my code:

class Albs extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      i: 0,
      anh: this.props.hinhanh[this.state.i]
    };
    var hinhanh = ["1.png", "2.png", "3.png"];
    this.state.i = this.state.i.bind(this);
  }
  nextPic(){
    this.setState({i: this.state.i++});
  }
  backPic(){
    this.setState({i: this.state.i--});
  }
  render(){
    return(

        <button onClick={nextPic}>Next</button>
        <button onClick={backPic}>Back</button>

    )
  }
}

ReactDOM.render(
  <Albs/>,
  document.getElementById('root')
);

In console it shows: Uncaught TypeError: Cannot read property 'i' of undefined. Reason please?

Body:
There are lots of mistakes you made, look at my code and compare yours. Hope you can find the error.

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      i: 0
    };
    var hinhanh = ["1.png", "2.png", "3.png"];
    this.nextPic = this.nextPic.bind(this);
    this.backPic = this.backPic.bind(this);
  }

  componentDidMount() {
    this.setState({ anh: this.state.i});
  }

  nextPic() {
    this.setState({ i: this.state.i++ });
    console.log(this.state.i);
  }
  backPic() {
    this.setState({ i: this.state.i-- });
    console.log(this.state.i);
  }
  render(){
    return(
      <div>
        <img src={this.state.anh}/>
        <br/>
        <button onClick={this.nextPic}>Next</button>
        <button onClick={this.backPic}>Back</button>
      </div>
    )
  }
}

You can define state property immediately into state like this this.state = { i: 0, j: this.state.i}, herejis undefined. So you need to use life cycle methodcomponentDidMounttosetState`.

You need to bind your functions, otherwise you need to use arrow function like this, nextPic = () => {//function defination}


问:
Google Data Studio REGEXP_MATCH for multiple URL variations
Just started using Google Data Studio, and ran into a problem.

We have a custom downloads report, which displays the full URL of file, and then file name; for example:

https://website.com/-/media/rak/files/productdocuments/filename.pdf

We also have files in a different location; for example:

https://website.com/-/media/rak/files/rak-library/filename.pdf

I'm trying to combine both to display in the downloads report, but with only the file name showing - we want to strip out the separate website URLs.

From trawling various websites, including this one, I've got the below CASE statement to partially work. It will run the first line, but does not seem to want to run the second line.

The Event Action field is what is displaying the full URL and file name.

I'm not 100% sure what the .* does, but it seems like a partial match, not exact? When I didn't have this in, it could not find either URLs, so presumed that REGEXP_MATCH is looking for an exact match, and I needed to not have the file name included in the path.

--

Main function

```<code>CASE
  WHEN REGEXP_MATCH(Event Action, '[https://website.com/-/media/rak/files/productdocuments/].*' ) THEN Remove TXT 01
  WHEN REGEXP_MATCH(Event Action, '[https://website.com/-/media/rak/files/rak-library/].*' ) THEN Remove TXT 02
  ELSE Event Action
END
</code>```

Remove TXT 01

```<code>REGEXP_REPLACE(Event Action, 'https://website.com/-/media/rak/files/productdocuments/', '' )
</code>```

Remove TXT 02

```<code>REGEXP_REPLACE(Event Action, 'https://website.com/-/media/rak/files/rak-library/', '' )
</code>```

--

I'm not 100% sure if it is user error, but if anyone can supply an idea as to how to get this to work, I'd be very grateful!

答:
It can be achieved by first creating the Extract_Text formula below, and then creating the Main Formula:

Formula 1: Extract_Text

```<code>REGEXP_EXTRACT(Event Action, "/([\\w-]+\\.\\w+)\\]?$")
</code>```

Formula 2: Main Formula

```<code>CASE
  WHEN REGEXP_MATCH(Event Action, "\\[?https://website\\.com/-/media/rak/files/(productdocuments|rak-library)/[\\w-]+\\.\\w+\\]?") THEN Extract_Text
  ELSE Event Action
END
</code>```

Formula Breakdown

Extract_Text: Captures a range of characters a-zA-Z0-9_- after the last / in the sequence: [characters].[characters]

Main Formula: If the pattern doesn't match, then values from the Event Action field are extracted.

Created a Google Data Studio Report (Google Sheets Embedded) to demonstrate.

  EDIT: The formula now captures - to extract product-name-01.pdf

Body:
Just started using Google Data Studio, and ran into a problem.

We have a custom downloads report, which displays the full URL of file, and then file name; for example:

https://website.com/-/media/rak/files/productdocuments/filename.pdf

We also have files in a different location; for example:

https://website.com/-/media/rak/files/rak-library/filename.pdf

I'm trying to combine both to display in the downloads report, but with only the file name showing - we want to strip out the separate website URLs.

From trawling various websites, including this one, I've got the below CASE statement to partially work. It will run the first line, but does not seem to want to run the second line.

The Event Action field is what is displaying the full URL and file name.

I'm not 100% sure what the .* does, but it seems like a partial match, not exact? When I didn't have this in, it could not find either URLs, so presumed that REGEXP_MATCH is looking for an exact match, and I needed to not have the file name included in the path.

--

Main function

CASE
  WHEN REGEXP_MATCH(Event Action, '[https://website.com/-/media/rak/files/productdocuments/].*' ) THEN Remove TXT 01
  WHEN REGEXP_MATCH(Event Action, '[https://website.com/-/media/rak/files/rak-library/].*' ) THEN Remove TXT 02
  ELSE Event Action
END

Remove TXT 01

REGEXP_REPLACE(Event Action, 'https://website.com/-/media/rak/files/productdocuments/', '' )

Remove TXT 02

REGEXP_REPLACE(Event Action, 'https://website.com/-/media/rak/files/rak-library/', '' )

--

I'm not 100% sure if it is user error, but if anyone can supply an idea as to how to get this to work, I'd be very grateful!

Body:
It can be achieved by first creating the Extract_Text formula below, and then creating the Main Formula:

Formula 1: Extract_Text

REGEXP_EXTRACT(Event Action, "/([\\w-]+\\.\\w+)\\]?$")

Formula 2: Main Formula

CASE
  WHEN REGEXP_MATCH(Event Action, "\\[?https://website\\.com/-/media/rak/files/(productdocuments|rak-library)/[\\w-]+\\.\\w+\\]?") THEN Extract_Text
  ELSE Event Action
END

Formula Breakdown

Extract_Text: Captures a range of characters a-zA-Z0-9_- after the last / in the sequence: [characters].[characters]

Main Formula: If the pattern doesn't match, then values from the Event Action field are extracted.

Created a Google Data Studio Report (Google Sheets Embedded) to demonstrate.

  EDIT: The formula now captures - to extract product-name-01.pdf


问:
How can i dynamically change bottom navigation items text?

Im trying to achieve the above design. I'm able to change the icons, but cannot change the bottom text. Im using material bottom navigation bar

I achieved the icon change by implementing separate selector drawables for each icon. Is there any way that i can do the same with the nav titles?

MainActivity.class

```<code>public class MainActivity extends AppCompatActivity {
BottomNavigationView navView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    navView = findViewById(R.id.nav_view);

    // Passing each menu ID as a set of Ids because each
    // menu should be considered as top level destinations.
    AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
            R.id.navigation_home, R.id.navigation_saved, R.id.navigation_applied, R.id.navigation_profile, R.id.navigation_more)
            .build();

    NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
    NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
    NavigationUI.setupWithNavController(navView, navController);

}
</code>```

activity_main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingTop="?attr/actionBarSize">

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/nav_view"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="0dp"
        android:layout_marginEnd="0dp"
        app:itemIconTint="@null"
        app:itemHorizontalTranslationEnabled="false"
        android:background="?android:attr/windowBackground"
        app:layout_constraintBottom_toBottomOf="parent"
        app:labelVisibilityMode="labeled"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:menu="@menu/bottom_nav_menu" />

    <fragment
        android:id="@+id/nav_host_fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:defaultNavHost="true"
        app:layout_constraintBottom_toTopOf="@id/nav_view"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:navGraph="@navigation/mobile_navigation" />

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

bottom_nav_menu.xml

```<code>    <item
        android:id="@+id/navigation_home"
        android:icon="@drawable/home_selector"
        android:title="@string/title_home" />

    <item
        android:id="@+id/navigation_saved"
        android:icon="@drawable/saved_jobs_selector"
        android:title="@string/title_saved" />

    <item
        android:id="@+id/navigation_applied"
        android:icon="@drawable/applied_jobs_selector"
        android:title="@string/title_applied" />

    <item
        android:id="@+id/navigation_profile"
        android:icon="@drawable/profile_selector"
        android:title="@string/title_profile" />

    <item
        android:id="@+id/navigation_more"
        android:icon="@drawable/more_selector"
        android:title="@string/title_More" />

</menu>
</code>```

答:
Check below the line of code and add this when you select your item of BottomNavigation in Kotlin (convert java to kotlin).

```<code>navView.getCheckedItem().setTitle(".");
</code>```

Body:
Im trying to achieve the above design. I'm able to change the icons, but cannot change the bottom text. Im using material bottom navigation bar

I achieved the icon change by implementing separate selector drawables for each icon. Is there any way that i can do the same with the nav titles?

MainActivity.class

public class MainActivity extends AppCompatActivity {
BottomNavigationView navView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    navView = findViewById(R.id.nav_view);

    // Passing each menu ID as a set of Ids because each
    // menu should be considered as top level destinations.
    AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
            R.id.navigation_home, R.id.navigation_saved, R.id.navigation_applied, R.id.navigation_profile, R.id.navigation_more)
            .build();

    NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
    NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
    NavigationUI.setupWithNavController(navView, navController);

}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingTop="?attr/actionBarSize">

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/nav_view"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="0dp"
        android:layout_marginEnd="0dp"
        app:itemIconTint="@null"
        app:itemHorizontalTranslationEnabled="false"
        android:background="?android:attr/windowBackground"
        app:layout_constraintBottom_toBottomOf="parent"
        app:labelVisibilityMode="labeled"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:menu="@menu/bottom_nav_menu" />

    <fragment
        android:id="@+id/nav_host_fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:defaultNavHost="true"
        app:layout_constraintBottom_toTopOf="@id/nav_view"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:navGraph="@navigation/mobile_navigation" />

</androidx.constraintlayout.widget.ConstraintLayout>

bottom_nav_menu.xml

    <item
        android:id="@+id/navigation_home"
        android:icon="@drawable/home_selector"
        android:title="@string/title_home" />

    <item
        android:id="@+id/navigation_saved"
        android:icon="@drawable/saved_jobs_selector"
        android:title="@string/title_saved" />

    <item
        android:id="@+id/navigation_applied"
        android:icon="@drawable/applied_jobs_selector"
        android:title="@string/title_applied" />

    <item
        android:id="@+id/navigation_profile"
        android:icon="@drawable/profile_selector"
        android:title="@string/title_profile" />

    <item
        android:id="@+id/navigation_more"
        android:icon="@drawable/more_selector"
        android:title="@string/title_More" />

</menu>

Body:
Check below the line of code and add this when you select your item of BottomNavigation in Kotlin (convert java to kotlin).

navView.getCheckedItem().setTitle(".");


问:
BBM SDK - How to get simulators communicating?
Suffice to say I'm struggling quite a bit with my foray into BlackBerry development. In trying to get the BBM SDK sample apps (platformdemo and  tictactoe) working, I fear I've taken a step backwards.

You see, I initially had it set up so that two BlackBerry simulators could message each other using BBM.

Now, that no longer works, and I simply can't figure out why. Why would the BBM communication not work?

I'm running:

BBM SDK Beta 4_03_10_2011

BlackBerry_Simulators_6.0.0.313_9800

MDS v3.5.3 (I've verified that this is running correctly, downloaded the unlimited strength encryption policy jars etc.)

Java JDK v1.6.0_25 (JRE v6)

I've uninstalled and reinstalled everything, including Java. I run the MDS first using this command line:

"run.bat" -log.console.dump -feature "bbm,keynego,monitor,servicebook,cmimep2p,ep2p,registration,ippp,http,httpm,httpc,httpcm,defaulthandler" -webconfig all

then start up the simulators using the included sim1.bat and sim2.bat files:

Sim1:

@echo off
fledge.exe /app=Jvm.dll /handheld=9800 /session=Sim1 /app-param=JvmAlxConfigFile:9800.xml /data-port=0x4d44 /data-port=0x4d4e /pin=0x2100000A /app-param=regVersion=3 /app-param=regDestIP=127.0.0.1 /app-param=regDestPort=19785 /app-param=regSrcPort=19788 /app-param=DisableSyncServiceRecord /title="BlackBerry 9800-1 Simulator"

Sim2:

@echo off
fledge.exe /app=Jvm.dll /handheld=9800 /session=Sim2 /app-param=JvmAlxConfigFile:9800.xml /data-port=0x4d44 /data-port=0x4d4e /pin=0x2100000B /app-param=regVersion=3 /app-param=regDestIP=127.0.0.1 /app-param=regDestPort=19785 /app-param=regSrcPort=19789 /app-param=DisableSyncServiceRecord /title="BlackBerry 9800-2 Simulator"

I forgot to mention that both simulators can connect to the Internet via the browser (which they cannot do when the MDS is not running properly) but cannot see each other on BBM after adding each other as contacts using the provided pins (2100000A and 2100000B).

What could be going wrong?

答:
For anyone interested, I managed to solve my own problem.

I have no idea why, but previously I could simply add a new contact, put in their BBM pin and they would show up on my contacts list within BBM, ready for me to start a chat with them.

This time, I had to take a screenshot of simulator 1's QR code, save it out in Photoshop, then use that image on simulator 2 to invite simulator 1.

For some reason, this allowed the contacts to see each other. I don't own a BlackBerry so I have no idea but I really can't imagine this is the way it's supposed to work since it requires both users to be in the same physical location. However, it's the only way I could get it working and it proves that the rest of my setup (MDS) and so on is correct.


问:
Firebase analytics android apps
When implementing fire base analytics in android apps do i need to add any codes in the app side or is it enough to enable it in firebase console only. Does it same in ios</p>

答:
if you just need normal analytics like number of installs, uninstalls, cache clear etc,
but if you want specific analytics like number of users visited a specific page you will have to create a event in firebase and write code for that event. </p>

Title: Firebase analytics android apps


问:
how the camera moves whenever the location of Android Google Map changes
I am a beginner of android and java.

I am using the Android Google Map API.

mGoogleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(currentLatLng, 18), 1000, null);

Pressing a button using [animateCamera] implements the function of moving the camera to its current position.

I want the camera to keep up with my position.

[Thread] tried applying [animateCamera] using [sleep], but the Google Map stops.

How do I apply it in Android?

答:
Use setOnCameraChangeListener on your google map: </p>

```<code>LatLngBounds.Builder builder = new LatLngBounds.Builder();
builder.include(latlng);

map.setOnCameraChangeListener(new OnCameraChangeListener() {

@Override
public void onCameraChange(CameraPosition arg0) {
    // Move camera
    map.moveCamera(CameraUpdateFactory.newLatLngBounds(builder.build(), 10));
    // Remove listener to prevent position reset on camera move
    map.setOnCameraChangeListener(null);
}
</code>```

Body:
Use setOnCameraChangeListener on your google map:

LatLngBounds.Builder builder = new LatLngBounds.Builder();
builder.include(latlng);

map.setOnCameraChangeListener(new OnCameraChangeListener() {

@Override
public void onCameraChange(CameraPosition arg0) {
    // Move camera
    map.moveCamera(CameraUpdateFactory.newLatLngBounds(builder.build(), 10));
    // Remove listener to prevent position reset on camera move
    map.setOnCameraChangeListener(null);
}


问:
GCP - DLP - Regex
Trying to process a BigQuery table with a custom infotype of RegEx variety.

RegEx I am using: ^(\d{5})$

In table below, I am trying to tag only against the "Codes" which are 5 digits. With the above RegEx, there are 0 matches.

With the following RegEx: \d{5}

It matches against all instances of 5 digits (including the two in Other)

How do I get it so that it only matches against 5 digits at the start of a "cell"(?) and ending with the 5th digit? Thanks a lot, been bogged down by this.

```
Name | Other     | Code
Blah | Test12345 | 12345
Bleh | 54311Test | 54311
```

答:
Your first instinct of using ^(\d{5})$ should have worked, but did not work because of a bug within the custom regex feature.

The Cloud DLP API team is aware of this issue and they are working on a fix.

Update: Bug has been fixed so this works now. Using \b(regex)\b works as well.

Title: GCP - DLP - Regex

Body:
Trying to process a BigQuery table with a custom infotype of RegEx variety.

RegEx I am using: ^(\d{5})$

In table below, I am trying to tag only against the "Codes" which are 5 digits. With the above RegEx, there are 0 matches.

With the following RegEx: \d{5}

It matches against all instances of 5 digits (including the two in Other)

How do I get it so that it only matches against 5 digits at the start of a "cell"(?) and ending with the 5th digit? Thanks a lot, been bogged down by this.

Name | Other     | Code
Blah | Test12345 | 12345
Bleh | 54311Test | 54311