问:
Moving labels in ggplot graph so that they match the x-axis tick marks
I am working with a bar graph, and am trying to adjust the labels (location, in my dataset) so that they line up with the x-axis tick marks. The data is below:

```<code>data <- data.frame(location=c('Allen',
                              'Allen',
                              'Anderson',
                              'Atchison',
                              'Barber',
                              'Barber',
                              'Bourbon',
                              'Brown',
                              'Brown',
                              'Butler',
                              'Butler',
                              'Butler',
                              'Butler',
                              'Cherokee',
                              'Cherokee',
                              'Cheyenne',
                              'Comanche',
                              'Cowley',
                              'Crawford',
                              'Crawford',
                              'Crawford',
                              'Decatur',
                              'Dickinson',
                              'Dickinson',
                              'Dickinson',
                              'Doniphan',
                              'Douglas',
                              'Douglas',
                              'Douglas',
                              'Douglas',
                              'Edwards',
                              'Edwards',
                              'Ellis',
                              'Ellis',
                              'Finney',
                              'Finney',
                              'Finney',
                              'Ford',
                              'Geary',
                              'Gove',
                              'Graham',
                              'Grant',
                              'Gray',
                              'Harper',
                              'Harper',
                              'Harvey',
                              'Harvey',
                              'Harvey',
                              'Jackson',
                              'Jefferson',
                              'Jefferson',
                              'Jefferson',
                              'Jefferson',
                              'Jewell',
                              'Johnson',
                              'Johnson',
                              'Johnson',
                              'Johnson',
                              'Johnson',
                              'Johnson',
                              'Johnson',
                              'Johnson',
                              'Johnson',
                              'Johnson',
                              'Johnson',
                              'Labette',
                              'Labette',
                              'Labette',
                              'Lane',
                              'Leavenworth',
                              'Leavenworth',
                              'Leavenworth',
                              'Leavenworth',
                              'Leavenworth',
                              'Leavenworth',
                              'Linn',
                              'Lyon',
                              'Marion',
                              'Marion',
                              'Marshall',
                              'Marshall',
                              'Meade',
                              'Miami',
                              'Miami',
                              'Miami',
                              'Miami',
                              'Miami',
                              'Miami',
                              'Montgomery',
                              'Montgomery',
                              'Montgomery',
                              'Montgomery',
                              'Montgomery',
                              'Morris',
                              'Nemaha',
                              'Neosho',
                              'Ness',
                              'Osage',
                              'Osage',
                              'Pottawatomie',
                              'Pottawatomie',
                              'Pottawatomie',
                              'Reno',
                              'Reno',
                              'Reno',
                              'Reno',
                              'Reno',
                              'Reno',
                              'Republic',
                              'Rice',
                              'Riley',
                              'Riley',
                              'Riley',
                              'Rooks',
                              'Rush',
                              'Sedgwick',
                              'Sedgwick',
                              'Sedgwick',
                              'Sedgwick',
                              'Sedgwick',
                              'Sedgwick',
                              'Sedgwick',
                              'Sedgwick',
                              'Sedgwick',
                              'Sedgwick',
                              'Sedgwick',
                              'Sedgwick',
                              'Sedgwick',
                              'Sedgwick',
                              'Sedgwick',
                              'Sedgwick',
                              'Sedgwick',
                              'Sedgwick',
                              'Sedgwick',
                              'Sedgwick',
                              'Sedgwick',
                              'Shawnee',
                              'Shawnee',
                              'Shawnee',
                              'Shawnee',
                              'Shawnee',
                              'Shawnee',
                              'Shawnee',
                              'Shawnee',
                              'Shawnee',
                              'Shawnee',
                              'Sheridan',
                              'Smith',
                              'Stanton',
                              'Sumner',
                              'Sumner',
                              'Trego',
                              'Wabaunsee',
                              'Wilson',
                              'Wilson',
                              'Woodson',
                              'Wyandotte',
                              'Wyandotte',
                              'Wyandotte',
                              'Wyandotte',
                              'Wyandotte',
                              'Wyandotte',
                              'Wyandotte',
                              'Wyandotte',
                              'Wyandotte',
                              'Wyandotte',
                              'Wyandotte',
                              'Wyandotte',
                              'Wyandotte',
                              'Wyandotte',
                              'Wyandotte'),
                   vehicles = c(43472,
                                51429,
                                53577,
                                54936,
                                56705,
                                63875,
                                46172,
                                54135,
                                53690,
                                72173,
                                93634,
                                83378,
                                72500,
                                46458,
                                53843,
                                55352,
                                58173,
                                78182,
                                56406,
                                45114,
                                74543,
                                43646,
                                68798,
                                57917,
                                46219,
                                62188,
                                53445,
                                79500,
                                86150,
                                63523,
                                55598,
                                58438,
                                65673,
                                71417,
                                73958,
                                117703,
                                36750,
                                52349,
                                50906,
                                56667,
                                67292,
                                65000,
                                67381,
                                54044,
                                49648,
                                55774,
                                78272,
                                67056,
                                69962,
                                73036,
                                74688,
                                63177,
                                66189,
                                51932,
                                67266,
                                27860,
                                72358,
                                106582,
                                72923,
                                71667,
                                115741,
                                97734,
                                113750,
                                98359,
                                0,
                                49193,
                                48553,
                                45313,
                                64805,
                                76667,
                                90597,
                                95944,
                                88431,
                                74613,
                                75625,
                                54848,
                                74750,
                                65057,
                                63824,
                                54250,
                                55651,
                                61797,
                                90083,
                                96450,
                                91549,
                                79722,
                                74543,
                                66111,
                                55865,
                                43750,
                                46310,
                                62411,
                                58750,
                                52838,
                                62813,
                                60972,
                                63125,
                                64495,
                                54492,
                                82574,
                                68850,
                                57557,
                                41100,
                                70313,
                                43152,
                                62482,
                                59155,
                                47713,
                                46613,
                                66583,
                                42853,
                                65773,
                                0,
                                54531,
                                52750,
                                25455,
                                28889,
                                55682,
                                52926,
                                43646,
                                26857,
                                34224,
                                81167,
                                81917,
                                79556,
                                86826,
                                80326,
                                43333,
                                84325,
                                103333,
                                78279,
                                97940,
                                71085,
                                91146,
                                98008,
                                83750,
                                44554,
                                78065,
                                75500,
                                84615,
                                76004,
                                88480,
                                80392,
                                65472,
                                77957,
                                90848,
                                59342,
                                49821,
                                50703,
                                60147,
                                73897,
                                57017,
                                68966,
                                48750,
                                45924,
                                50568,
                                0,
                                22399,
                                30625,
                                29676,
                                36250,
                                0,
                                0,
                                66806,
                                41714,
                                0,
                                0,
                                106574,
                                110909,
                                73487,
                                97083))
</code>```

Here is the code that I am using to generate my graph:

```<code>library(ggplot2)

ggplot(data = data, aes(x = location, y = vehicles)) +
  geom_bar(stat = 'identity', fill = 'steelblue') +
  theme(axis.text.x = element_text(angle = 90)) +
  xlab("Location") +
  ylab("Vehicles")+
  ggtitle("Vehicles per location")
</code>```

As can be seen below, the labels do not match up with the tick marks. I need to shift them slightly to the left. How can I fix this?

答:
This is in addition to Allan's sensible answer, but I just wanted to add the perhaps less widely known option that you can set the angle in the axis guide, which automatically adjust hjust/vjust for you. Especially for angles like 45 degrees, it is easier than using the theme.

library(ggplot2)

ggplot(data = data, aes(x = location, y = vehicles)) +
  geom_bar(stat = 'identity', fill = 'steelblue') +
  guides(x = guide_axis(angle = 90)) +
  xlab("Location") +
  ylab("Vehicles")+
  ggtitle("Vehicles per location")
```

Body:
I am working with a bar graph, and am trying to adjust the labels (location, in my dataset) so that they line up with the x-axis tick marks. The data is below:

data <- data.frame(location=c('Allen',
                              'Allen',
                              'Anderson',
                              'Atchison',
                              'Barber',
                              'Barber',
                              'Bourbon',
                              'Brown',
                              'Brown',
                              'Butler',
                              'Butler',
                              'Butler',
                              'Butler',
                              'Cherokee',
                              'Cherokee',
                              'Cheyenne',
                              'Comanche',
                              'Cowley',
                              'Crawford',
                              'Crawford',
                              'Crawford',
                              'Decatur',
                              'Dickinson',
                              'Dickinson',
                              'Dickinson',
                              'Doniphan',
                              'Douglas',
                              'Douglas',
                              'Douglas',
                              'Douglas',
                              'Edwards',
                              'Edwards',
                              'Ellis',
                              'Ellis',
                              'Finney',
                              'Finney',
                              'Finney',
                              'Ford',
                              'Geary',
                              'Gove',
                              'Graham',
                              'Grant',
                              'Gray',
                              'Harper',
                              'Harper',
                              'Harvey',
                              'Harvey',
                              'Harvey',
                              'Jackson',
                              'Jefferson',
                              'Jefferson',
                              'Jefferson',
                              'Jefferson',
                              'Jewell',
                              'Johnson',
                              'Johnson',
                              'Johnson',
                              'Johnson',
                              'Johnson',
                              'Johnson',
                              'Johnson',
                              'Johnson',
                              'Johnson',
                              'Johnson',
                              'Johnson',
                              'Labette',
                              'Labette',
                              'Labette',
                              'Lane',
                              'Leavenworth',
                              'Leavenworth',
                              'Leavenworth',
                              'Leavenworth',
                              'Leavenworth',
                              'Leavenworth',
                              'Linn',
                              'Lyon',
                              'Marion',
                              'Marion',
                              'Marshall',
                              'Marshall',
                              'Meade',
                              'Miami',
                              'Miami',
                              'Miami',
                              'Miami',
                              'Miami',
                              'Miami',
                              'Montgomery',
                              'Montgomery',
                              'Montgomery',
                              'Montgomery',
                              'Montgomery',
                              'Morris',
                              'Nemaha',
                              'Neosho',
                              'Ness',
                              'Osage',
                              'Osage',
                              'Pottawatomie',
                              'Pottawatomie',
                              'Pottawatomie',
                              'Reno',
                              'Reno',
                              'Reno',
                              'Reno',
                              'Reno',
                              'Reno',
                              'Republic',
                              'Rice',
                              'Riley',
                              'Riley',
                              'Riley',
                              'Rooks',
                              'Rush',
                              'Sedgwick',
                              'Sedgwick',
                              'Sedgwick',
                              'Sedgwick',
                              'Sedgwick',
                              'Sedgwick',
                              'Sedgwick',
                              'Sedgwick',
                              'Sedgwick',
                              'Sedgwick',
                              'Sedgwick',
                              'Sedgwick',
                              'Sedgwick',
                              'Sedgwick',
                              'Sedgwick',
                              'Sedgwick',
                              'Sedgwick',
                              'Sedgwick',
                              'Sedgwick',
                              'Sedgwick',
                              'Sedgwick',
                              'Shawnee',
                              'Shawnee',
                              'Shawnee',
                              'Shawnee',
                              'Shawnee',
                              'Shawnee',
                              'Shawnee',
                              'Shawnee',
                              'Shawnee',
                              'Shawnee',
                              'Sheridan',
                              'Smith',
                              'Stanton',
                              'Sumner',
                              'Sumner',
                              'Trego',
                              'Wabaunsee',
                              'Wilson',
                              'Wilson',
                              'Woodson',
                              'Wyandotte',
                              'Wyandotte',
                              'Wyandotte',
                              'Wyandotte',
                              'Wyandotte',
                              'Wyandotte',
                              'Wyandotte',
                              'Wyandotte',
                              'Wyandotte',
                              'Wyandotte',
                              'Wyandotte',
                              'Wyandotte',
                              'Wyandotte',
                              'Wyandotte',
                              'Wyandotte'),
                   vehicles = c(43472,
                                51429,
                                53577,
                                54936,
                                56705,
                                63875,
                                46172,
                                54135,
                                53690,
                                72173,
                                93634,
                                83378,
                                72500,
                                46458,
                                53843,
                                55352,
                                58173,
                                78182,
                                56406,
                                45114,
                                74543,
                                43646,
                                68798,
                                57917,
                                46219,
                                62188,
                                53445,
                                79500,
                                86150,
                                63523,
                                55598,
                                58438,
                                65673,
                                71417,
                                73958,
                                117703,
                                36750,
                                52349,
                                50906,
                                56667,
                                67292,
                                65000,
                                67381,
                                54044,
                                49648,
                                55774,
                                78272,
                                67056,
                                69962,
                                73036,
                                74688,
                                63177,
                                66189,
                                51932,
                                67266,
                                27860,
                                72358,
                                106582,
                                72923,
                                71667,
                                115741,
                                97734,
                                113750,
                                98359,
                                0,
                                49193,
                                48553,
                                45313,
                                64805,
                                76667,
                                90597,
                                95944,
                                88431,
                                74613,
                                75625,
                                54848,
                                74750,
                                65057,
                                63824,
                                54250,
                                55651,
                                61797,
                                90083,
                                96450,
                                91549,
                                79722,
                                74543,
                                66111,
                                55865,
                                43750,
                                46310,
                                62411,
                                58750,
                                52838,
                                62813,
                                60972,
                                63125,
                                64495,
                                54492,
                                82574,
                                68850,
                                57557,
                                41100,
                                70313,
                                43152,
                                62482,
                                59155,
                                47713,
                                46613,
                                66583,
                                42853,
                                65773,
                                0,
                                54531,
                                52750,
                                25455,
                                28889,
                                55682,
                                52926,
                                43646,
                                26857,
                                34224,
                                81167,
                                81917,
                                79556,
                                86826,
                                80326,
                                43333,
                                84325,
                                103333,
                                78279,
                                97940,
                                71085,
                                91146,
                                98008,
                                83750,
                                44554,
                                78065,
                                75500,
                                84615,
                                76004,
                                88480,
                                80392,
                                65472,
                                77957,
                                90848,
                                59342,
                                49821,
                                50703,
                                60147,
                                73897,
                                57017,
                                68966,
                                48750,
                                45924,
                                50568,
                                0,
                                22399,
                                30625,
                                29676,
                                36250,
                                0,
                                0,
                                66806,
                                41714,
                                0,
                                0,
                                106574,
                                110909,
                                73487,
                                97083))

Here is the code that I am using to generate my graph:

library(ggplot2)

ggplot(data = data, aes(x = location, y = vehicles)) +
  geom_bar(stat = 'identity', fill = 'steelblue') +
  theme(axis.text.x = element_text(angle = 90)) +
  xlab("Location") +
  ylab("Vehicles")+
  ggtitle("Vehicles per location")

As can be seen below, the labels do not match up with the tick marks. I need to shift them slightly to the left. How can I fix this?


来源: stackexchange

问:
VMs unable to join domain controller on Hyper-V host
I've setup a Hyper-V machine running Server 2008 R2.  it's configured as a DC for contoso.com (for example).

I'm trying to get a virtual machine to join the Domain, but it says it cannot find a domain controller for that domain.  The virtual can ping the host (servername.contoso.com) ok.

Any thoughs?

thanks.

答: I have installed hyper-v with 2 virtual machines. I set one as DC and the other one i wanted to use it to test exchange. I was having issue with joining. I de-selected the IPv6 option on the VM and that resolved the issue.</p>

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 4.0


问:
Is there a way to trigger a Logic App on a deletion of a record in an Azure SQL table?
Is there a way to trigger a Logic App on a deletion of a record in an Azure SQL table?

I've checked the SQL Connector and there is only When an item is created and When an item is modified, which gives me the C and U in CRUD, but sadly there isn't an out-of-the-box trigger for the D.

I can think of some awful way of polling to get record deletions, but I'm hoping that there is a cleaner solution that some bright person has come up with, however I've had no joy with the Google searching.

答: I added an on delete trigger which adds the id of the deleted record to a secondary table.  I have the logic app look for modifications on the secondary table.</p>


问:
Conditional routing in Angular
I have a route:

```<code>    {
        path: 'business-rules',
        data: { routeName: _('Business rules') },
        component: BusinessRulesComponent,
    },
</code>```

And I'm developing a new component that will replace the BusinessRulesComponent at some point. Users can opt in to the new NewBusinessRulesComponent by using a feature flag.

Now I'm wondering if it's possible to do conditional routing based on the selected feature flag.

I've added a guard CanAccessNewBusinessRules but as far as I know this can only stop a route from showing up:

```<code>    {
        path: 'business-rules',
        data: { routeName: _('Business rules') },
        component: BusinessRulesComponent,
        canActivate: [CanAccessNewBusinessRules]
    },
</code>```

CanAccessNewBusinessRules:

```<code>        const new_business_rules_flagged = await this.companyFeatureFlagsService.getAllFeatureFlags(company.id)
            .then((flags) => flags.includes(possibleFlags.new_business_rules))

        if (new_business_rules_flagged) {
            // this.router.navigate(['new-business-rules'])
            return false;
        }

        return true;
</code>```

Can I change the routing in the guard, or is it better to add another route that's only active when the flag is enabled?

答:
No. you can't do it. A good way to handle situations like this is to return UrlTree from your guard so angular can route to another route.

app-routing.module.ts

```<code>  {
    path: 'page',
    loadChildren: () => import('./pages/home/home.module').then(m => m.HomeModule),
    canActivate: [ProfileGuard]
  },
  {
    path: 'page2',
    loadChildren: () => import('./pages/another/another.module').then(m => m.AnotherModule),
  }
</code>```

and then in your guard decide that first route(page) can activate or you need to navigate to page2

profile.gurad.ts

```<code> if (!condition) {
   return this.router.parseUrl('/page2');
 }
 return true;
</code>```

Title: Conditional routing in Angular

Body:
I have a route:

    {
        path: 'business-rules',
        data: { routeName: _('Business rules') },
        component: BusinessRulesComponent,
    },

And I'm developing a new component that will replace the BusinessRulesComponent at some point. Users can opt in to the new NewBusinessRulesComponent by using a feature flag.

Now I'm wondering if it's possible to do conditional routing based on the selected feature flag.

I've added a guard CanAccessNewBusinessRules but as far as I know this can only stop a route from showing up:

    {
        path: 'business-rules',
        data: { routeName: _('Business rules') },
        component: BusinessRulesComponent,
        canActivate: [CanAccessNewBusinessRules]
    },

CanAccessNewBusinessRules:

        const new_business_rules_flagged = await this.companyFeatureFlagsService.getAllFeatureFlags(company.id)
            .then((flags) => flags.includes(possibleFlags.new_business_rules))

        if (new_business_rules_flagged) {
            // this.router.navigate(['new-business-rules'])
            return false;
        }

        return true;

Can I change the routing in the guard, or is it better to add another route that's only active when the flag is enabled?

Body:
No. you can't do it. A good way to handle situations like this is to return UrlTree from your guard so angular can route to another route.

app-routing.module.ts

  {
    path: 'page',
    loadChildren: () => import('./pages/home/home.module').then(m => m.HomeModule),
    canActivate: [ProfileGuard]
  },
  {
    path: 'page2',
    loadChildren: () => import('./pages/another/another.module').then(m => m.AnotherModule),
  }

and then in your guard decide that first route(page) can activate or you need to navigate to page2

profile.gurad.ts

 if (!condition) {
   return this.router.parseUrl('/page2');
 }
 return true;


问:
How do I provide an informal string representation of a python Class (not instance)
I understand how I can provide an informal representation of an instance of the object, but I am interested in providing an informal string representation of the Class name.

So specifically, I want to override what is returned when I print the Class (__main__.SomeClass).

```<code>>>> class SomeClass:
...   def __str__(self):
...     return 'I am a SomeClass instance.'
...
>>> SomeClass
<class __main__.SomeClass at 0x2ba2f0fd3b30>
>>> print SomeClass
__main__.SomeClass
>>>
>>> x = SomeClass()
>>> x
<__main__.SomeClass instance at 0x2ba2f0ff3f38>
>>> print x
I am a SomeClass instance.
</code>```

答:
Your problem is called meta class confusion. Of class A, if A.__str__(self) is a template for methods of instances of A, how can I provide a method __str__() for A itself? Meta classes to the rescue.

The following links explain this better than I could here.

http://gnosis.cx/publish/programming/metaclass_1.html

http://gnosis.cx/publish/programming/metaclass_2.html

A short example here:

```<code>class AMeta(type):
    def __str__(self):
        return "I am the truly remarkable class A"

class A(object):
    __metaclass__ = AMeta
    def __str__(self):
        return "I am an A instance"

print A
I am the truly remarkable class A
print A()
I am an A instance
</code>```

Btw you can do the same for __repr__.

ContentLicense: CC BY-SA 3.0

Body:
I understand how I can provide an informal representation of an instance of the object, but I am interested in providing an informal string representation of the Class name.

So specifically, I want to override what is returned when I print the Class (__main__.SomeClass).

>>> class SomeClass:
...   def __str__(self):
...     return 'I am a SomeClass instance.'
...
>>> SomeClass
<class __main__.SomeClass at 0x2ba2f0fd3b30>
>>> print SomeClass
__main__.SomeClass
>>>
>>> x = SomeClass()
>>> x
<__main__.SomeClass instance at 0x2ba2f0ff3f38>
>>> print x
I am a SomeClass instance.

Body:
Your problem is called meta class confusion. Of class A, if A.__str__(self) is a template for methods of instances of A, how can I provide a method __str__() for A itself? Meta classes to the rescue.

The following links explain this better than I could here.

http://gnosis.cx/publish/programming/metaclass_1.html

http://gnosis.cx/publish/programming/metaclass_2.html

A short example here:

class AMeta(type):
    def __str__(self):
        return "I am the truly remarkable class A"

class A(object):
    __metaclass__ = AMeta
    def __str__(self):
        return "I am an A instance"

print A
I am the truly remarkable class A
print A()
I am an A instance

Btw you can do the same for __repr__.


问:
Laravel dynamic email not sending by Mailable Class
In my case, In the Mailable Class I store the email in the variable hardcode form LIKE

$email = 'abc@example.com';
```
<p>then, its work fine. but when we pass the email dynamically from the Controller LIKE</p>
<pre class="lang-php prettyprint-override"><code>$this->email;
</code>```

this shows the error are given below :

Expected response code 250 but got code "550", with message "550 The from address does not match a verified Sender Identity. Mail cannot be sent until this error is resolved. Visit https://sendgrid.com/docs/for-developers/sending-email/sender-identity/ to see the Sender Identity requirements "

$subject = 'Account Created Successfully';

$name = 'Saakin Qatar';

return $this->view('emails.AgencyRegisterMail')

                   ->from($address, $name)

                   ->cc($address, $name)

                   ->bcc($address, $name)

                   ->replyTo($address, $name)

                   ->subject($subject)

                   ->with('inputs', $this->inputs);
```
<p>It works but when I pass the address from the controller and store it like below:</p>
<pre class="lang-php prettyprint-override"><code>$subject = 'Account Created Successfully';

$name = 'Saakin Qatar';

$name = 'Saakin Qatar';

return $this->view('emails.AgencyRegisterMail')

                    ->from($address, $name)

                    ->cc($address, $name)

                    ->bcc($address, $name)

                    ->replyTo($address, $name)

                    ->subject($subject)

                    ->with('inputs', $this->inputs);
</code>```

then it returns the error

答:
Twilio SendGrid developer evangelist here.

The error message here said:

Visit https://sendgrid.com/docs/for-developers/sending-email/sender-identity/ to see the Sender Identity requirements

On the page it recommends you visit it describes that to send emails you need to send them from either an email address that has been verified or an email address from an authenticated domain.

My guess is that you are building a contact form of sorts and trying to send the mail from an email address that a user enters into the form. If that is the case, you cannot use the user provided email address as the from parameter for sending the email, you have to use an email address that is verified or authenticated. But you can set the user's email address as the replyTo so that when you reply from your email client you write back to the user.

Body:
In my case, In the Mailable Class I store the email in the variable hardcode form LIKE

$email = 'abc@example.com';

then, its work fine. but when we pass the email dynamically from the Controller LIKE

$this->email;

this shows the error are given below :

Expected response code 250 but got code "550", with message "550 The from address does not match a verified Sender Identity. Mail cannot be sent until this error is resolved. Visit https://sendgrid.com/docs/for-developers/sending-email/sender-identity/ to see the Sender Identity requirements "

$subject = 'Account Created Successfully';

$name = 'Saakin Qatar';

return $this->view('emails.AgencyRegisterMail')

                   ->from($address, $name)

                   ->cc($address, $name)

                   ->bcc($address, $name)

                   ->replyTo($address, $name)

                   ->subject($subject)

                   ->with('inputs', $this->inputs);

It works but when I pass the address from the controller and store it like below:

$subject = 'Account Created Successfully';

$name = 'Saakin Qatar';

$name = 'Saakin Qatar';

return $this->view('emails.AgencyRegisterMail')

                    ->from($address, $name)

                    ->cc($address, $name)

                    ->bcc($address, $name)

                    ->replyTo($address, $name)

                    ->subject($subject)

                    ->with('inputs', $this->inputs);

then it returns the error


问:
How can I add a close button to my announcement bar on a Shopify website?
There is no option to add a close button when customising the theme, so I will have to add the code manually into the header.liquid file. But I am not sure where or what. Kindly assist.</p>

答:
you can add something like that on your header file:</p>
```<code><button type="button" class="text-link notification__close" id="NotificationPromoClose">
 {% render 'icon-close' %}
  <span class="icon__fallback-text">{{ 'cart.general.close_notification' | t }}</span></button>
</code>```

Body:
you can add something like that on your header file:

<button type="button" class="text-link notification__close" id="NotificationPromoClose">
 {% render 'icon-close' %}
  <span class="icon__fallback-text">{{ 'cart.general.close_notification' | t }}</span></button>


问:
How to correct code so that it runs or inserts formula in column to left of Range for cells that = "Metered"
I have a worksheet where column C has a formula that looks up value if column D = "Metered".
Users, who are mostly farm workers, have the ability to overwrite it (or possibly delete it using the Make Correction button).  Unless column D = "Metered", I don't care if column C is overwritten because data validation makes sure entry is OK.  Users are supposed to Tab past column C unless load is "Metered". As a failsafe, I duplicated the "Metered" lookup formula elsewhere and the results are in column S. I don't get any errors on code below, but it doesn't do anything -- previous versions would do things but not the right things. Clearly, I cannot solve this on my own and very much appreciate any help you can provide.  I want to run the failsafe once a day when the workbook is opened (running on laptops and speed is important).</p>
```<code>Private Sub Workbook_Open()

    Application.OnTime TimeValue("02:57:00"), "SaveBeforeDailyRestart"
    Application.MoveAfterReturnDirection = xlToRight
    Call MeteredLookupRefreshFormula

End Sub

Sub MeteredLookupRefreshFormula()

    Sheet1.Unprotect Password:="Cami8"

    Dim bng As Range
    Set bng = Range("D8:D10009")

    For Each cell In bng
        If Value = "Metered" Then
            bng.Offset(0, -1).Select
            Selection.Value = "S & ActiveCell.Row)"
      Else
    End If

    Next

    Sheet1.Protect Password:="Cami8"

End Sub
</code>```

答:
It appears as though the contents of your FOR loop is all screwed up.  This is untested but change this ...

```<code>For Each cell In bng
    If Value = "Metered" Then
        bng.Offset(0, -1).Select
        Selection.Value = "S & ActiveCell.Row)"
  Else
End If

Next
</code>```

... to this ...

```<code>For Each cell In bng
    If cell.Value = "Metered" Then
        cell.Offset(0, -1).Value = cell.Worksheet.Range("S" & cell.Row).Value
    End If
Next
</code>```

... and it should help.

Body:
I have a worksheet where column C has a formula that looks up value if column D = "Metered".
Users, who are mostly farm workers, have the ability to overwrite it (or possibly delete it using the Make Correction button).  Unless column D = "Metered", I don't care if column C is overwritten because data validation makes sure entry is OK.  Users are supposed to Tab past column C unless load is "Metered". As a failsafe, I duplicated the "Metered" lookup formula elsewhere and the results are in column S. I don't get any errors on code below, but it doesn't do anything -- previous versions would do things but not the right things. Clearly, I cannot solve this on my own and very much appreciate any help you can provide.  I want to run the failsafe once a day when the workbook is opened (running on laptops and speed is important).

Private Sub Workbook_Open()

    Application.OnTime TimeValue("02:57:00"), "SaveBeforeDailyRestart"
    Application.MoveAfterReturnDirection = xlToRight
    Call MeteredLookupRefreshFormula

End Sub

Sub MeteredLookupRefreshFormula()

    Sheet1.Unprotect Password:="Cami8"

    Dim bng As Range
    Set bng = Range("D8:D10009")

    For Each cell In bng
        If Value = "Metered" Then
            bng.Offset(0, -1).Select
            Selection.Value = "S & ActiveCell.Row)"
      Else
    End If

    Next

    Sheet1.Protect Password:="Cami8"

End Sub

Body:
It appears as though the contents of your FOR loop is all screwed up.  This is untested but change this ...

For Each cell In bng
    If Value = "Metered" Then
        bng.Offset(0, -1).Select
        Selection.Value = "S & ActiveCell.Row)"
  Else
End If

Next

... to this ...

For Each cell In bng
    If cell.Value = "Metered" Then
        cell.Offset(0, -1).Value = cell.Worksheet.Range("S" & cell.Row).Value
    End If
Next

... and it should help.


问:
merge multiple observables to an observable array
Hi I am trying to merge a number of observables to an observable array. Here an example that works in fsi. (sorry that it is lengthy)

```<code>#r "./bin/Debug/System.Reactive.dll"

open System
open System.Reactive.Linq

/// Subscribes to the Observable with all 3 callbacks.
let subscribeComplete next error completed (observable: IObservable<'T>) =
    observable.Subscribe(
        (fun x -> next x),
        (fun e -> error e),
        (fun () -> completed()))

/// Subscribes to the Observable with a next and an error-function.
let subscribeWithError next error observable =
    subscribeComplete next error (fun () -> ()) observable

/// Subscribes to the Observable with a next-function
let subscribe (next: 'T -> unit) (observable: IObservable<'T>) : IDisposable =
    subscribeWithError next ignore observable

/// Static method to generate observable from input functions
let ObsGenerate (initState: 'TS) (termCond: 'TS -> bool) (iterStep: 'TS -> 'TS)
        (resSelect: 'TS -> 'TR) (timeSelect : 'TS -> System.TimeSpan) =
            Observable.Generate(initState, termCond, iterStep, resSelect, timeSelect)

//maps the given observable with the given function
let obsMap (f: 'T -> 'U) (observable : IObservable<'T>) : IObservable<'U> =
    Observable.Select(observable, Func<_,_>(f))

/// Merges two observable sequences into one observable sequence whenever one of the observable sequences has a new value.
let combineLatest (obs1: IObservable<'T>) (obs2: IObservable<'U>) : IObservable<'T * 'U> =
    Observable.CombineLatest(
        obs1, obs2, Func<_,_,_>(fun a b -> a, b))

/// Merges three observable sequences into one observable sequence whenever one of the observable sequences has a new value.
let combineLatest3 (obs1: IObservable<'T>) (obs2: IObservable<'U>) (obs3: IObservable<'V>) : IObservable<'T * 'U * 'V> =
    let obs12 =obs1.CombineLatest(obs2, Func<_,_,_>(fun a b -> a, b))
    obs12.CombineLatest(obs3, Func<_,_,_>(fun (a,b) c -> a, b, c))

/// Merges four observable sequences into one observable sequence whenever one of the observable sequences has a new value.
let combineLatest4 (obs1: IObservable<'T>) (obs2: IObservable<'U>) (obs3: IObservable<'V>) (obs4: IObservable<'W>) : IObservable<'T * 'U * 'V * 'W> =
    let obsNew = combineLatest3 obs1 obs2 obs3
    obsNew.CombineLatest(obs4, Func<_,_,_>(fun (a,b,c) d -> a, b, c, d))

// second section generating arrays
let combineLatestArray (obs1: IObservable<'T>) (obs2: IObservable<'T>) =
    combineLatest obs1 obs2
    |> obsMap (fun (a, b) -> [a; b] |> List.toArray)

let combineLatest3Array (obs1: IObservable<'T>) (obs2: IObservable<'T>) (obs3: IObservable<'T>) =
    combineLatest3 obs1 obs2 obs3
    |> obsMap (fun (a, b, c) -> [a; b; c] |> List.toArray)

let combineLatest4Array (obs1: IObservable<'T>) (obs2: IObservable<'T>) (obs3: IObservable<'T>) (obs4: IObservable<'T>) =
    combineLatest4 obs1 obs2 obs3 obs4
    |> obsMap (fun (a, b, c, d) -> [a; b; c; d] |> List.toArray)

let combineLatestListToArray (list: IObservable<'T> List) =
    match list.Length with
    | 2 -> combineLatestArray list.[0] list.[1]
    | 3 -> combineLatest3Array list.[0] list.[1] list.[2]
    | 4 -> combineLatest4Array list.[0] list.[1] list.[2] list.[3]
    | _ -> failwith "combine latest on unsupported list size"

type FooType =
        {   NameVal :   string
            IdVal   :   int
            RetVal  :   float }

        member x.StringKey() =
            x.NameVal.ToString() + ";" + x.IdVal.ToString()

// example code starts here

let rnd = System.Random()

let fooListeners = Collections.Generic.Dictionary()

let AddAFoo (foo : FooType) =
    let fooId = foo.StringKey()

    if fooListeners.ContainsKey(fooId)
        then fooListeners.[fooId]
    else
        let myObs = ObsGenerate {NameVal = foo.NameVal; IdVal = foo.IdVal; RetVal = foo.RetVal} (fun x -> true) (fun x -> {NameVal = (x.NameVal); IdVal = (x.IdVal); RetVal = (x.RetVal + rnd.NextDouble() - 0.5)}) (fun x -> x) (fun x -> System.TimeSpan.FromMilliseconds(rnd.NextDouble() * 2000.0))
        fooListeners.Add(fooId,myObs)
        myObs

let fooInit =   [6..9]
                |> List.map (fun index -> {NameVal = (string index + "st"); IdVal = index; RetVal = (float index + 1.0)})
                |> List.map (fun foo -> AddAFoo foo)

let fooValuesArray =    fooInit
                        |> List.map(fun x -> (x |> obsMap (fun x -> x.RetVal)))
                        |> combineLatestListToArray

let mySub =
    fooValuesArray
    |> subscribe (fun fooVals -> printfn "fooArray: %A" fooVals)

//execute until here to start example

// execute this last line to unsubscribe
mySub.Dispose()
</code>```

I have two questions about this code:

Is there a smarter way of merging the observables to arrays? (it gets very lengthy as I need to merge larger arrays)

I want to throttle the updates. What I mean by that is that I want all updates that occur within (say) the same half a second window to be handled as one update on the array. Ideally, I want this window to open only when a first update comes in, i.e if no updates arrive in 2 seconds, then one update arrives, then we wait and include further updates for 0.5 seconds and then trigger the observable. I don't want it to publish periodically every 0.5 seconds although no observables are triggered. I hope this description is clear enough.

update: I have decided to accept one of the F# answers, but I haven't done the C# answers justice yet. I hope to be able to check them out properly soon.

答:
Seems that Observable.Merge() which has overloads for variable number of IObservables is closer to what you want.

Observable.Buffer() with the time overloads will do what you want here. In the "no events" situation, Buffer will still OnNext() an empty list, letting you react to that stiuation.

Body:
Hi I am trying to merge a number of observables to an observable array. Here an example that works in fsi. (sorry that it is lengthy)

#r "./bin/Debug/System.Reactive.dll"

open System
open System.Reactive.Linq

/// Subscribes to the Observable with all 3 callbacks.
let subscribeComplete next error completed (observable: IObservable<'T>) =
    observable.Subscribe(
        (fun x -> next x),
        (fun e -> error e),
        (fun () -> completed()))

/// Subscribes to the Observable with a next and an error-function.
let subscribeWithError next error observable =
    subscribeComplete next error (fun () -> ()) observable

/// Subscribes to the Observable with a next-function
let subscribe (next: 'T -> unit) (observable: IObservable<'T>) : IDisposable =
    subscribeWithError next ignore observable

/// Static method to generate observable from input functions
let ObsGenerate (initState: 'TS) (termCond: 'TS -> bool) (iterStep: 'TS -> 'TS)
        (resSelect: 'TS -> 'TR) (timeSelect : 'TS -> System.TimeSpan) =
            Observable.Generate(initState, termCond, iterStep, resSelect, timeSelect)

//maps the given observable with the given function
let obsMap (f: 'T -> 'U) (observable : IObservable<'T>) : IObservable<'U> =
    Observable.Select(observable, Func<_,_>(f))

/// Merges two observable sequences into one observable sequence whenever one of the observable sequences has a new value.
let combineLatest (obs1: IObservable<'T>) (obs2: IObservable<'U>) : IObservable<'T * 'U> =
    Observable.CombineLatest(
        obs1, obs2, Func<_,_,_>(fun a b -> a, b))

/// Merges three observable sequences into one observable sequence whenever one of the observable sequences has a new value.
let combineLatest3 (obs1: IObservable<'T>) (obs2: IObservable<'U>) (obs3: IObservable<'V>) : IObservable<'T * 'U * 'V> =
    let obs12 =obs1.CombineLatest(obs2, Func<_,_,_>(fun a b -> a, b))
    obs12.CombineLatest(obs3, Func<_,_,_>(fun (a,b) c -> a, b, c))

/// Merges four observable sequences into one observable sequence whenever one of the observable sequences has a new value.
let combineLatest4 (obs1: IObservable<'T>) (obs2: IObservable<'U>) (obs3: IObservable<'V>) (obs4: IObservable<'W>) : IObservable<'T * 'U * 'V * 'W> =
    let obsNew = combineLatest3 obs1 obs2 obs3
    obsNew.CombineLatest(obs4, Func<_,_,_>(fun (a,b,c) d -> a, b, c, d))

// second section generating arrays
let combineLatestArray (obs1: IObservable<'T>) (obs2: IObservable<'T>) =
    combineLatest obs1 obs2
    |> obsMap (fun (a, b) -> [a; b] |> List.toArray)

let combineLatest3Array (obs1: IObservable<'T>) (obs2: IObservable<'T>) (obs3: IObservable<'T>) =
    combineLatest3 obs1 obs2 obs3
    |> obsMap (fun (a, b, c) -> [a; b; c] |> List.toArray)

let combineLatest4Array (obs1: IObservable<'T>) (obs2: IObservable<'T>) (obs3: IObservable<'T>) (obs4: IObservable<'T>) =
    combineLatest4 obs1 obs2 obs3 obs4
    |> obsMap (fun (a, b, c, d) -> [a; b; c; d] |> List.toArray)

let combineLatestListToArray (list: IObservable<'T> List) =
    match list.Length with
    | 2 -> combineLatestArray list.[0] list.[1]
    | 3 -> combineLatest3Array list.[0] list.[1] list.[2]
    | 4 -> combineLatest4Array list.[0] list.[1] list.[2] list.[3]
    | _ -> failwith "combine latest on unsupported list size"

type FooType =
        {   NameVal :   string
            IdVal   :   int
            RetVal  :   float }

        member x.StringKey() =
            x.NameVal.ToString() + ";" + x.IdVal.ToString()

// example code starts here

let rnd = System.Random()

let fooListeners = Collections.Generic.Dictionary()

let AddAFoo (foo : FooType) =
    let fooId = foo.StringKey()

    if fooListeners.ContainsKey(fooId)
        then fooListeners.[fooId]
    else
        let myObs = ObsGenerate {NameVal = foo.NameVal; IdVal = foo.IdVal; RetVal = foo.RetVal} (fun x -> true) (fun x -> {NameVal = (x.NameVal); IdVal = (x.IdVal); RetVal = (x.RetVal + rnd.NextDouble() - 0.5)}) (fun x -> x) (fun x -> System.TimeSpan.FromMilliseconds(rnd.NextDouble() * 2000.0))
        fooListeners.Add(fooId,myObs)
        myObs

let fooInit =   [6..9]
                |> List.map (fun index -> {NameVal = (string index + "st"); IdVal = index; RetVal = (float index + 1.0)})
                |> List.map (fun foo -> AddAFoo foo)

let fooValuesArray =    fooInit
                        |> List.map(fun x -> (x |> obsMap (fun x -> x.RetVal)))
                        |> combineLatestListToArray

let mySub =
    fooValuesArray
    |> subscribe (fun fooVals -> printfn "fooArray: %A" fooVals)

//execute until here to start example

// execute this last line to unsubscribe
mySub.Dispose()

I have two questions about this code:

Is there a smarter way of merging the observables to arrays? (it gets very lengthy as I need to merge larger arrays)

I want to throttle the updates. What I mean by that is that I want all updates that occur within (say) the same half a second window to be handled as one update on the array. Ideally, I want this window to open only when a first update comes in, i.e if no updates arrive in 2 seconds, then one update arrives, then we wait and include further updates for 0.5 seconds and then trigger the observable. I don't want it to publish periodically every 0.5 seconds although no observables are triggered. I hope this description is clear enough.

update: I have decided to accept one of the F# answers, but I haven't done the C# answers justice yet. I hope to be able to check them out properly soon.


问:
Python variable manipulated indirectly without being mentioned in function
I'm a coding beginner that's putting a project together for a game. To update the game board, I use this function:

```<code>Board = [0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
def boardupdate(self, move):
    for index, val in enumerate(move):
        try:
            if val >= 15:
                val -= 3
                move[index] = val
        except TypeError:
            pass
    try: self[move[0]] = 1
    except Exception: None
    try: self[move[1]] = 0
    except Exception: None
    try: self[move[2]] = 0
    except Exception: None
    return self
</code>```

Where the first item of the list move represents the location where a piece is being placed in a turn, the second item representing where the piece is being taken from (in this game, you can either place a new piece on the board or move a piece), and the third item represents where a piece is being completely removed from the game. A certain turn can involve any of or none of these actions, hence the try and except blocks (which I learned just today, so if I am using them incorrectly, help would be much appreciated).

The code works as intended inside the function, but for some reason after this function is called, Board gets changed as if it was run through the function.

```<code>print(Board)
print(boardupdate(Board, [0, None]))
print(Board)
</code>```

returns:

```<code>[0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
</code>```

I've tried to solve this by copying Board to a temporary variable like so:

```<code>def boardupdate(self, move):
    tempboard = self
    for index, val in enumerate(move):
        try:
            if val >= 15:
                val -= 3
                move[index] = val
        except TypeError:
            pass
    try: tempboard[move[0]] = 1
    except Exception: None
    try: tempboard[move[1]] = 0
    except Exception: None
    try: tempboard[move[2]] = 0
    except Exception: None
    return tempboard
</code>```

Returns the same output as before. How can I change the output of this function without messing around with the initial conditions of Board? This is necessary in order for the rest of my code to run. Thanks!

答:
You are just pointing to Board, not actually copying it. In python, iterables are not copied by default for efficiency reasons.
So for example:

```<code>x=[1,2,3]
y=x
y[1]=5
print(x)
[1,5,3]
</code>```

To get over this, you should make a deep copy of Board either inside the function:

```<code>tempboard = self.copy()
</code>```

or when you are calling the function:

```<code>boardupdate(Board.copy())
</code>```

This is not the same for immutable objects, like integers:

```<code>x=5
y=x
y+=1
print(x)
5
</code>```

Body:
I'm a coding beginner that's putting a project together for a game. To update the game board, I use this function:

Board = [0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
def boardupdate(self, move):
    for index, val in enumerate(move):
        try:
            if val >= 15:
                val -= 3
                move[index] = val
        except TypeError:
            pass
    try: self[move[0]] = 1
    except Exception: None
    try: self[move[1]] = 0
    except Exception: None
    try: self[move[2]] = 0
    except Exception: None
    return self

Where the first item of the list move represents the location where a piece is being placed in a turn, the second item representing where the piece is being taken from (in this game, you can either place a new piece on the board or move a piece), and the third item represents where a piece is being completely removed from the game. A certain turn can involve any of or none of these actions, hence the try and except blocks (which I learned just today, so if I am using them incorrectly, help would be much appreciated).

The code works as intended inside the function, but for some reason after this function is called, Board gets changed as if it was run through the function.

print(Board)
print(boardupdate(Board, [0, None]))
print(Board)

returns:

[0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

I've tried to solve this by copying Board to a temporary variable like so:

def boardupdate(self, move):
    tempboard = self
    for index, val in enumerate(move):
        try:
            if val >= 15:
                val -= 3
                move[index] = val
        except TypeError:
            pass
    try: tempboard[move[0]] = 1
    except Exception: None
    try: tempboard[move[1]] = 0
    except Exception: None
    try: tempboard[move[2]] = 0
    except Exception: None
    return tempboard

Returns the same output as before. How can I change the output of this function without messing around with the initial conditions of Board? This is necessary in order for the rest of my code to run. Thanks!

Body:
You are just pointing to Board, not actually copying it. In python, iterables are not copied by default for efficiency reasons.
So for example:

x=[1,2,3]
y=x
y[1]=5
print(x)
[1,5,3]

To get over this, you should make a deep copy of Board either inside the function:

tempboard = self.copy()

or when you are calling the function:

boardupdate(Board.copy())

This is not the same for immutable objects, like integers:

x=5
y=x
y+=1
print(x)
5


问:
Lumen Passport return 500 except successfully log in request
I've created Lumen Passport in my local and free Heroku and successfully created it. Now I’m creating my production lumen in digital ocean VPS. All of my applications work fine and give good bad responses format when it should be failed responses, except my login. In my login, it passes a good response when correct emails and passwords but returns 500 in other cases.

This is my code in my LoginService.php

```<code>public function generate_token($email, $password){
    // $token = Http::post(config('service.passport.login_endpoint'), [
    //     'grant_type' => 'password',
    //     'client_id' => config('service.passport.client_id'),
    //     'client_secret' => config('service.passport.client_secret'),
    //     'username' => $email,
    //     'password' => $password,
    // ]);

    // return $token->json();
    $http = new Client;
    try {
        $response = $http->post(config('service.passport.login_endpoint'), [
            'form_params' => [
                'grant_type' => 'password',
                'client_id' => config('service.passport.client_id'),
                'client_secret' => config('service.passport.client_secret'),
                'username' => $email,
                'password' => $password,
            ]
        ]);
        return [true, $response->getBody()];
    } catch (ClientException $e) {
        $response = $e->getResponse();
        $responseBodyAsString = $response->getBody()->getContents();
        return [false, Psr7\str($e->getResponse())];
        // return $responseBodyAsString;
    }
}

public function login($email, $password){
    $login = $this->generate_token($email, $password);

    // if(isset($login['error'])){
    //     $response = [
    //         "success" => false,
    //         "message" => (object)[
    //             "errorInfo" => [
    //                 "status" => 401,
    //                 "reason" => $login['error'],
    //                 "server_code" => 401,
    //                 "status_detail" => $login['error_description']
    //             ]
    //         ],
    //         "status" => 401
    //     ];
    // } else {
    //     $response = [
    //         "success" => true,
    //         "data" => [
    //             "message" => "success generate token",
    //             "token" => $login['access_token']
    //         ],
    //         "status" => 200
    //     ];
    // }
    if($login[0]){
        $response = [
            "success" => true,
            "data" => json_decode($login[1]),
            "status" => 200
        ];
    } else {
        $response = [
            "success" => true,
            "data" => $login[1],
            "status" => 200
        ];
    }

    return $response;
}
</code>```

This is my error log from my server

```
2022/02/08 09:11:58 [error] 61359#61359: *4187 FastCGI sent in stderr: "PHP message: PHP Fatal error:  Uncaught UnexpectedValueException: The stream or file "/var/www/html/ims/storage/logs/lumen-2022-02-08.log" could not be opened in append mode: failed to open stream: Permission denied in /var/www/html/ims/vendor/monolog/monolog/src/Monolog/Handler/StreamHandler.php:111
Stack trace:
#0 /var/www/html/ims/vendor/monolog/monolog/src/Monolog/Handler/RotatingFileHandler.php(121): Monolog\Handler\StreamHandler->write()
#1 /var/www/html/ims/vendor/monolog/monolog/src/Monolog/Handler/AbstractProcessingHandler.php(42): Monolog\Handler\RotatingFileHandler->write()
#2 /var/www/html/ims/vendor/monolog/monolog/src/Monolog/Logger.php(317): Monolog\Handler\AbstractProcessingHandler->handle()
#3 /var/www/html/ims/vendor/monolog/monolog/src/Monolog/Logger.php(539): Monolog\Logger->addRecord()
#4 /var/www/html/ims/vendor/illuminate/log/Logger.php(174): Monolog\Logger->error()
#5 /var/www/html/ims/vendor/illuminate/log/Logger.php(87): Illuminate\Log\Logger->writeLog()
#6 /var/www/html/...PHP message: PHP Fatal error:  Uncaught UnexpectedValueException: The stream or file "/var/www/html/ims/storage/logs/lumen-2022-02-08.log" could not be opened in append mode: failed to open stream: Permission denied in /var/www/html/ims/vendor/monolog/monolog/src/Monolog/Handler/StreamHandler.php:111
Stack trace:
#0 /var/www/html/ims/vendor/monolog/monolog/src/Monolog/Handler/RotatingFileHandler.php(121): Monolog\Handler\StreamHandler->write()
#1 /var/www/html/ims/vendor/monolog/monolog/src/Monolog/Handler/AbstractProcessingHandler.php(42): Monolog\Handler\RotatingFileHandler->write()
#2 /var/www/html/ims/vendor/monolog/monolog/src/Monolog/Logger.php(317): Monolog\Handler\AbstractProcessingHandler->handle()
#3 /var/www/html/ims/vendor/monolog/monolog/src/Monolog/Logger.php(539): Monolog\Logger->addRecord()
#4 /var/www/html/ims/vendor/illuminate/log/Logger.php(174): Monolog\Logger->error()
#5 /var/www/html/ims/vendor/illuminate/log/Logger.php(87):
```

This is my permission and user list in my storage and logs

```
root@mighty-app-1:/var/www/html/ims# ll
total 444
drwxr-xr-x 14 root www-data   4096 Feb  7 23:30 ./
drwxr-xr-x  4 root root       4096 Feb  3 17:17 ../
-rw-r--r--  1 root root        220 Feb  7 07:14 .editorconfig
-rwxr-xr-x  1 root root        586 Feb  7 23:30 .env*
-rw-r--r--  1 root root        293 Feb  7 07:14 .env.example
drwxr-xr-x  8 root www-data   4096 Feb  8 07:12 .git/
-rw-r--r--  1 root root         87 Feb  7 07:14 .gitignore
-rw-r--r--  1 root root         71 Feb  7 07:14 .styleci.yml
drwxr-xr-x  2 root www-data   4096 Feb  7 07:14 .vscode/
-rw-r--r--  1 root root        121 Feb  7 07:14 Procfile
-rw-r--r--  1 root root       1585 Feb  7 07:14 README.md
drwxr-xr-x 13 root www-data   4096 Feb  7 07:14 app/
-rwxr-xr-x  1 root root       1094 Feb  7 07:14 artisan*
drwxr-xrwx  2 root www-data   4096 Feb  7 07:14 bootstrap/
-rw-r--r--  1 root root       1463 Feb  7 07:14 composer.json
-rw-r--r--  1 root root     355645 Feb  7 07:14 composer.lock
drwxr-xr-x  2 root www-data   4096 Feb  7 07:14 config/
drwxr-xr-x  5 root www-data   4096 Feb  3 17:01 database/
-rw-r--r--  1 root root        756 Feb  7 07:14 phpunit.xml
drwxr-xr-x  3 root www-data   4096 Feb  8 07:12 public/
drwxr-xr-x  3 root www-data   4096 Feb  3 17:01 resources/
drwxr-xr-x  2 root www-data   4096 Feb  7 07:14 routes/
drwxr-xrwx  5 root www-data   4096 Feb  7 07:14 storage/
drwxr-xr-x  2 root www-data   4096 Feb  7 07:14 tests/
drwxr-xr-x 60 root root       4096 Feb  4 03:49 vendor/
root@mighty-app-1:/var/www/html/ims# cd storage
root@mighty-app-1:/var/www/html/ims/storage# ll
total 36
drwxr-xrwx  5 root www-data 4096 Feb  7 07:14 ./
drwxr-xr-x 14 root www-data 4096 Feb  7 23:30 ../
-rw-r--r--  1 root root     6148 Feb  7 07:14 .DS_Store
drwxr-xrwx  2 root www-data 4096 Feb  7 07:14 app/
drwxr-xrwx  4 root www-data 4096 Feb  7 07:14 framework/
drwxr-xrwx  2 root www-data 4096 Feb  7 10:24 logs/
-rw-r--r--  1 root root     3292 Feb  7 23:30 oauth-private.key
-rw-r--r--  1 root root      812 Feb  7 23:30 oauth-public.key
root@mighty-app-1:/var/www/html/ims/storage# cd logs/
root@mighty-app-1:/var/www/html/ims/storage/logs# ll
total 108
drwxr-xrwx 2 root www-data  4096 Feb  7 10:24 ./
drwxr-xrwx 5 root www-data  4096 Feb  7 07:14 ../
-rw-r--r-- 1 root root        14 Feb  7 07:14 .gitignore
-rwxr-xrwx 1 root root     93743 Feb  4 11:13 lumen-2022-02-04.log*
root@mighty-app-1:/var/www/html/ims/storage/logs#

```

I've tried some ways to check whether the responses couldn't be read or something, but it seems that there's something missing that I couldn't get.

I didn’t find other similar cases with my case other than this Lumen Passport return 500 error instead 401 error but this also couldn’t solve my problem.

Can anyone give me some tips for me? Thanks in advance

答:
After some time searching for answer, the problem was because my storage folder had root user permission. And it solved by giving the user and group permission to www-data with command like this

```<code>sudo chown -R www-data:www-data /var/www/<project_name>/storage
</code>```

Special thanks to @Peppermintology for giving me many hints

Body:
I've created Lumen Passport in my local and free Heroku and successfully created it. Now I’m creating my production lumen in digital ocean VPS. All of my applications work fine and give good bad responses format when it should be failed responses, except my login. In my login, it passes a good response when correct emails and passwords but returns 500 in other cases.

This is my code in my LoginService.php

public function generate_token($email, $password){
    // $token = Http::post(config('service.passport.login_endpoint'), [
    //     'grant_type' => 'password',
    //     'client_id' => config('service.passport.client_id'),
    //     'client_secret' => config('service.passport.client_secret'),
    //     'username' => $email,
    //     'password' => $password,
    // ]);

    // return $token->json();
    $http = new Client;
    try {
        $response = $http->post(config('service.passport.login_endpoint'), [
            'form_params' => [
                'grant_type' => 'password',
                'client_id' => config('service.passport.client_id'),
                'client_secret' => config('service.passport.client_secret'),
                'username' => $email,
                'password' => $password,
            ]
        ]);
        return [true, $response->getBody()];
    } catch (ClientException $e) {
        $response = $e->getResponse();
        $responseBodyAsString = $response->getBody()->getContents();
        return [false, Psr7\str($e->getResponse())];
        // return $responseBodyAsString;
    }
}

public function login($email, $password){
    $login = $this->generate_token($email, $password);

    // if(isset($login['error'])){
    //     $response = [
    //         "success" => false,
    //         "message" => (object)[
    //             "errorInfo" => [
    //                 "status" => 401,
    //                 "reason" => $login['error'],
    //                 "server_code" => 401,
    //                 "status_detail" => $login['error_description']
    //             ]
    //         ],
    //         "status" => 401
    //     ];
    // } else {
    //     $response = [
    //         "success" => true,
    //         "data" => [
    //             "message" => "success generate token",
    //             "token" => $login['access_token']
    //         ],
    //         "status" => 200
    //     ];
    // }
    if($login[0]){
        $response = [
            "success" => true,
            "data" => json_decode($login[1]),
            "status" => 200
        ];
    } else {
        $response = [
            "success" => true,
            "data" => $login[1],
            "status" => 200
        ];
    }

    return $response;
}

This is my error log from my server

2022/02/08 09:11:58 [error] 61359#61359: *4187 FastCGI sent in stderr: "PHP message: PHP Fatal error:  Uncaught UnexpectedValueException: The stream or file "/var/www/html/ims/storage/logs/lumen-2022-02-08.log" could not be opened in append mode: failed to open stream: Permission denied in /var/www/html/ims/vendor/monolog/monolog/src/Monolog/Handler/StreamHandler.php:111
Stack trace:
#0 /var/www/html/ims/vendor/monolog/monolog/src/Monolog/Handler/RotatingFileHandler.php(121): Monolog\Handler\StreamHandler->write()
#1 /var/www/html/ims/vendor/monolog/monolog/src/Monolog/Handler/AbstractProcessingHandler.php(42): Monolog\Handler\RotatingFileHandler->write()
#2 /var/www/html/ims/vendor/monolog/monolog/src/Monolog/Logger.php(317): Monolog\Handler\AbstractProcessingHandler->handle()
#3 /var/www/html/ims/vendor/monolog/monolog/src/Monolog/Logger.php(539): Monolog\Logger->addRecord()
#4 /var/www/html/ims/vendor/illuminate/log/Logger.php(174): Monolog\Logger->error()
#5 /var/www/html/ims/vendor/illuminate/log/Logger.php(87): Illuminate\Log\Logger->writeLog()
#6 /var/www/html/...PHP message: PHP Fatal error:  Uncaught UnexpectedValueException: The stream or file "/var/www/html/ims/storage/logs/lumen-2022-02-08.log" could not be opened in append mode: failed to open stream: Permission denied in /var/www/html/ims/vendor/monolog/monolog/src/Monolog/Handler/StreamHandler.php:111
Stack trace:
#0 /var/www/html/ims/vendor/monolog/monolog/src/Monolog/Handler/RotatingFileHandler.php(121): Monolog\Handler\StreamHandler->write()
#1 /var/www/html/ims/vendor/monolog/monolog/src/Monolog/Handler/AbstractProcessingHandler.php(42): Monolog\Handler\RotatingFileHandler->write()
#2 /var/www/html/ims/vendor/monolog/monolog/src/Monolog/Logger.php(317): Monolog\Handler\AbstractProcessingHandler->handle()
#3 /var/www/html/ims/vendor/monolog/monolog/src/Monolog/Logger.php(539): Monolog\Logger->addRecord()
#4 /var/www/html/ims/vendor/illuminate/log/Logger.php(174): Monolog\Logger->error()
#5 /var/www/html/ims/vendor/illuminate/log/Logger.php(87):

This is my permission and user list in my storage and logs

root@mighty-app-1:/var/www/html/ims# ll
total 444
drwxr-xr-x 14 root www-data   4096 Feb  7 23:30 ./
drwxr-xr-x  4 root root       4096 Feb  3 17:17 ../
-rw-r--r--  1 root root        220 Feb  7 07:14 .editorconfig
-rwxr-xr-x  1 root root        586 Feb  7 23:30 .env*
-rw-r--r--  1 root root        293 Feb  7 07:14 .env.example
drwxr-xr-x  8 root www-data   4096 Feb  8 07:12 .git/
-rw-r--r--  1 root root         87 Feb  7 07:14 .gitignore
-rw-r--r--  1 root root         71 Feb  7 07:14 .styleci.yml
drwxr-xr-x  2 root www-data   4096 Feb  7 07:14 .vscode/
-rw-r--r--  1 root root        121 Feb  7 07:14 Procfile
-rw-r--r--  1 root root       1585 Feb  7 07:14 README.md
drwxr-xr-x 13 root www-data   4096 Feb  7 07:14 app/
-rwxr-xr-x  1 root root       1094 Feb  7 07:14 artisan*
drwxr-xrwx  2 root www-data   4096 Feb  7 07:14 bootstrap/
-rw-r--r--  1 root root       1463 Feb  7 07:14 composer.json
-rw-r--r--  1 root root     355645 Feb  7 07:14 composer.lock
drwxr-xr-x  2 root www-data   4096 Feb  7 07:14 config/
drwxr-xr-x  5 root www-data   4096 Feb  3 17:01 database/
-rw-r--r--  1 root root        756 Feb  7 07:14 phpunit.xml
drwxr-xr-x  3 root www-data   4096 Feb  8 07:12 public/
drwxr-xr-x  3 root www-data   4096 Feb  3 17:01 resources/
drwxr-xr-x  2 root www-data   4096 Feb  7 07:14 routes/
drwxr-xrwx  5 root www-data   4096 Feb  7 07:14 storage/
drwxr-xr-x  2 root www-data   4096 Feb  7 07:14 tests/
drwxr-xr-x 60 root root       4096 Feb  4 03:49 vendor/
root@mighty-app-1:/var/www/html/ims# cd storage
root@mighty-app-1:/var/www/html/ims/storage# ll
total 36
drwxr-xrwx  5 root www-data 4096 Feb  7 07:14 ./
drwxr-xr-x 14 root www-data 4096 Feb  7 23:30 ../
-rw-r--r--  1 root root     6148 Feb  7 07:14 .DS_Store
drwxr-xrwx  2 root www-data 4096 Feb  7 07:14 app/
drwxr-xrwx  4 root www-data 4096 Feb  7 07:14 framework/
drwxr-xrwx  2 root www-data 4096 Feb  7 10:24 logs/
-rw-r--r--  1 root root     3292 Feb  7 23:30 oauth-private.key
-rw-r--r--  1 root root      812 Feb  7 23:30 oauth-public.key
root@mighty-app-1:/var/www/html/ims/storage# cd logs/
root@mighty-app-1:/var/www/html/ims/storage/logs# ll
total 108
drwxr-xrwx 2 root www-data  4096 Feb  7 10:24 ./
drwxr-xrwx 5 root www-data  4096 Feb  7 07:14 ../
-rw-r--r-- 1 root root        14 Feb  7 07:14 .gitignore
-rwxr-xrwx 1 root root     93743 Feb  4 11:13 lumen-2022-02-04.log*
root@mighty-app-1:/var/www/html/ims/storage/logs#

I've tried some ways to check whether the responses couldn't be read or something, but it seems that there's something missing that I couldn't get.

I didn’t find other similar cases with my case other than this Lumen Passport return 500 error instead 401 error but this also couldn’t solve my problem.

Can anyone give me some tips for me? Thanks in advance

Body:
After some time searching for answer, the problem was because my storage folder had root user permission. And it solved by giving the user and group permission to www-data with command like this

sudo chown -R www-data:www-data /var/www/<project_name>/storage

Special thanks to @Peppermintology for giving me many hints