问:
Get location of file present in Clipboard
```<code>private void button1_Click(object sender, EventArgs e)
{
    textBox1.Text = Clipboard.GetData.ToString();
}
</code>```

I pressed Ctrl+C on a file, not a text. I want set TextBox.Text or a string the location of the file. suppose c:\myfile.abc in Clipboard. I want set text equal to the location/path present in the clipboard.

答:
```<code>if (Clipboard.ContainsFileDropList()) // If Clipboard has one or more files
{
    var files = Clipboard.GetFileDropList().Cast<string>().ToArray(); // Get all files from clipboard

    if (files != null)
    {
        if (files.Length >= 1)
        {
            string filepath = files[0]; // Get first file from clipboard as a file path
            textBox1.Text = filepath;
        }
    }
}
</code>```

Body:
private void button1_Click(object sender, EventArgs e)
{
    textBox1.Text = Clipboard.GetData.ToString();
}

I pressed Ctrl+C on a file, not a text. I want set TextBox.Text or a string the location of the file. suppose c:\myfile.abc in Clipboard. I want set text equal to the location/path present in the clipboard.


来源: stackexchange

问:
Is there a callback on completion of a CSS3 animation?
Is there any way to implement a callback function in case of css3 animation? In case of Javascript animation its possible but not finding any way to do it in css3.

One way I could see is to execute callback after the animation duration but that doesn't make sure that it will always be called right after the animation ends. It will depend on the browser UI queue. I want a more robust method. Any clue?

答:
Yes, there is. The callback is an event, so you must add an event listener to catch it. This is an example with jQuery:

```<code>$("#sun").bind('oanimationend animationend webkitAnimationEnd', function() {
   alert("fin")
});
</code>```

Or pure js:

```<code>element.addEventListener("webkitAnimationEnd", callfunction,false);
element.addEventListener("animationend", callfunction,false);
element.addEventListener("oanimationend", callfunction,false);
</code>```

Live demo:
http://jsfiddle.net/W3y7h/

ContentLicense: CC BY-SA 3.0

Body:
Yes, there is. The callback is an event, so you must add an event listener to catch it. This is an example with jQuery:

$("#sun").bind('oanimationend animationend webkitAnimationEnd', function() {
   alert("fin")
});

Or pure js:

element.addEventListener("webkitAnimationEnd", callfunction,false);
element.addEventListener("animationend", callfunction,false);
element.addEventListener("oanimationend", callfunction,false);

Live demo:
http://jsfiddle.net/W3y7h/


问:
Formatting a date is giving me a different one from the passed one
I need to get the first and last day of the current month, this works perfectly but when I format the date to looks like this yyyy/mm/dd it changes from the one I passed

For example, if a passed the 1 May 2020 when I format the date returns me the 30 April 2020

var startID = document.getElementById('start');
var datenow = new Date();
var firstday = new Date(datenow.getFullYear(), datenow.getMonth(), 1);
firstday = firstday.toISOString().slice(0, 10);
startID.value = firstday;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="date" name="start" class="form-control" id="start" required autofocus>
<label for="start">Start Date</label></code>```

This is how I get the first day of the current month:

var datenow = new Date();
var firstday = new Date(datenow.getFullYear(),datenow.getMonth(), 1);
```

<p>This is how I format the date to looks like <code>yyyy/mm/dd</code> in this part is where I get another wrong date from the passed one:</p>

<pre class="lang-js prettyprint-override"><code>firstday = firstday.toISOString().slice(0,10);
</code>```

答: use moment.js to properly format dates and perform date related operations. it makes thing fairly easier to implement.</p>

ContentLicense: CC BY-SA 4.0

Body:
I need to get the first and last day of the current month, this works perfectly but when I format the date to looks like this yyyy/mm/dd it changes from the one I passed

For example, if a passed the 1 May 2020 when I format the date returns me the 30 April 2020

var startID = document.getElementById('start');
var datenow = new Date();
var firstday = new Date(datenow.getFullYear(), datenow.getMonth(), 1);
firstday = firstday.toISOString().slice(0, 10);
startID.value = firstday;

<input type="date" name="start" class="form-control" id="start" required autofocus>
Start Date

This is how I get the first day of the current month:

var datenow = new Date();
var firstday = new Date(datenow.getFullYear(),datenow.getMonth(), 1);

This is how I format the date to looks like yyyy/mm/dd in this part is where I get another wrong date from the passed one:

firstday = firstday.toISOString().slice(0,10);


问:
Receiving Integrity Error from CustomUserModel form
I would like to create a form with my CustomUserModel as shown below, which has a extending model called customer.

```<code>class UserManager(BaseUserManager):
    def create_user(self, email, password=None,is_active=True, is_staff=False, is_admin=False):
        if not email:
            raise ValueError("Users must have email address")
        user_obj = self.model(email = self.normalize_email(email))
        if not password:
            raise ValueError("Users must have a password")

        user_obj.set_password(password)
        user_obj.staff = is_staff
        user_obj.admin = is_admin
        user_obj.active = is_active
        user_obj.save(using=self._db)

        return user_obj

    def create_staffuser(self,email,password=None):
        user = self.create_user(email, password=password,is_staff=True)

        return user

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

        return user

class User(AbstractBaseUser):

    email = models.EmailField(max_length=255,unique=True)
    active = models.BooleanField(default=True)
    staff = models.BooleanField(default=False)
    admin = models.BooleanField(default=False)

    USERNAME_FIELD = 'email'
    # email and password are required by default
    REQUIRED_FIELDS = []

    objects = UserManager()

    def __str__(self):
        return self.email

    def get_full_name(self):
        return self.email

    def get_short_name(self):
        return self.email

    def has_perm(self, perm, obj=None):
        return True

    def has_module_perms(self, app_label):
        return True

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

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

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

class Customer(models.Model):

    GENDER = (
            ('Male', 'Male'),
            ('Female', 'Female'),
            )

    TITLE = (
            ('Mr', 'Mr'),
            ('Mrs', 'Mrs'),
            ('Miss', 'Miss'),
            ('Ms', 'Ms'),
            ('Dr', 'Dr'),
            ('Sir', 'Sir'),
            ('Madam', 'Madam'),
            )

    user = models.OneToOneField(User,on_delete=models.CASCADE)
    title = models.CharField(max_length=200, null=True, choices=TITLE)
    first_name = models.CharField(max_length=200, null=True)
    middle_name = models.CharField(max_length=200, blank=True,default='')
    last_name = models.CharField(max_length=200, null=True)
    phone = models.CharField(max_length=200, null=True)
    country = CountryField()
    birth_year = models.CharField(max_length=4, null=True)
    gender = models.CharField(max_length=200, null=True, choices=GENDER)
    date_created = models.DateTimeField(auto_now=True, null=True)
    profile_pic = models.ImageField(null=True, blank=True)
    last_purchase = models.DateTimeField(blank=True, null=True)

    def __str__(self):
        return self.user.email

</code>```

Below shows my views.py to create a new customer/user form, that I would like to create at the same time.

```<code>
@login_required(login_url='login')
def NewCustomerProfile(request):
    user_form = RegisterForm()
    customer_form = CustomerProfileForm()
    if request.method == 'POST':
        user_form = RegisterForm(request.POST)
        customer_form = CustomerProfileForm(request.POST)

        if user_form.is_valid() and customer_form.is_valid():
            user_form.save()
            customer_form.save()
            return redirect('/')
    return render(request, 'accounts/new_customer_profile.html', {'user_form': user_form,'customer_form':customer_form})

</code>```

And see below showing my forms for both of the models

```<code>
class CustomerProfileForm(ModelForm):
    class Meta:
        model = Customer
        fields = ['title','first_name','middle_name','last_name','phone','country','birth_year','gender']

class RegisterForm(forms.ModelForm):
    """
    A form for creating new users. Includes all the required
    fields, plus a repeated password.
    """
    password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
    password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput)

    class Meta:
        model = User
        fields = ('email','admin', 'active')

</code>```

I have been getting an error as shown below

```<code>IntegrityError at /new_customer_profile/
NOT NULL constraint failed: accounts_customer.user_id
</code>```

Problem is new customer can be created once a user has been established and created. I would like to create a new user and customer at the same time with no errors accordingly to the models, forms and views shown above.

How does one come to the solution?

答:
I think you answer your own question, in a sense:

"Problem is new customer can be created once a user has been established and created."

Re-write your view to logic to do this in the order that it actually works.  It can still happen "at the same time" relative to to the user, even when your view is doing it sequentially.

Body:
I would like to create a form with my CustomUserModel as shown below, which has a extending model called customer.

class UserManager(BaseUserManager):
    def create_user(self, email, password=None,is_active=True, is_staff=False, is_admin=False):
        if not email:
            raise ValueError("Users must have email address")
        user_obj = self.model(email = self.normalize_email(email))
        if not password:
            raise ValueError("Users must have a password")

        user_obj.set_password(password)
        user_obj.staff = is_staff
        user_obj.admin = is_admin
        user_obj.active = is_active
        user_obj.save(using=self._db)

        return user_obj

    def create_staffuser(self,email,password=None):
        user = self.create_user(email, password=password,is_staff=True)

        return user

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

        return user

class User(AbstractBaseUser):

    email = models.EmailField(max_length=255,unique=True)
    active = models.BooleanField(default=True)
    staff = models.BooleanField(default=False)
    admin = models.BooleanField(default=False)

    USERNAME_FIELD = 'email'
    # email and password are required by default
    REQUIRED_FIELDS = []

    objects = UserManager()

    def __str__(self):
        return self.email

    def get_full_name(self):
        return self.email

    def get_short_name(self):
        return self.email

    def has_perm(self, perm, obj=None):
        return True

    def has_module_perms(self, app_label):
        return True

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

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

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

class Customer(models.Model):

    GENDER = (
            ('Male', 'Male'),
            ('Female', 'Female'),
            )

    TITLE = (
            ('Mr', 'Mr'),
            ('Mrs', 'Mrs'),
            ('Miss', 'Miss'),
            ('Ms', 'Ms'),
            ('Dr', 'Dr'),
            ('Sir', 'Sir'),
            ('Madam', 'Madam'),
            )

    user = models.OneToOneField(User,on_delete=models.CASCADE)
    title = models.CharField(max_length=200, null=True, choices=TITLE)
    first_name = models.CharField(max_length=200, null=True)
    middle_name = models.CharField(max_length=200, blank=True,default='')
    last_name = models.CharField(max_length=200, null=True)
    phone = models.CharField(max_length=200, null=True)
    country = CountryField()
    birth_year = models.CharField(max_length=4, null=True)
    gender = models.CharField(max_length=200, null=True, choices=GENDER)
    date_created = models.DateTimeField(auto_now=True, null=True)
    profile_pic = models.ImageField(null=True, blank=True)
    last_purchase = models.DateTimeField(blank=True, null=True)

    def __str__(self):
        return self.user.email

Below shows my views.py to create a new customer/user form, that I would like to create at the same time.

@login_required(login_url='login')
def NewCustomerProfile(request):
    user_form = RegisterForm()
    customer_form = CustomerProfileForm()
    if request.method == 'POST':
        user_form = RegisterForm(request.POST)
        customer_form = CustomerProfileForm(request.POST)

        if user_form.is_valid() and customer_form.is_valid():
            user_form.save()
            customer_form.save()
            return redirect('/')
    return render(request, 'accounts/new_customer_profile.html', {'user_form': user_form,'customer_form':customer_form})

And see below showing my forms for both of the models

class CustomerProfileForm(ModelForm):
    class Meta:
        model = Customer
        fields = ['title','first_name','middle_name','last_name','phone','country','birth_year','gender']

class RegisterForm(forms.ModelForm):
    """
    A form for creating new users. Includes all the required
    fields, plus a repeated password.
    """
    password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
    password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput)

    class Meta:
        model = User
        fields = ('email','admin', 'active')

I have been getting an error as shown below

IntegrityError at /new_customer_profile/
NOT NULL constraint failed: accounts_customer.user_id

Problem is new customer can be created once a user has been established and created. I would like to create a new user and customer at the same time with no errors accordingly to the models, forms and views shown above.

How does one come to the solution?


问:
How to set default namespace for T4 generated code
So, I have f T4 template stored in folder ProjectRoot/Data, and every time I rebuild my project, this template also gets rebuild and so VS automatically sets namespace for the generated class to ProjectName.Data, but all of my other classes are stored in namespace ProjectName, so this makes a problem because I don't want to change this namespace each time I rebuild project or template, especially if I will share this project with others, so are there any functionality to set a namespace for generated code inside T4 code itself?

EDIT

Here is the minimal reproductive example of this problem:

File Output.tt, located in ProjectRoot/Data

```<code><#@ template language="C#" #>
<#@ assembly name="System.Core" #>
<#@ import namespace="GLGenerator" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ import namespace="System.Linq" #>

// Some other code

<#+

    // Public constructor & class properties here

#>
</code>```

And then auto-generated class based on this .tt file looks like this:

```<code>namespace <ProjectRoot>.Data
{
    using GLGenerator;
    using System.Text;
    using System.Collections.Generic;
    using System.Linq;
    using System;

    public partial class OutputEnums : OutputEnumsBase
    {
        public virtual string TransformText()
        {
            // Auto-generated template code
        }

        // Class properties & constructor
    }
    // Other auto-generated code.
}
</code>```

And as you can see, VS automatically sets namespace for this class to ProjectName.Data, which is bad for me as I want to have all of my classes in one namespace to make most of them internal for this namespace. So, is there a way to change this behavior of VS to something else?

答:
The following works fine for me:

```<code><#@ template language="C#" #>
<#@ assembly name="System.Core" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ import namespace="System.Linq" #>

namespace MyNamespace
{
    public partial class OutputEnums
    {
        public virtual string TransformText()
        {
            // Auto-generated template code
<#
#>
            return "";
        }

        // Class properties & constructor
    }
    // Other auto-generated code.
}
</code>```

It produces - as expected -

```<code>namespace MyNamespace
{
    public partial class OutputEnums
    {
        public virtual string TransformText()
        {
            // Auto-generated template code
            return "";
        }

        // Class properties & constructor
    }
    // Other auto-generated code.
}
</code>```

Body:
So, I have f T4 template stored in folder ProjectRoot/Data, and every time I rebuild my project, this template also gets rebuild and so VS automatically sets namespace for the generated class to ProjectName.Data, but all of my other classes are stored in namespace ProjectName, so this makes a problem because I don't want to change this namespace each time I rebuild project or template, especially if I will share this project with others, so are there any functionality to set a namespace for generated code inside T4 code itself?

EDIT

Here is the minimal reproductive example of this problem:

File Output.tt, located in ProjectRoot/Data

<#@ template language="C#" #>
<#@ assembly name="System.Core" #>
<#@ import namespace="GLGenerator" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ import namespace="System.Linq" #>

// Some other code

<#+

    // Public constructor & class properties here

#>

And then auto-generated class based on this .tt file looks like this:

namespace <ProjectRoot>.Data
{
    using GLGenerator;
    using System.Text;
    using System.Collections.Generic;
    using System.Linq;
    using System;

    public partial class OutputEnums : OutputEnumsBase
    {
        public virtual string TransformText()
        {
            // Auto-generated template code
        }

        // Class properties & constructor
    }
    // Other auto-generated code.
}

And as you can see, VS automatically sets namespace for this class to ProjectName.Data, which is bad for me as I want to have all of my classes in one namespace to make most of them internal for this namespace. So, is there a way to change this behavior of VS to something else?

Body:
The following works fine for me:

<#@ template language="C#" #>
<#@ assembly name="System.Core" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ import namespace="System.Linq" #>

namespace MyNamespace
{
    public partial class OutputEnums
    {
        public virtual string TransformText()
        {
            // Auto-generated template code
<#
#>
            return "";
        }

        // Class properties & constructor
    }
    // Other auto-generated code.
}

It produces - as expected -

namespace MyNamespace
{
    public partial class OutputEnums
    {
        public virtual string TransformText()
        {
            // Auto-generated template code
            return "";
        }

        // Class properties & constructor
    }
    // Other auto-generated code.
}


问:
How to add a custom extension when using typescript
I am trying to add a custom extension to scrumpy/tiptap, but my project is using typescript and I think this is causing me some problems.

I got the code from this issue, and tried importing and using it like this:

```<code>import HighlightMark from '../ts/tiptap-extensions/HighlightMark';

...

this.editor = new Editor({
  content: '<p>This is just a boring paragraph.</p>',
  extensions: [new HighlightMark()]
})
</code>```

But I am faced with this error

Type 'HighlightMark' is not assignable to type 'ExtensionOption'.
    Type 'HighlightMark' is not assignable to type 'Mark'.
      The types returned by 'schema.toDOM(...)' are incompatible between these types.
        Type '(string | number | { style: string; })[]' is not assignable to type 'DOMOutputSpec'.
          Property '0' is missing in type '(string | number | { style: string; })[]' but required in type 'DOMOutputSpecArray'.

I tried importing it in a .d.ts (as I had to do with all the built-int tiptap extensions), but I get an error telling me that I can't import files from relative path here:

Import or export declaration in an ambient module declaration cannot reference module through relative module name.ts(2439)

I also tried just changing the file to typescript (HighlightMark.ts), but it then gives me several errors:

Property 'commands' in type 'HighlightMark' is not assignable to the same property in base type 'Mark'.
    Type '({ type }: { type: any; }) => (attrs: any) => Command' is not assignable to type '({ type, schema, attrs }: { type: MarkType; schema: MarkSpec; attrs: { [key: string]: string; }; }) => CommandGetter'.
      Type '(attrs: any) => Command' is not assignable to type 'CommandGetter'.

and

'mark' is declared but its value is never read.ts(6133)
  Parameter 'mark' implicitly has an 'any' type.ts(7006)

and

Parameter 'attrs' implicitly has an 'any' type.ts(7006)

Has anyone done this before? Is it actually possible?

This is the code from HighlightMark.js:

```<code>   import { Mark } from 'tiptap';
   import { toggleMark } from 'tiptap-commands'

  export default class HighlightMark extends Mark {
  get name() {
    return "mark";
  }

  get schema() {
    return {
      attrs: {
        color: {
          default: "rgba(240,87,100,0.7)"
        }
      },
      parseDOM: [
        {
          tag: "mark"
        }
      ],
      toDOM: mark => [
        "mark",
        {
          style: `background: red` // ${mark.attrs.color}
        },
        0
      ]
    };
  }

  commands({ type }) {
    return attrs => toggleMark(type, attrs);
  }
}
</code>```

答:
It seems I could resolve this by initialising tiptap like this

```<code>this.editor = new Editor({
  content: '<p>This is just a boring paragraph.</p>',
  extensions: [new HighlightMark() as any]
</code>```

Which is not ideal, but seems to be working for now.

If anyone can post the real solution I will mark it as the answer

Body:
I am trying to add a custom extension to scrumpy/tiptap, but my project is using typescript and I think this is causing me some problems.

I got the code from this issue, and tried importing and using it like this:

import HighlightMark from '../ts/tiptap-extensions/HighlightMark';

...

this.editor = new Editor({
  content: '
This is just a boring paragraph.
',
  extensions: [new HighlightMark()]
})

But I am faced with this error

Type 'HighlightMark' is not assignable to type 'ExtensionOption'.
    Type 'HighlightMark' is not assignable to type 'Mark'.
      The types returned by 'schema.toDOM(...)' are incompatible between these types.
        Type '(string | number | { style: string; })[]' is not assignable to type 'DOMOutputSpec'.
          Property '0' is missing in type '(string | number | { style: string; })[]' but required in type 'DOMOutputSpecArray'.

I tried importing it in a .d.ts (as I had to do with all the built-int tiptap extensions), but I get an error telling me that I can't import files from relative path here:

Import or export declaration in an ambient module declaration cannot reference module through relative module name.ts(2439)

I also tried just changing the file to typescript (HighlightMark.ts), but it then gives me several errors:

Property 'commands' in type 'HighlightMark' is not assignable to the same property in base type 'Mark'.
    Type '({ type }: { type: any; }) => (attrs: any) => Command' is not assignable to type '({ type, schema, attrs }: { type: MarkType; schema: MarkSpec; attrs: { [key: string]: string; }; }) => CommandGetter'.
      Type '(attrs: any) => Command' is not assignable to type 'CommandGetter'.

and

'mark' is declared but its value is never read.ts(6133)
  Parameter 'mark' implicitly has an 'any' type.ts(7006)

and

Parameter 'attrs' implicitly has an 'any' type.ts(7006)

Has anyone done this before? Is it actually possible?

This is the code from HighlightMark.js:

   import { Mark } from 'tiptap';
   import { toggleMark } from 'tiptap-commands'

  export default class HighlightMark extends Mark {
  get name() {
    return "mark";
  }

  get schema() {
    return {
      attrs: {
        color: {
          default: "rgba(240,87,100,0.7)"
        }
      },
      parseDOM: [
        {
          tag: "mark"
        }
      ],
      toDOM: mark => [
        "mark",
        {
          style: `background: red` // ${mark.attrs.color}
        },
        0
      ]
    };
  }

  commands({ type }) {
    return attrs => toggleMark(type, attrs);
  }
}

Body:
It seems I could resolve this by initialising tiptap like this

this.editor = new Editor({
  content: '<p>This is just a boring paragraph.</p>',
  extensions: [new HighlightMark() as any]

Which is not ideal, but seems to be working for now.

If anyone can post the real solution I will mark it as the answer


问:
Altering Web.Config SessionTimeout value from within application
I am trying to work out a way to alter the session timeout dynamically, as my customer has requested that this be a value they can easily change (as though it were a database transaction). Here is a truncated version of the value I am trying to change:

```<code><appSettings>
   <add key="SessionTimeout" value="20"/>
</appsettings>
</code>```

I'm working with C#/.Net 3.5 with all of this.

For the record, I am aware that altering the web.config file will cause a restart of the application. What I am going for is to give the administrator of the program the ability to alter the timeout on the fly. If, for example, one of the forms they are requiring people to fill out is taking longer than 20 minutes, and they need to bump the time up to a half hour, or if they want it shortened for some other reason. Since we want to keep the users (including admins) out of the code files, the goal is to create this as part of the site's admin page.

The problem is, I have no idea how to do this, or if it's even possible (much less a good idea). I've given google the run around and come up with nothing.

Is there a way to make these alterations, or even potentially to dynamically change the timeout on the fly (overriding the contents of the web.config)?

Thanks for the help.

答:
Extend timeout from code where you need it:

```<code>Session.Timeout = 40;
</code>```

Also if you will try to change this parameter in config it will lead to application pool restart.

Body:
I am trying to work out a way to alter the session timeout dynamically, as my customer has requested that this be a value they can easily change (as though it were a database transaction). Here is a truncated version of the value I am trying to change:

<appSettings>
   <add key="SessionTimeout" value="20"/>
</appsettings>

I'm working with C#/.Net 3.5 with all of this.

For the record, I am aware that altering the web.config file will cause a restart of the application. What I am going for is to give the administrator of the program the ability to alter the timeout on the fly. If, for example, one of the forms they are requiring people to fill out is taking longer than 20 minutes, and they need to bump the time up to a half hour, or if they want it shortened for some other reason. Since we want to keep the users (including admins) out of the code files, the goal is to create this as part of the site's admin page.

The problem is, I have no idea how to do this, or if it's even possible (much less a good idea). I've given google the run around and come up with nothing.

Is there a way to make these alterations, or even potentially to dynamically change the timeout on the fly (overriding the contents of the web.config)?

Thanks for the help.

Body:
Extend timeout from code where you need it:

Session.Timeout = 40;

Also if you will try to change this parameter in config it will lead to application pool restart.


问:
Spring boot: enforce best practices
I am setting up a project and wondering if there any way to enforce repository instance access from service layer only? </p>

答:
If you do not use public keyword when defining a repository and service class and put them together in one package. Of course you need to communicate from Controller to Service. The best way to do that is to create interface which is public (in the same package), let's say:

```<code>public interface UserFacade
</code>```

which is implemented by the (same package, without public keyword):

```<code>@Component
class UserFacadeImpl implements UserFacade {

   private YourService service;

   void someMethod() {
       service.doSomethingWithRepository();
   }
}
</code>```

Then you can define methods in this facade which use your service or any other services which are defined in this package. In the end, the only way to access your repository from outside the package is indirectly by the methods defined in UserFacade, so directly only services in the same package can use this repo.

Title: Spring boot: enforce best practices

Body:
If you do not use public keyword when defining a repository and service class and put them together in one package. Of course you need to communicate from Controller to Service. The best way to do that is to create interface which is public (in the same package), let's say:

public interface UserFacade

which is implemented by the (same package, without public keyword):

@Component
class UserFacadeImpl implements UserFacade {

   private YourService service;

   void someMethod() {
       service.doSomethingWithRepository();
   }
}

Then you can define methods in this facade which use your service or any other services which are defined in this package. In the end, the only way to access your repository from outside the package is indirectly by the methods defined in UserFacade, so directly only services in the same package can use this repo.


问:
Firebase Cloud Functions: "status":"INVALID_ARGUMENT"
I am locally testing a Firebase Cloud Function. When I call this function using the local URL http://localhost:5001/projectName/us-central1/functionName as described here:

exports.createSession = functions.https.onRequest((_req, res) => {
  res.status(200).send('TESTING');
});
```

<p>the function works and it returns the string.</p>

<p>However, when I call this function:</p>

<pre class="lang-js prettyprint-override"><code>exports.createSession = functions.https.onCall((data, context) => {
  return 'TESTING';
});
</code>```

It throws the error: {"error":{"message":"Bad Request","status":"INVALID_ARGUMENT"}}

I'd like to use the latter function because I want to access the context.auth object to check for user Firebase authentication.

I'm using Firebase CLI v8.4 and Node v10.20.

What am I missing from the second function to get it working? I am not calling it with any arguments as I do not need to.

答:
The answer is that you can't call the .onCall method in the same way as you can the onRequest method, you have to call it from the SDK. If the data argument is missing it will throw an error:

If the client trigger is invoked, but the request is in the wrong format, such as not being JSON, having invalid fields, or missing the data field, the request is rejected with 400 Bad Request, with an error code of INVALID_ARGUMENT.

So you have to call it with an argument even if you don't need to use the argument for anything.

Body:
I am locally testing a Firebase Cloud Function. When I call this function using the local URL http://localhost:5001/projectName/us-central1/functionName as described here:

exports.createSession = functions.https.onRequest((_req, res) => {
  res.status(200).send('TESTING');
});

the function works and it returns the string.

However, when I call this function:

exports.createSession = functions.https.onCall((data, context) => {
  return 'TESTING';
});

It throws the error: {"error":{"message":"Bad Request","status":"INVALID_ARGUMENT"}}

I'd like to use the latter function because I want to access the context.auth object to check for user Firebase authentication.

I'm using Firebase CLI v8.4 and Node v10.20.

What am I missing from the second function to get it working? I am not calling it with any arguments as I do not need to.


问:
LinkedIn Link Sharing: Open Graph Image Issue
NOTE: I've seen a variety of similar questions to this one so I'm going to try and be succinct in describing the issue along with what I've done so far.

The issue is that LinkedIn is failing to properly scrape images from articles on a WordPress site. The site is using All-in-One SEO to add the appropriate meta tags and these tags and, judging by facebook's sharing and object debuggers, is doing so correctly.

Here's a sample article that demonstrates the issue.

Upon entering the URI into a LinkedIn article, LinkedIn attempts to fetch the page's data. It returns with the title and description but leaves an empty space where the image would presumably display:

In tailing the access logs, I've seen LinkedIn hitting the site along with 200 status codes for the page itself and the image:

```<code>[ip redacted] - - [29/Mar/2017:19:50:44 +0000]  "GET /linkedin-test/?refTest=LI17 HTTP/1.1" 200 23758 "-" "LinkedInBot/1.0 (compatible; Mozilla/5.0; Jakarta Commons-HttpClient/3.1 +http://www.linkedin.com)" 0.906 "[ips redacted]"
[ip redacted] - - [29/Mar/2017:19:50:44 +0000]  "GET /wp-content/uploads/2017/03/modern-architecture-skyscrapers-modest-with-images-of-modern-architecture-ideas-on-gallery.jpg HTTP/1.1" 200 510088 "-" "LinkedInBot/1.0 (compatible; Mozilla/5.0; Jakarta Commons-HttpClient/3.1 +http://www.linkedin.com)" 0.000 "[ips redacted]"
</code>```

Following some other Stack Overflow threads, I experimented with the following:

Attempt to bust LinkedIn's cache with query strings

Result: No change with query strings or completely new URLs

Verify image dimensions for og:image resource are not too small

Result: No change was seen here in using images that match or exceed those indicated in LinkedIn's knowledge base

Revise all meta tags to include prefix="og: http://ogp.me/ns#"

Result: No change

I feel like I've hit a wall so any suggestions or thoughts are definitely welcome!

Thanks!

答:
This seems to work fine for me:

```<code>https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fdev-agilealliance.pantheonsite.io%2F
</code>```

Source: Official Microsoft Documentation for Sharing on LinkedIn.  Results:

So, what changed???  I did some digging.

Let's look at the 2018 robots.txt file for dev-agilealliance.pantheonsite.io, and compare it to the working, 2020 robots.txt file.  Seems pretty clear.  This is why things were blocked in 2018...

```<code># Pantheon's documentation on robots.txt: http://pantheon.io/docs/articles/sites/code/bots-and-indexing/
User-agent: *
Disallow: /
</code>```

And this is the working robots.txt in 2020...

```<code>User-agent: RavenCrawler
User-agent: rogerbot
User-agent: dotbot
User-agent: SemrushBot
User-agent: SemrushBot-SA
User-agent: PowerMapper
User-agent: Swiftbot
Allow: /
</code>```

Of course, it could also be that sharing services are much more lenient in 2020 than in 2017!  But things do seem to be working now, according to the above specs., I can confirm.

Body:
NOTE: I've seen a variety of similar questions to this one so I'm going to try and be succinct in describing the issue along with what I've done so far.

The issue is that LinkedIn is failing to properly scrape images from articles on a WordPress site. The site is using All-in-One SEO to add the appropriate meta tags and these tags and, judging by facebook's sharing and object debuggers, is doing so correctly.

Here's a sample article that demonstrates the issue.

Upon entering the URI into a LinkedIn article, LinkedIn attempts to fetch the page's data. It returns with the title and description but leaves an empty space where the image would presumably display:

In tailing the access logs, I've seen LinkedIn hitting the site along with 200 status codes for the page itself and the image:

[ip redacted] - - [29/Mar/2017:19:50:44 +0000]  "GET /linkedin-test/?refTest=LI17 HTTP/1.1" 200 23758 "-" "LinkedInBot/1.0 (compatible; Mozilla/5.0; Jakarta Commons-HttpClient/3.1 +http://www.linkedin.com)" 0.906 "[ips redacted]"
[ip redacted] - - [29/Mar/2017:19:50:44 +0000]  "GET /wp-content/uploads/2017/03/modern-architecture-skyscrapers-modest-with-images-of-modern-architecture-ideas-on-gallery.jpg HTTP/1.1" 200 510088 "-" "LinkedInBot/1.0 (compatible; Mozilla/5.0; Jakarta Commons-HttpClient/3.1 +http://www.linkedin.com)" 0.000 "[ips redacted]"

Following some other Stack Overflow threads, I experimented with the following:

Attempt to bust LinkedIn's cache with query strings

Result: No change with query strings or completely new URLs

Verify image dimensions for og:image resource are not too small

Result: No change was seen here in using images that match or exceed those indicated in LinkedIn's knowledge base

Revise all meta tags to include prefix="og: http://ogp.me/ns#"

Result: No change

I feel like I've hit a wall so any suggestions or thoughts are definitely welcome!

Thanks!

Body:
This seems to work fine for me:

https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fdev-agilealliance.pantheonsite.io%2F

Source: Official Microsoft Documentation for Sharing on LinkedIn.  Results:

So, what changed???  I did some digging.

Let's look at the 2018 robots.txt file for dev-agilealliance.pantheonsite.io, and compare it to the working, 2020 robots.txt file.  Seems pretty clear.  This is why things were blocked in 2018...

# Pantheon's documentation on robots.txt: http://pantheon.io/docs/articles/sites/code/bots-and-indexing/
User-agent: *
Disallow: /

And this is the working robots.txt in 2020...

User-agent: RavenCrawler
User-agent: rogerbot
User-agent: dotbot
User-agent: SemrushBot
User-agent: SemrushBot-SA
User-agent: PowerMapper
User-agent: Swiftbot
Allow: /

Of course, it could also be that sharing services are much more lenient in 2020 than in 2017!  But things do seem to be working now, according to the above specs., I can confirm.


问:
Show/hide password onClick of using Vanilla js
I'm trying to hide/show password using the following codes which works fine if it is for 1 input field. If I have another input field, say for 'verify password', how do I make the other works. I'm kinda stuck here.

Any input is very much appreciated. Thank you.

```<code>    var passwordField = document.querySelector(".password"),
        eyeIcon = document.querySelector(".icon");

    function togglePassword() {
        if (passwordField.type === "password") {
            passwordField.type = "text";
        } else {
            passwordField.type = "password";
        }
    }
    eyeIcon.addEventListener("click", togglePassword);
</code>```

答:
You can use this if you want to toggle both at a time</p>

```<code>var passwordField =
document.getElementById('password');
var passwordField2 =
document.getElementById('password2');

if (passwordField.type === "password") {
    passwordField.type = 'text';
    passwordField2.type = 'text';
} else {
    passwordField.type = 'password';
    passwordField2.type = 'password';
}
</code>```

Body:
I'm trying to hide/show password using the following codes which works fine if it is for 1 input field. If I have another input field, say for 'verify password', how do I make the other works. I'm kinda stuck here.

Any input is very much appreciated. Thank you.

    var passwordField = document.querySelector(".password"),
        eyeIcon = document.querySelector(".icon");

    function togglePassword() {
        if (passwordField.type === "password") {
            passwordField.type = "text";
        } else {
            passwordField.type = "password";
        }
    }
    eyeIcon.addEventListener("click", togglePassword);

Body:
You can use this if you want to toggle both at a time

var passwordField =
document.getElementById('password');
var passwordField2 =
document.getElementById('password2');

if (passwordField.type === "password") {
    passwordField.type = 'text';
    passwordField2.type = 'text';
} else {
    passwordField.type = 'password';
    passwordField2.type = 'password';
}


问:
Actually delete a git commit in such a way that it disappears from the log
I cannot find a way to delete a targeted commit from the log. Documentation about deleting commits either just resets a pointer using reset (which does not delete anything, it just resets pointers), or rebase, which creates a new structure of some sort at the deleted commit. The hash of the targeted commit still appears. There may be old documentation out there related to

```<code>git rebase -i fork1~1 fork1~3
</code>```

because in older messages, it states to delete a line in the editor, that is, the line corresponding to the targeted commit. When I get into the interactive editor, one of the choices is "drop", which it says removes the commit. However, I have not successfully removed any commits in the sense that they disappear from the log. I insert the word drop, and it creates some sort of fork-looking thing in the log output. But I can still see the hash of the commit I am trying to remove. Simply put, I want to identify a hash to remove and have it no longer appear in the log.

So, the idea here is to drop 1bc7112:

```<code>*   4518859 (refs/stash) WIP on fork3: 8c438a9 Added first.bsh back in
|\
| * 1bc7112 index on fork3: 8c438a9 Added first.bsh back in
|/
* 8c438a9 Added first.bsh back in
* eef828f (HEAD -> fork4) Removed using git rm
* c21cda0 Third change.
</code>```

答:
Now that you have posted the log (as a graph), the reason is clear: the commit you want to drop is not part of the history at all. It's being preserved by the stash. The way to delete it is to drop the stash itself.

The graph reveals what an odd duck the stash really is. It is in fact a merge commit; its first parent is the HEAD when you created the stash (because the working tree existed with regard to that HEAD) and its second parent is the entire index at that moment, and the parent of that second parent is the HEAD. The documentation draws it like this:

```<code>       .----W
      /    /
-----H----I
</code>```

The dot is the stash, H is the HEAD, I is the recorded index, and W is the recorded worktree.

So as long as the stash exists, that H commit (the one that was head at the time you stashed) cannot go out of existence.

Meanwhile, the commit you are complaining about isn't even a real commit! It's the frozen snapshot of the Index at the moment you made the stash. It is integral to the stash.

Body:
I cannot find a way to delete a targeted commit from the log. Documentation about deleting commits either just resets a pointer using reset (which does not delete anything, it just resets pointers), or rebase, which creates a new structure of some sort at the deleted commit. The hash of the targeted commit still appears. There may be old documentation out there related to

git rebase -i fork1~1 fork1~3

because in older messages, it states to delete a line in the editor, that is, the line corresponding to the targeted commit. When I get into the interactive editor, one of the choices is "drop", which it says removes the commit. However, I have not successfully removed any commits in the sense that they disappear from the log. I insert the word drop, and it creates some sort of fork-looking thing in the log output. But I can still see the hash of the commit I am trying to remove. Simply put, I want to identify a hash to remove and have it no longer appear in the log.

So, the idea here is to drop 1bc7112:

*   4518859 (refs/stash) WIP on fork3: 8c438a9 Added first.bsh back in
|\
| * 1bc7112 index on fork3: 8c438a9 Added first.bsh back in
|/
* 8c438a9 Added first.bsh back in
* eef828f (HEAD -> fork4) Removed using git rm
* c21cda0 Third change.

Body:
Now that you have posted the log (as a graph), the reason is clear: the commit you want to drop is not part of the history at all. It's being preserved by the stash. The way to delete it is to drop the stash itself.

The graph reveals what an odd duck the stash really is. It is in fact a merge commit; its first parent is the HEAD when you created the stash (because the working tree existed with regard to that HEAD) and its second parent is the entire index at that moment, and the parent of that second parent is the HEAD. The documentation draws it like this:

       .----W
      /    /
-----H----I

The dot is the stash, H is the HEAD, I is the recorded index, and W is the recorded worktree.

So as long as the stash exists, that H commit (the one that was head at the time you stashed) cannot go out of existence.

Meanwhile, the commit you are complaining about isn't even a real commit! It's the frozen snapshot of the Index at the moment you made the stash. It is integral to the stash.


问:
Get data from request npm
I'm building an app using express js and using request(v-2.88.2) to get data from an api

```<code>request(url, function(error, request, body) {
    var data = JSON.parse(body);
});
</code>```

I want to use var data in other functions.

Are there any ways to do this?

答:
hi you can do this by making you variable as global. its not really good method but we can do this

```<code>var data;
request(url, function(error, request, body) {
data = JSON.parse(body);
});
</code>```

by this, you can even access your data variable outside of your function too. hope this may help you.

Title: Get data from request npm

Body:
I'm building an app using express js and using request(v-2.88.2) to get data from an api

request(url, function(error, request, body) {
    var data = JSON.parse(body);
});

I want to use var data in other functions.

Are there any ways to do this?

Body:
hi you can do this by making you variable as global. its not really good method but we can do this

var data;
request(url, function(error, request, body) {
data = JSON.parse(body);
});

by this, you can even access your data variable outside of your function too. hope this may help you.


问:
Do WebGL fragment shaders support outerProduct?
When compiling this WebGL fragment shader in both Chrome 22 and Firefox 15:

```<code>precision mediump float;
uniform vec2 u_resolution;
uniform sampler2D u_tex;
void main() {
    vec2 texCoord = gl_FragCoord.xy / u_resolution;
    vec4 floatColor = texture2D(u_tex, texCoord);
    mat3 outerMat = outerProduct(floatColor.rgb,floatColor.rgb);
    gl_FragColor = vec4(outerMat[0], 1);
}
</code>```

I'm getting this error:

```<code>ERROR: 0:8: 'outerProduct' : no matching overloaded function found
ERROR: 0:8: '=' :  cannot convert from 'const mediump float' to '3X3 matrix of float'
</code>```

The OpenGL ES 2.0 GLSL spec indicates that mat3 outerProduct(vec3,vec3) is supported, and the WebGL spec says that it accepts ES shaders, so I'm not sure what's going wrong. Is outerProduct not supported in WebGL fragment shaders, or am I doing something wrong?

答:
it is now available with webGL2.
Check your system here: https://webglreport.com/?v=2</p>

Body:
When compiling this WebGL fragment shader in both Chrome 22 and Firefox 15:

precision mediump float;
uniform vec2 u_resolution;
uniform sampler2D u_tex;
void main() {
    vec2 texCoord = gl_FragCoord.xy / u_resolution;
    vec4 floatColor = texture2D(u_tex, texCoord);
    mat3 outerMat = outerProduct(floatColor.rgb,floatColor.rgb);
    gl_FragColor = vec4(outerMat[0], 1);
}

I'm getting this error:

ERROR: 0:8: 'outerProduct' : no matching overloaded function found
ERROR: 0:8: '=' :  cannot convert from 'const mediump float' to '3X3 matrix of float'

The OpenGL ES 2.0 GLSL spec indicates that mat3 outerProduct(vec3,vec3) is supported, and the WebGL spec says that it accepts ES shaders, so I'm not sure what's going wrong. Is outerProduct not supported in WebGL fragment shaders, or am I doing something wrong?


问:
How to show table data in ng-bootstrap in angular 8
I am trying to show multiple table data in a table So i am declared each variable.If i click table 1 button i want to show tabledatas1 array data same like If i click table 2 button i want to show tabledatas2 array data same like for table 3 button. But i do not how to assign the array to table data service.If you see my stackblitz you can easily understand.Please help to find the solution.

Demo:https://stackblitz.com/edit/angular-yz5ch9-xmdqv8?file=src%2Fapp%2Ftable-complete.ts

table-complete.html:

```<code><div class="col-4">
  <button class="btn btn-secondary" (click)="forTableData1()">Table 1</button>
</div>
   <div class="col-4">
    <button class="btn btn-secondary" (click)="forTableData2()">Table 2</button>
</div>
   <div class="col-4">
    <button class="btn btn-secondary" (click)="forTableData3()">Table 3</button>
</div>
</div>
</code>```

table-complete.ts:

```<code> forTableData1(){
    this.service.tabledataGet(this.tabledatas1);
 }
 forTableData2(){
    this.service.tabledataGet(this.tabledatas2);
 }
 forTableData3(){
    this.service.tabledataGet(this.tabledatas3);
 }
</code>```

答:
create a global variable called selectedData

selectedData: Array<any> = [];
```

<p>iterate on <code>selectedData</code> template</p>

<pre class="lang-html prettyprint-override"><code>    <tr *ngFor="let country of selectedData">
      <th scope="row">{{ country.id }}</th>
      <td>
        <img [src]="'https://upload.wikimedia.org/wikipedia/commons/' + country.flag" class="mr-2" style="width: 20px">
        <ngb-highlight [result]="country.name" [term]="service.searchTerm"></ngb-highlight>
      </td>
      <td><ngb-highlight [result]="country.area | number" [term]="service.searchTerm"></ngb-highlight></td>
      <td><ngb-highlight [result]="country.population | number" [term]="service.searchTerm"></ngb-highlight></td>
    </tr>
</code>```

on clicking of buttons set each country array to selectedData

  forTableData1(){
    // Rest of the method
    this.selectedData = this.tabledatas1;
  }
  forTableData2(){
     // Rest of the method
     this.selectedData = this.tabledatas2;
  }
  forTableData3(){
    // Rest of the method
    this.selectedData = this.tabledatas3;
  }
```

Body:
I am trying to show multiple table data in a table So i am declared each variable.If i click table 1 button i want to show tabledatas1 array data same like If i click table 2 button i want to show tabledatas2 array data same like for table 3 button. But i do not how to assign the array to table data service.If you see my stackblitz you can easily understand.Please help to find the solution.

Demo:https://stackblitz.com/edit/angular-yz5ch9-xmdqv8?file=src%2Fapp%2Ftable-complete.ts

table-complete.html:

  <button class="btn btn-secondary" (click)="forTableData1()">Table 1</button>

    <button class="btn btn-secondary" (click)="forTableData2()">Table 2</button>

    <button class="btn btn-secondary" (click)="forTableData3()">Table 3</button>

table-complete.ts:

 forTableData1(){
    this.service.tabledataGet(this.tabledatas1);
 }
 forTableData2(){
    this.service.tabledataGet(this.tabledatas2);
 }
 forTableData3(){
    this.service.tabledataGet(this.tabledatas3);
 }

Body:
create a global variable called selectedData

selectedData: Array<any> = [];

iterate on selectedData template

    <tr *ngFor="let country of selectedData">
      <th scope="row">{{ country.id }}</th>
      <td>
        <img [src]="'https://upload.wikimedia.org/wikipedia/commons/' + country.flag" class="mr-2" style="width: 20px">
        <ngb-highlight [result]="country.name" [term]="service.searchTerm"></ngb-highlight>
      </td>
      <td><ngb-highlight [result]="country.area | number" [term]="service.searchTerm"></ngb-highlight></td>
      <td><ngb-highlight [result]="country.population | number" [term]="service.searchTerm"></ngb-highlight></td>
    </tr>

on clicking of buttons set each country array to selectedData

  forTableData1(){
    // Rest of the method
    this.selectedData = this.tabledatas1;
  }
  forTableData2(){
     // Rest of the method
     this.selectedData = this.tabledatas2;
  }
  forTableData3(){
    // Rest of the method
    this.selectedData = this.tabledatas3;
  }


问:
convenient way to convert seconds into more specific format
Is there any convenient way to convert seconds into more specific format.

For example:

I want to convert

```<code>559 seconds
</code>```

to

```<code>9 min 19 sec
</code>```

答:
See http://dev.kafol.net/2008/09/php-calculating-time-span-duration.html</p>

```<code> $days = floor($seconds/60/60/24);
 $hours = $seconds/60/60%24;
 $mins = $seconds/60%60;
 $secs = $seconds%60;

 $duration='';
 if($days>0) $duration .= "$days days ";
 if($hours>0) $duration .= "$hours hours ";
 if($mins>0) $duration .= "$mins minutes ";
 if($secs>0) $duration .= "$secs seconds ";
</code>```

Body:
Is there any convenient way to convert seconds into more specific format.

For example:

I want to convert

559 seconds

to

9 min 19 sec

Body:
See http://dev.kafol.net/2008/09/php-calculating-time-span-duration.html

 $days = floor($seconds/60/60/24);
 $hours = $seconds/60/60%24;
 $mins = $seconds/60%60;
 $secs = $seconds%60;

 $duration='';
 if($days>0) $duration .= "$days days ";
 if($hours>0) $duration .= "$hours hours ";
 if($mins>0) $duration .= "$mins minutes ";
 if($secs>0) $duration .= "$secs seconds ";


问:
Cannot load routing modules after building in Angular
I am trying to build my angular app und serve it on xampp, but after building my Angular Project and copying the dist folder into the htdocs folder, I cannot access the routing modules.
When running the angular app with ng serve, I have no problems accessing the route in the module, but after building it, I am getting an 404 error when trying to acess a route thats in the routing module.

The routes that are in the app module work just fine.

My app-routing.module.ts:

```<code>import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

const routes: Routes = [
  {path: 'intern', loadChildren: () => import('./intern/intern.module').then(m => m.InternModule)}
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }
</code>```

My intern-routing.module.ts:

```<code>import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { DashboardSiteComponent } from './sites/dashboard-site/dashboard-site.component';

const routes: Routes = [
  {
    path: '', children: [
      { path: 'dashboard', component: DashboardSiteComponent }
    ]
  }
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class InternRoutingModule { }
</code>```

After I added the following htaccess file to my htdocs folder I am not getting an 404 error any more but the page is just empty.
.htaccess file:

```<code>RewriteEngine On

    # -- REDIRECTION to https (optional):
    # If you need this, uncomment the next two commands
    # RewriteCond %{HTTPS} !on
    # RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
    # --

    RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]
    RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d

    RewriteRule ^.*$ - [NC,L]
    RewriteRule ^(.*) index.html [NC,L]
</code>```

I have also already changed the base href in index.html to <base href="./"> but this didn't solve my problem as well.

答:
Build your app like this using angular cli

```<code>ng build --prod --base-href /<project_name>/
</code>```

Try with this one and let me know as It works for me

```<code><IfModule mod_rewrite.c>
 RewriteEngine On
 RewriteBase /
 RewriteRule ^index\.html$ - [L]
 RewriteCond %{REQUEST_FILENAME} !-f
 RewriteCond %{REQUEST_FILENAME} !-d
 RewriteRule . /index.html [L]
</IfModule>
</code>```

Body:
I am trying to build my angular app und serve it on xampp, but after building my Angular Project and copying the dist folder into the htdocs folder, I cannot access the routing modules.
When running the angular app with ng serve, I have no problems accessing the route in the module, but after building it, I am getting an 404 error when trying to acess a route thats in the routing module.

The routes that are in the app module work just fine.

My app-routing.module.ts:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

const routes: Routes = [
  {path: 'intern', loadChildren: () => import('./intern/intern.module').then(m => m.InternModule)}
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

My intern-routing.module.ts:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { DashboardSiteComponent } from './sites/dashboard-site/dashboard-site.component';

const routes: Routes = [
  {
    path: '', children: [
      { path: 'dashboard', component: DashboardSiteComponent }
    ]
  }
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class InternRoutingModule { }

After I added the following htaccess file to my htdocs folder I am not getting an 404 error any more but the page is just empty.
.htaccess file:

RewriteEngine On

    # -- REDIRECTION to https (optional):
    # If you need this, uncomment the next two commands
    # RewriteCond %{HTTPS} !on
    # RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
    # --

    RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]
    RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d

    RewriteRule ^.*$ - [NC,L]
    RewriteRule ^(.*) index.html [NC,L]

I have also already changed the base href in index.html to <base href="./"> but this didn't solve my problem as well.

Body:
Build your app like this using angular cli

ng build --prod --base-href /<project_name>/

Try with this one and let me know as It works for me

<IfModule mod_rewrite.c>
 RewriteEngine On
 RewriteBase /
 RewriteRule ^index\.html$ - [L]
 RewriteCond %{REQUEST_FILENAME} !-f
 RewriteCond %{REQUEST_FILENAME} !-d
 RewriteRule . /index.html [L]
</IfModule>


问:
What is the Authentication scope necessary to read comments in Google Sheets from Python
I can't figure out what authentication scope I need to get comments from a file.  I ran this code:

```<code>SCOPES = ['https://spreadsheets.google.com/feeds',
         'https://www.googleapis.com/auth/drive']
"""Shows basic usage of the Drive v3 API.
Prints the names and ids of the first 10 files the user has access to.
"""
creds = None
# The file token.pickle stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists('token.pickle'):
    with open('token.pickle', 'rb') as token:
        creds = pickle.load(token)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
    if creds and creds.expired and creds.refresh_token:
        creds.refresh(Request())
    else:
        flow = InstalledAppFlow.from_client_secrets_file(
            r'C:\Users\morton.hsiao\OneDrive - 247 Customer Pvt. Ltd\workspace\247\DriveApiCredentials.json', SCOPES)
        creds = flow.run_local_server(port=0)
    # Save the credentials for the next run
    with open('token.pickle', 'wb') as token:
        pickle.dump(creds, token)

service = build('drive', 'v3', credentials=creds)

# Call the Drive v3 API
results = service.files().list(
    pageSize=1, fields="nextPageToken, files(id, name)").execute()
items = results.get('files', [])

if not items:
    print('No files found.')
else:
    print('Files:')
    for item in items:
        print(u'{0} ({1})'.format(item['name'], item['id']))
</code>```

This works fine.  Then I ran this:

```<code>x = service.comments().list(fileId='FILEID).execute()
items = x.get('files', [])
print(items)
</code>```

and I got:
HttpError: https://www.googleapis.com/drive/v3/files/FILEID/comments?alt=json returned "Insufficient Permission: Request had insufficient authentication scopes.">

How do I get a list of scopes sufficient for things such as this?

答:
I figured it out.  Here are a few tips for Drive API v3.

[This documentation][1] is really demoralizing for a non-programmer, but I now know its wrong, I'm not an idiot for this reason.  Do not read it.  Here are two major mistakes.
 1. fileId is not a positional parameter like this documentation leads you to believe.  You have to specify it like VBA, with words before it.  They call that a named parameter
2. You need a fields parameter.  You specify it like fields = "*"

Here's a better [link][2].  It's not an easy link to find and its only for curl, not python.  If you go through the front door, this [link][3] leads to a 404 error. The scope that they tell you is wrong.  The scope that worked for me is:  ['googleapis.com/auth/spreadsheets', "googleapis.com/auth/drive.file", "googleapis.com/auth/drive"].

Also one other subtle victory.  The get method for python is not documented.  My running theory is that you look at the response from the curl thingy and you put the name of the field into get.  So for comments, its "comments".  I've seen "items" in documentation elsewhere.  Ignore it.  I have to say, for people who's full time job is to bang their head against the wall reverse engineering a process the penetrate the CIA or NSA.  You have my respect.  This must be what it feels like.

So here is my full code:

```<code>from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
SCOPES = ['https://www.googleapis.com/auth/spreadsheets', "https://www.googleapis.com/auth/drive.file", "https://www.googleapis.com/auth/drive"]
"""Shows basic usage of the Drive v3 API.
Prints the names and ids of the first 1 files the user has access to.
"""
creds = None
# The file token.pickle stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists('token.pickle'):
    with open('token.pickle', 'rb') as token:
        creds = pickle.load(token)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
    if creds and creds.expired and creds.refresh_token:
        creds.refresh(Request())
    else:
        flow = InstalledAppFlow.from_client_secrets_file(
            'DriveApiCredentials.json', SCOPES)
        creds = flow.run_local_server(port=0)
    # Save the credentials for the next run
    with open('token.pickle', 'wb') as token:
        pickle.dump(creds, token)

service = build('drive', 'v3', credentials=creds)

# Call the Drive v3 API
results = service.files().list(
    pageSize=1, fields="nextPageToken, files(id, name)").execute()
items = results.get('files', [])

if not items:
    print('No files found.')
else:
    print('Files:')
    for item in items:
        print(u'{0} ({1})'.format(item['name'], item['id']))
x = service.comments().list(fileId=secret code from above, fields='*').execute()
items = x.get('comments', [])
print(items)

  [1]: https://developers.google.com/resources/api-libraries/documentation/drive/v3/python/latest/drive_v3.comments.html
  [2]: https://developers.google.com/drive/api/v3/reference/comments/list?apix_params=%7B%22fileId%22%3A%2212TBoX2UI_Yu2MA2ZN3p9f-cZsySE4et1slwpgjZbSzw%22%2C%22fields%22%3A%22*%22%7D
  [3]: https://developers.google.com/drive/api/v3/manage-comments
</code>```

Body:
I can't figure out what authentication scope I need to get comments from a file.  I ran this code:

SCOPES = ['https://spreadsheets.google.com/feeds',
         'https://www.googleapis.com/auth/drive']
"""Shows basic usage of the Drive v3 API.
Prints the names and ids of the first 10 files the user has access to.
"""
creds = None
# The file token.pickle stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists('token.pickle'):
    with open('token.pickle', 'rb') as token:
        creds = pickle.load(token)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
    if creds and creds.expired and creds.refresh_token:
        creds.refresh(Request())
    else:
        flow = InstalledAppFlow.from_client_secrets_file(
            r'C:\Users\morton.hsiao\OneDrive - 247 Customer Pvt. Ltd\workspace\247\DriveApiCredentials.json', SCOPES)
        creds = flow.run_local_server(port=0)
    # Save the credentials for the next run
    with open('token.pickle', 'wb') as token:
        pickle.dump(creds, token)

service = build('drive', 'v3', credentials=creds)

# Call the Drive v3 API
results = service.files().list(
    pageSize=1, fields="nextPageToken, files(id, name)").execute()
items = results.get('files', [])

if not items:
    print('No files found.')
else:
    print('Files:')
    for item in items:
        print(u'{0} ({1})'.format(item['name'], item['id']))

This works fine.  Then I ran this:

x = service.comments().list(fileId='FILEID).execute()
items = x.get('files', [])
print(items)

and I got:
HttpError: https://www.googleapis.com/drive/v3/files/FILEID/comments?alt=json returned "Insufficient Permission: Request had insufficient authentication scopes.">

How do I get a list of scopes sufficient for things such as this?

Body:
I figured it out.  Here are a few tips for Drive API v3.

[This documentation][1] is really demoralizing for a non-programmer, but I now know its wrong, I'm not an idiot for this reason.  Do not read it.  Here are two major mistakes.
 1. fileId is not a positional parameter like this documentation leads you to believe.  You have to specify it like VBA, with words before it.  They call that a named parameter
2. You need a fields parameter.  You specify it like fields = "*"

Here's a better [link][2].  It's not an easy link to find and its only for curl, not python.  If you go through the front door, this [link][3] leads to a 404 error. The scope that they tell you is wrong.  The scope that worked for me is:  ['googleapis.com/auth/spreadsheets', "googleapis.com/auth/drive.file", "googleapis.com/auth/drive"].

Also one other subtle victory.  The get method for python is not documented.  My running theory is that you look at the response from the curl thingy and you put the name of the field into get.  So for comments, its "comments".  I've seen "items" in documentation elsewhere.  Ignore it.  I have to say, for people who's full time job is to bang their head against the wall reverse engineering a process the penetrate the CIA or NSA.  You have my respect.  This must be what it feels like.

So here is my full code:

from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
SCOPES = ['https://www.googleapis.com/auth/spreadsheets', "https://www.googleapis.com/auth/drive.file", "https://www.googleapis.com/auth/drive"]
"""Shows basic usage of the Drive v3 API.
Prints the names and ids of the first 1 files the user has access to.
"""
creds = None
# The file token.pickle stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists('token.pickle'):
    with open('token.pickle', 'rb') as token:
        creds = pickle.load(token)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
    if creds and creds.expired and creds.refresh_token:
        creds.refresh(Request())
    else:
        flow = InstalledAppFlow.from_client_secrets_file(
            'DriveApiCredentials.json', SCOPES)
        creds = flow.run_local_server(port=0)
    # Save the credentials for the next run
    with open('token.pickle', 'wb') as token:
        pickle.dump(creds, token)

service = build('drive', 'v3', credentials=creds)

# Call the Drive v3 API
results = service.files().list(
    pageSize=1, fields="nextPageToken, files(id, name)").execute()
items = results.get('files', [])

if not items:
    print('No files found.')
else:
    print('Files:')
    for item in items:
        print(u'{0} ({1})'.format(item['name'], item['id']))
x = service.comments().list(fileId=secret code from above, fields='*').execute()
items = x.get('comments', [])
print(items)

  [1]: https://developers.google.com/resources/api-libraries/documentation/drive/v3/python/latest/drive_v3.comments.html
  [2]: https://developers.google.com/drive/api/v3/reference/comments/list?apix_params=%7B%22fileId%22%3A%2212TBoX2UI_Yu2MA2ZN3p9f-cZsySE4et1slwpgjZbSzw%22%2C%22fields%22%3A%22*%22%7D
  [3]: https://developers.google.com/drive/api/v3/manage-comments


问:
Python function: Find Change from purchase amount
I'm looking for the most efficient way to figure out a change amount (Quarters, dimes, nickels, and pennies) from a purchase amount. The purchase amount must be less than $1, and the change is from one dollar. I need to know how many quarters, dimes, nickels, and pennies someone would get back.

Would it be best to set up a dictionary?

答:
Your best bet is to probably have a sorted dictionary of coin sizes, and then loop through them checking if your change is greater than the value, add that coin and subtract the value, otherwise move along to the next row in the dictionary.

Eg

```<code>Coins = [50, 25, 10, 5, 2, 1]
ChangeDue = 87
CoinsReturned = []
For I in coins:
   While I >= ChangeDue:
        CoinsReturned.add(I)
        ChangeDue = ChangeDue - I
</code>```

Forgive my lousy python syntax there. Hope that's enough to go on.

OwnerDisplayName: Jason

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Oddthinking

Body:
Your best bet is to probably have a sorted dictionary of coin sizes, and then loop through them checking if your change is greater than the value, add that coin and subtract the value, otherwise move along to the next row in the dictionary.

Eg

Coins = [50, 25, 10, 5, 2, 1]
ChangeDue = 87
CoinsReturned = []
For I in coins:
   While I >= ChangeDue:
        CoinsReturned.add(I)
        ChangeDue = ChangeDue - I

Forgive my lousy python syntax there. Hope that's enough to go on.


问:
react-native-webview: distinguish between window.location caused by script and user clicking the link
Is there a way in react-native-webview to distinguish between user-caused and script-caused navigations?

I see that onLoad[Start,End] and onNavigationStateChange events are fired in both cases. Also, if I add logging to WebViewClient.shouldOverrideUrlLoading() or WebViewClient.shouldInterceptRequest(), both fns are invoked if either window.location is changed inside a script, or if user clicks a link. So how can one distinguish these two?

Thanks!

EDIT: have to clarify, that I have no control over what scripts are loaded and what they are doing on the page.

答:
you can pass query param isUserCause=true in every window.location in user-caused on website end and onNavigationStateChange you can detect isUserCause params

you can pass url like this

```<code>http://www.example.com/index.php?isUserCause=true
</code>```

and in onNavigationStateChange you can parse query params by QS pacakge

```<code>import qs from 'qs';

getQueryParams = (url) => {
    var regex = /\?.+/g;
    const result = url.match(regex);
    if (result && result.length>0) {
      const parsed = qs.parse(result[0], {ignoreQueryPrefix: true});
      return parsed;
    } else {
      return {};
    }
  };

onNavigationStateChange = (navState) => {
    const queryParams=this.getQueryParams(navState.url);
    if(queryParams.isUserCause)
    {
      console.log("user-caused");
    }
    else
    {
      console.log("script-caused");
    }
  };
</code>```

Body:
you can pass query param isUserCause=true in every window.location in user-caused on website end and onNavigationStateChange you can detect isUserCause params

you can pass url like this

http://www.example.com/index.php?isUserCause=true

and in onNavigationStateChange you can parse query params by QS pacakge

import qs from 'qs';

getQueryParams = (url) => {
    var regex = /\?.+/g;
    const result = url.match(regex);
    if (result && result.length>0) {
      const parsed = qs.parse(result[0], {ignoreQueryPrefix: true});
      return parsed;
    } else {
      return {};
    }
  };

onNavigationStateChange = (navState) => {
    const queryParams=this.getQueryParams(navState.url);
    if(queryParams.isUserCause)
    {
      console.log("user-caused");
    }
    else
    {
      console.log("script-caused");
    }
  };


问:
How to avoid if statements which returns value based on the input in java 8
I have input as roleID (of Long data type), so I can not use switch case,
I am using if else statements right now.
I have search for the solution but have not came across with the perfect one.

```<code>RoleEnum fetchProcessForRole(roleID) {
    if (RoleEnum.USER.equals(roleID) {
        return RoleEnum.USER_VALIDATION; // this is of int type
    } else if (RoleEnum.ADMIN.equals(roleID) {
        return RoleEnum.ADMIN_VALIDATION;
    } else if (RoleEnum.MGR.equals(roleID) {
        return RoleEnum.MGR_VALIDATION;
    }
}

RoleEnum {
    USER(1,"USER","userrpt"),
    ADMIN(2,"ADMIN","adminrpt"),
    MGR(3,"MGR","mgrrpt"),
    USER_VALIDATION(4,"USER_VALIDATION","userrpt"),
    ADMIN_VALIDATION(5,"ADMIN_VALIDATION","adminrpt"),
    MGR_VALIDATION(6,"MGR_VALIDATION","mgrrpt");
    // it have int id, String name and its getters
}
</code>```

I want to know if there is any other way to achieve same thing, as the input is Long, I do not want to use switch as it will require lot of conversions.

答:
You can create a static class that stores enum constants on the map. because the third argument for pair of enum constants is the same(USER & USER_VALIDATION and ...) you can init the map base on this param. so the map will initial map<String, RoleEnum> which the key is third param and value is enum constant.
consider this fact that I supposed USER_VALIDATION comes after USER and for others too. after finding the roleEnum based on id then you can get pair of it from the map based on roleEnum's third param.

```<code>enum RoleEnum {
  USER(1, "USER", "userrpt"),
  ADMIN(2, "ADMIN", "adminrpt"),
  MGR(3, "MGR", "mgrrpt"),
  USER_VALIDATION(4, "USER_VALIDATION", "userrpt"),
  ADMIN_VALIDATION(5, "ADMIN_VALIDATION", "adminrpt"),
  MGR_VALIDATION(6, "MGR_VALIDATION", "mgrrpt");

  static class Holder {
     private static HashMap<String, RoleEnum> map = new HashMap<>();

     public HashMap<String, RoleEnum> getMap() {
        return map;
     }
  }

  private long id;
  private String name;
  private String des;

  RoleEnum(long id, String name, String des) {
    this.id = id;
    this.name = name;
    this.des = des;
    Holder.map.put(this.getDes(), this);
  }

  public static Map<String, RoleEnum> getMap() {
    return Holder.map;
  }

 public static RoleEnum findById(Long id) {
     RoleEnum roleEnum = EnumSet.allOf(RoleEnum.class)
            .stream().filter(role -> role.getId() == id)
            .findFirst().orElse(null);
     return getMap().get(roleEnum.getDes());
  }
}
</code>```

Body:
I have input as roleID (of Long data type), so I can not use switch case,
I am using if else statements right now.
I have search for the solution but have not came across with the perfect one.

RoleEnum fetchProcessForRole(roleID) {
    if (RoleEnum.USER.equals(roleID) {
        return RoleEnum.USER_VALIDATION; // this is of int type
    } else if (RoleEnum.ADMIN.equals(roleID) {
        return RoleEnum.ADMIN_VALIDATION;
    } else if (RoleEnum.MGR.equals(roleID) {
        return RoleEnum.MGR_VALIDATION;
    }
}

RoleEnum {
    USER(1,"USER","userrpt"),
    ADMIN(2,"ADMIN","adminrpt"),
    MGR(3,"MGR","mgrrpt"),
    USER_VALIDATION(4,"USER_VALIDATION","userrpt"),
    ADMIN_VALIDATION(5,"ADMIN_VALIDATION","adminrpt"),
    MGR_VALIDATION(6,"MGR_VALIDATION","mgrrpt");
    // it have int id, String name and its getters
}

I want to know if there is any other way to achieve same thing, as the input is Long, I do not want to use switch as it will require lot of conversions.

Body:
You can create a static class that stores enum constants on the map. because the third argument for pair of enum constants is the same(USER & USER_VALIDATION and ...) you can init the map base on this param. so the map will initial map<String, RoleEnum> which the key is third param and value is enum constant.
consider this fact that I supposed USER_VALIDATION comes after USER and for others too. after finding the roleEnum based on id then you can get pair of it from the map based on roleEnum's third param.

enum RoleEnum {
  USER(1, "USER", "userrpt"),
  ADMIN(2, "ADMIN", "adminrpt"),
  MGR(3, "MGR", "mgrrpt"),
  USER_VALIDATION(4, "USER_VALIDATION", "userrpt"),
  ADMIN_VALIDATION(5, "ADMIN_VALIDATION", "adminrpt"),
  MGR_VALIDATION(6, "MGR_VALIDATION", "mgrrpt");

  static class Holder {
     private static HashMap<String, RoleEnum> map = new HashMap<>();

     public HashMap<String, RoleEnum> getMap() {
        return map;
     }
  }

  private long id;
  private String name;
  private String des;

  RoleEnum(long id, String name, String des) {
    this.id = id;
    this.name = name;
    this.des = des;
    Holder.map.put(this.getDes(), this);
  }

  public static Map<String, RoleEnum> getMap() {
    return Holder.map;
  }

 public static RoleEnum findById(Long id) {
     RoleEnum roleEnum = EnumSet.allOf(RoleEnum.class)
            .stream().filter(role -> role.getId() == id)
            .findFirst().orElse(null);
     return getMap().get(roleEnum.getDes());
  }
}


问:
Android LiveData: How to do an ArrayList<LiveData<RetrofitObject>>?
I am creating an app with MVVM architecture and I ran into an issue of getting a list of LiveData to show in the View.

In my ViewModel I have a getAll() function that retrieves a list of strings from the database using Room. From there, I get the strings and call my Retrofit function to send each string individually to a web-server that returns an object. Here is where my issue occurs.

From the MVVM tutorials I see online, they usually have the LiveData> style but in this since I am getting each object individually, it becomes List> but I don't think this is the correct way of doing it because in my View I would need to do a ForEach loop to observe each LiveData object in the list.

I have tried other work arounds but it doesn't seem to work. Is there a better way of doing this?

DAO

```<code>@Query("SELECT * FROM table")
    fun getAll(): LiveData<List<String>>
</code>```

Repository

```<code>fun getAll(): LiveData<List<String>> {
        return dao.getAll()
    }

fun getRetrofitObject(s: String): LiveData<RetrofitObject> {
        api = jsonApi.getRetrofitObjectInfo(s, API_KEY)
        val retrofitObject: MutableLiveData<RetrofitObject> = MutableLiveData()
        api.enqueue(object : Callback<RetrofitObject> {
            override fun onFailure(call: Call<RetrofitObject>?, t: Throwable?) {
                Log.d("TEST", "Code: " + t.toString())
            }

            override fun onResponse(call: Call<RetrofitObject>?, response: Response<RetrofitObject>?) {
                if (response!!.isSuccessful) {
                    retrofitObject.value = response.body()
                }
            }
        })
        return retrofitObject
    }
</code>```

MainActivityViewModel (ViewModel)

```<code>var objectList ArrayList<LiveData<retrofitObject>> = ArrayList()

// This is getting objects using Retrofit
fun getRetrofitObject(s: String): LiveData<retrofitObject> {
        return repo.getRetrofitObject(s)
    }

// This is getting all the strings from the internal database
fun getAll(): ArrayList<LiveData<retroFitObject>> {
        repo.getAll().value?.forEach {it ->
            objectList.add(getRetrofitObject(it)) //How else would I be able to do this?
        }
        return objectList
    }
</code>```

MainActivity (View)

```<code>override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mainActivityViewModel.getAll().forEach {
                        it.observe(this, Observer {it ->
                            mainActivityViewModel.objectList.add(it) //Here is part of the issue since I don't want to use a forloop in the View

                        })
                    }
                    adapter.objectList = mainActivityViewModel.objectList
                    recyclerView.adapter = adapter
}

</code>```

Thanks, let me know if there is anything else needed or confusion!

答:
There might be other methods exist I don't know about them.

But you can deal with situation using Transformations for more information please look at documentation page.
Transformations.switchMap(LiveData trigger, Function> func)

You don't have to put the live data observer inside for loop.

Body:
I am creating an app with MVVM architecture and I ran into an issue of getting a list of LiveData to show in the View.

In my ViewModel I have a getAll() function that retrieves a list of strings from the database using Room. From there, I get the strings and call my Retrofit function to send each string individually to a web-server that returns an object. Here is where my issue occurs.

From the MVVM tutorials I see online, they usually have the LiveData> style but in this since I am getting each object individually, it becomes List> but I don't think this is the correct way of doing it because in my View I would need to do a ForEach loop to observe each LiveData object in the list.

I have tried other work arounds but it doesn't seem to work. Is there a better way of doing this?

DAO

@Query("SELECT * FROM table")
    fun getAll(): LiveData<List<String>>

Repository

fun getAll(): LiveData<List<String>> {
        return dao.getAll()
    }

fun getRetrofitObject(s: String): LiveData<RetrofitObject> {
        api = jsonApi.getRetrofitObjectInfo(s, API_KEY)
        val retrofitObject: MutableLiveData<RetrofitObject> = MutableLiveData()
        api.enqueue(object : Callback<RetrofitObject> {
            override fun onFailure(call: Call<RetrofitObject>?, t: Throwable?) {
                Log.d("TEST", "Code: " + t.toString())
            }

            override fun onResponse(call: Call<RetrofitObject>?, response: Response<RetrofitObject>?) {
                if (response!!.isSuccessful) {
                    retrofitObject.value = response.body()
                }
            }
        })
        return retrofitObject
    }

MainActivityViewModel (ViewModel)

var objectList ArrayList<LiveData<retrofitObject>> = ArrayList()

// This is getting objects using Retrofit
fun getRetrofitObject(s: String): LiveData<retrofitObject> {
        return repo.getRetrofitObject(s)
    }

// This is getting all the strings from the internal database
fun getAll(): ArrayList<LiveData<retroFitObject>> {
        repo.getAll().value?.forEach {it ->
            objectList.add(getRetrofitObject(it)) //How else would I be able to do this?
        }
        return objectList
    }

MainActivity (View)

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mainActivityViewModel.getAll().forEach {
                        it.observe(this, Observer {it ->
                            mainActivityViewModel.objectList.add(it) //Here is part of the issue since I don't want to use a forloop in the View

                        })
                    }
                    adapter.objectList = mainActivityViewModel.objectList
                    recyclerView.adapter = adapter
}

Thanks, let me know if there is anything else needed or confusion!


问:
Timezone differences resulting in an incorrect time remaining when using Laravel and javascript
I'm trying to get the remaining time in a booking page. I'm giving javascript the date and exact starting time of a booking as follows :

```<code>if (Auth()->user()->role == 1) { //this is the owner of the time slot that was selected. So it makes sense not to set a time zone for him.
    $dateTime = Carbon::parse($dateTime . ' ' . $book->from);
} else { //this is a normal user
    $dateTime = Carbon::parse($dateTime . ' ' . $book->from)->setTimezone(Auth()->user()->time_zone);
}
</code>```

And the javascript function handles it as follows :

```<code><script>
$(document).ready(function() {
    var tomorrow = new Date();
    tomorrow.setDate(tomorrow.getDate() + 1)
    $('.date').datepicker({minDate: tomorrow, dateFormat: 'yy-mm-dd'});

    currentDate = new Date();
    currentDateNextFiveDays =  currentDate;
    remainingTime =  new Date(currentDateNextFiveDays) - new Date(currentDate);
    // Set the date we're counting down to
    var countDownDate = new Date("{{$dateTime}}");
    // Update the count down every 1 second
    var x = setInterval(function() {
        // Get today's date and time
        var now = new Date().getTime();
        // Find the distance between now and the count down date
        var distance = countDownDate - now;
        // Time calculations for days, hours, minutes and seconds
        var days = Math.floor(distance / (1000 * 60 * 60 * 24));
        // days = days * 24;
        var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        // hours = hours + days;
        var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
        var seconds = Math.floor((distance % (1000 * 60)) / 1000);
        // Display the result in the element with id="demo"
        if(-3000 < distance && distance < -1000) {
            location.reload();
        }
        if(distance > 0) {
            if(days > 0) {
                $('.remaining-time').text(days + " " + "@lang('profile.lang_day')");
            }
            else {
                $('.remaining-time').text(hours + " " + "@lang('profile.lang_hour')" + " " + minutes + " " + "@lang('profile.lang_minutes')" + " " + seconds + " " + "@lang('profile.lang_second')");
            }
        }
        else {
            $('.remaining-time-button').hide();
        }
    }, 1000);
});

Date.prototype.addDays = function(days) {
    var date = new Date(this.valueOf());
    date.setDate(date.getDate() + days);
    return date;
}
</code>```

The code works perfectly fine but whenever I use two browsers from different countries, it will give different results. (Plus 3 hours, plus 10 hours.. depending on the time zones)

The server time zone is located in Asia/Riyadh. And I do store the user's time zone each time they login but I'm not sure how is that going to help me in this case. I show the date and times correctly without any problem (In relative to the timezone) but the remaining time is incorrect.

答:
The comment assertion is not accurate. Doing differently for users in the same or other timezone is not relevant. You should give to JS the ISO string with GMT timezone (that's done automatically if you send it through a JSON response. You will get a string like 2020-06-30T19:49:03.123Z where Z means GMT.

So use:

```<code> $dateTime = Carbon::parse($dateTime . ' ' . $book->from)->toJSON();
</code>```

For every users. So new Date("{{$dateTime}}"); will perfectly understand it's a GMT date and it will convert it. So if your JS script doesn't mess up the timezone, it will be the same duration everywhere.

Body:
I'm trying to get the remaining time in a booking page. I'm giving javascript the date and exact starting time of a booking as follows :

if (Auth()->user()->role == 1) { //this is the owner of the time slot that was selected. So it makes sense not to set a time zone for him.
    $dateTime = Carbon::parse($dateTime . ' ' . $book->from);
} else { //this is a normal user
    $dateTime = Carbon::parse($dateTime . ' ' . $book->from)->setTimezone(Auth()->user()->time_zone);
}

And the javascript function handles it as follows :

Body:
The comment assertion is not accurate. Doing differently for users in the same or other timezone is not relevant. You should give to JS the ISO string with GMT timezone (that's done automatically if you send it through a JSON response. You will get a string like 2020-06-30T19:49:03.123Z where Z means GMT.

So use:

 $dateTime = Carbon::parse($dateTime . ' ' . $book->from)->toJSON();

For every users. So new Date("{{$dateTime}}"); will perfectly understand it's a GMT date and it will convert it. So if your JS script doesn't mess up the timezone, it will be the same duration everywhere.


问:
Image in gridview in yii2
How to put an image in GridView in yii2?I have the following code. But its not displaying the image as it is not giving any image url. Where to put the image url?</p>

```<code> <?php echo GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => [
        ['class' => 'yii\grid\SerialColumn'],

        'c_id',
        'name:ntext',
        'description:ntext',
        array(
                'format' => 'image',
               'attribute'=>'logo',

),

        ['class' => 'yii\grid\ActionColumn'],
    ],
]); ?>
</code>```

答:
```<code><?php echo GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => [
        ['class' => 'yii\grid\SerialColumn'],

        'c_id',
        'name:ntext',
        'description:ntext',
        'logo:image',

        ['class' => 'yii\grid\ActionColumn'],
    ],
]); ?>
</code>```

Title: Image in gridview in yii2

Body:
How to put an image in GridView in yii2?I have the following code. But its not displaying the image as it is not giving any image url. Where to put the image url?

 <?php echo GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => [
        ['class' => 'yii\grid\SerialColumn'],

        'c_id',
        'name:ntext',
        'description:ntext',
        array(
                'format' => 'image',
               'attribute'=>'logo',

),

        ['class' => 'yii\grid\ActionColumn'],
    ],
]); ?>


问:
Discord.py SSLCertVerificationError
I have been working on a bot and last night it was working just fine operating as needed but this morning when I opened the bot in my terminal I got this following error:

```<code>Traceback (most recent call last):
  File "d:/Documents/Bots/DS BOT/bot.py", line 58, in <module>
    bot.run(token, bot=False)
  File "C:\Python38\lib\site-packages\discord\client.py", line 640, in run
    return future.result()
  File "C:\Python38\lib\site-packages\discord\client.py", line 621, in runner
    await self.start(*args, **kwargs)
  File "C:\Python38\lib\site-packages\discord\client.py", line 584, in start
    await self.login(*args, bot=bot)
  File "C:\Python38\lib\site-packages\discord\client.py", line 442, in login
    await self.http.static_login(token.strip(), bot=bot)
  File "C:\Python38\lib\site-packages\discord\http.py", line 261, in static_login
    data = await self.request(Route('GET', '/users/@me'))
  File "C:\Python38\lib\site-packages\discord\http.py", line 165, in request
    async with self.__session.request(method, url, **kwargs) as r:
  File "C:\Python38\lib\site-packages\aiohttp\client.py", line 1012, in __aenter__
    self._resp = await self._coro
  File "C:\Python38\lib\site-packages\aiohttp\client.py", line 480, in _request
    conn = await self._connector.connect(
  File "C:\Python38\lib\site-packages\aiohttp\connector.py", line 523, in connect
    proto = await self._create_connection(req, traces, timeout)
  File "C:\Python38\lib\site-packages\aiohttp\connector.py", line 858, in _create_connection
    _, proto = await self._create_direct_connection(
  File "C:\Python38\lib\site-packages\aiohttp\connector.py", line 1004, in _create_direct_connection
    raise last_exc
  File "C:\Python38\lib\site-packages\aiohttp\connector.py", line 980, in _create_direct_connection
    transp, proto = await self._wrap_create_connection(
  File "C:\Python38\lib\site-packages\aiohttp\connector.py", line 938, in _wrap_create_connection
    raise ClientConnectorCertificateError(
aiohttp.client_exceptions.ClientConnectorCertificateError: Cannot connect to host discordapp.com:443 ssl:True [SSLCertVerificationError: (1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:1108)')]
</code>```

My token is up to date, I have the latest versions of both Discord.py and python

any help is greatly appreciated

答:
Since you are using Windows,

Open Internet Explorer preferably as Administrator

Open discord.com

On address bar, click on the lock icon

Click on Install Certificates and install the certificate

Probably you are facing the problem because they were using Sectigo Certificate which expired on 30th May 2020.

Title: Discord.py SSLCertVerificationError

Body:
I have been working on a bot and last night it was working just fine operating as needed but this morning when I opened the bot in my terminal I got this following error:

Traceback (most recent call last):
  File "d:/Documents/Bots/DS BOT/bot.py", line 58, in <module>
    bot.run(token, bot=False)
  File "C:\Python38\lib\site-packages\discord\client.py", line 640, in run
    return future.result()
  File "C:\Python38\lib\site-packages\discord\client.py", line 621, in runner
    await self.start(*args, **kwargs)
  File "C:\Python38\lib\site-packages\discord\client.py", line 584, in start
    await self.login(*args, bot=bot)
  File "C:\Python38\lib\site-packages\discord\client.py", line 442, in login
    await self.http.static_login(token.strip(), bot=bot)
  File "C:\Python38\lib\site-packages\discord\http.py", line 261, in static_login
    data = await self.request(Route('GET', '/users/@me'))
  File "C:\Python38\lib\site-packages\discord\http.py", line 165, in request
    async with self.__session.request(method, url, **kwargs) as r:
  File "C:\Python38\lib\site-packages\aiohttp\client.py", line 1012, in __aenter__
    self._resp = await self._coro
  File "C:\Python38\lib\site-packages\aiohttp\client.py", line 480, in _request
    conn = await self._connector.connect(
  File "C:\Python38\lib\site-packages\aiohttp\connector.py", line 523, in connect
    proto = await self._create_connection(req, traces, timeout)
  File "C:\Python38\lib\site-packages\aiohttp\connector.py", line 858, in _create_connection
    _, proto = await self._create_direct_connection(
  File "C:\Python38\lib\site-packages\aiohttp\connector.py", line 1004, in _create_direct_connection
    raise last_exc
  File "C:\Python38\lib\site-packages\aiohttp\connector.py", line 980, in _create_direct_connection
    transp, proto = await self._wrap_create_connection(
  File "C:\Python38\lib\site-packages\aiohttp\connector.py", line 938, in _wrap_create_connection
    raise ClientConnectorCertificateError(
aiohttp.client_exceptions.ClientConnectorCertificateError: Cannot connect to host discordapp.com:443 ssl:True [SSLCertVerificationError: (1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:1108)')]

My token is up to date, I have the latest versions of both Discord.py and python

any help is greatly appreciated


问:
Help for making Complex List View
I am having a problem creating ListView. Its a complex ListView with each row having 1 imageview and 2 textviews.It looks something like this:

The row has 1 image on the left and the 2 texts are on the right of the image one below the other and within the height of the image

Can anybody guide me on this.
The 2 texts will keep on changing for each row.
Texts are stored in a string array.

Thanks

答: Please check below this or this or this</p>

Title: Help for making Complex List View

Body: Please check below this or this or this