问:
Exception occurred while initializing the installation: System.BadImageFormatException: Could not load file or assembly
I have Worker Services as Windows services which I am trying to install on a machine however it throws the below error when I try Installing it

```<code>Microsoft (R) .NET Framework Installation utility Version 4.8.3752.0
Copyright (C) Microsoft Corporation.  All rights reserved.

Exception occurred while initializing the installation:
System.BadImageFormatException: Could not load file or assembly 'file:///C:\Users\JNyingi\source\repos\SeSPWS\SeSPWS\bin\Release\netcoreapp3.0\SeSPWS.exe' or one of its dependencies. The module was expected to contain an assembly manifest..
</code>```

Below is the .csproj file content of the packages in use

<Project Sdk="Microsoft.NET.Sdk.Worker">
  <PropertyGroup>
    <TargetFramework>netcoreapp3.0</TargetFramework>
    <UserSecretsId>dotnet-SeSPWS-00EEA7BA-8CD9-4E72-B073-FB0FB7B9192A</UserSecretsId>
    <ApplicationIcon />
    <OutputType>WinExe</OutputType>
    <StartupObject />
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="AutoMapper" Version="9.0.0" />
    <PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="7.0.0" />
    <PackageReference Include="Microsoft.AspNetCore" Version="2.2.0" />
    <PackageReference Include="Microsoft.AspNetCore.Hosting" Version="2.2.7" />
    <PackageReference Include="Microsoft.AspNetCore.Hosting.WindowsServices" Version="3.0.0" />
    <PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="3.0.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="3.0.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.0.0" />
    <PackageReference Include="Microsoft.Extensions.Hosting" Version="3.0.1" />
    <PackageReference Include="System.ServiceModel.Duplex" Version="4.4.*" />
    <PackageReference Include="System.ServiceModel.Http" Version="4.4.*" />
    <PackageReference Include="System.ServiceModel.NetTcp" Version="4.4.*" />
    <PackageReference Include="System.ServiceModel.Security" Version="4.4.*" />
  </ItemGroup>

  <ItemGroup>
    <WCFMetadata Include="Connected Services" />
  </ItemGroup>
</Project>

```

<p>While looking at assembly binding log viewer I this error log.</p>

```** Assembly Binder Log Entry  (2/14/2020 @ 1:41:17 PM) ***

The operation failed.
Bind result: hr = 0x80131018. No description available.

Assembly manager loaded from:  C:\Windows\Microsoft.NET\Framework64\v4.0.30319\clr.dll
Running under executable  C:\Windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe
--- A detailed error log follows.

=== Pre-bind state information ===
LOG: Where-ref bind. Location = C:\Users\JNyingi\source\repos\SeSPWS\SeSPWS\bin\Release\netcoreapp3.0\SeSPWS.exe
LOG: Appbase = file:///C:/Windows/Microsoft.NET/Framework64/v4.0.30319/
LOG: Initial PrivatePath = NULL
LOG: Dynamic Base = NULL
LOG: Cache Base = NULL
LOG: AppName = InstallUtil.exe
Calling assembly : (Unknown).
===
LOG: This bind starts in LoadFrom load context.
WRN: Native image will not be probed in LoadFrom context. Native image will only be probed in default load context, like with Assembly.Load().
LOG: Using application configuration file: C:\Windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe.Config
LOG: Using host configuration file:
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework64\v4.0.30319\config\machine.config.
LOG: Attempting download of new URL file:///C:/Users/JNyingi/source/repos/SeSPWS/SeSPWS/bin/Release/netcoreapp3.0/SeSPWS.exe.
LOG: Assembly download was successful. Attempting setup of file: C:\Users\JNyingi\source\repos\SeSPWS\SeSPWS\bin\Release\netcoreapp3.0\SeSPWS.exe
LOG: Entering run-from-source setup phase.
ERR: Error extracting manifest import from file (hr = 0x80131018).
ERR: Run-from-source setup phase failed with hr = 0x80131018.
ERR: Failed to complete setup of assembly (hr = 0x80131018). Probing terminated.

```

<p>I have installed the following runtime; .NET Core 3.0, ASP.NET Core 3.0 and Windows desktop 3.0. However, the service still fails to install even after upgrading to .NET Core 3.1 runtime.</p>

<p>Below is my build profile</p>

<p><img src="https://i.stack.imgur.com/XLSiI.png" alt="Build Setup"></p>

<p>I have built a similar worker service before which installed without any hustle; kindly I wish to resolve this error and deploy the service to the machine.</p>

<p><strong>EDIT</strong>
Below is My Program Class</p>

```public class Program
    {
        public static void Main(string[] args)
        {
            var isService = !(Debugger.IsAttached || args.Contains("--console"));
            if (isService)
            {
                CreateWebHostBuilder(args).Build().RunAsService();
            }
            else
            {
                CreateWebHostBuilder(args).Build().Run();
            }
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseContentRoot(Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName))
                .UseStartup<Startup>()
                .UseKestrel((context, serverOptions) =>
                {
                    serverOptions.ListenAnyIP(1042);
                    serverOptions.Limits.KeepAliveTimeout = TimeSpan.FromMinutes(1.5);
                });
    }
```

EDIT2

These are the NuGet packages in use for the service

答:
So after much frustrating dead ends, our Lady showed me how to resolve the error. It's really simple, I made three main changes to my application.

.csproj was updated to;

```<code><Project Sdk="Microsoft.NET.Sdk.Worker">

  <PropertyGroup>
    <TargetFramework>netcoreapp3.0</TargetFramework>
    <IsTransformWebConfigDisabled>true</IsTransformWebConfigDisabled>
    <UserSecretsId>dotnet-SeSPWS-00EEA7BA-8CD9-4E72-B073-FB0FB7B9192A</UserSecretsId>
    <ApplicationIcon />
    <OutputType>WinExe</OutputType>
    <StartupObject />
    <RuntimeIdentifiers>win-x64</RuntimeIdentifiers>
    <Platforms>AnyCPU;x64</Platforms>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="AutoMapper" Version="9.0.0" />
    <PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="7.0.0" />
    <PackageReference Include="Microsoft.AspNet.WebApi.Core" Version="5.2.7" />
    <PackageReference Include="Microsoft.AspNetCore" Version="2.2.0" />
    <PackageReference Include="Microsoft.AspNetCore.Hosting" Version="2.2.7" />
    <PackageReference Include="Microsoft.AspNetCore.Hosting.WindowsServices" Version="3.0.0" />
    <PackageReference Include="Microsoft.AspNetCore.Mvc.Core" Version="2.2.5" />
    <PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="3.0.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="3.0.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.0.0" />
    <PackageReference Include="Microsoft.Extensions.Hosting" Version="3.0.1" />
    <PackageReference Include="Microsoft.Extensions.Hosting.WindowsServices" Version="3.0.0" />
    <PackageReference Include="System.ServiceModel.Duplex" Version="4.4.*" />
    <PackageReference Include="System.ServiceModel.Http" Version="4.4.*" />
    <PackageReference Include="System.ServiceModel.NetTcp" Version="4.4.*" />
    <PackageReference Include="System.ServiceModel.Security" Version="4.4.*" />
  </ItemGroup>

  <ItemGroup>
    <WCFMetadata Include="Connected Services" />
  </ItemGroup>
</Project>
</code>```

I also changed my program.cs and changed from IWebHostBuilder to IHostBuilder as shown below;

```<code>public class Program
    {
        public static void Main(string[] args)
        {
            var isService = !(Debugger.IsAttached || args.Contains("--console"));
            if (isService)
            {
                CreateHostBuilder(args).Build().Run();//.RunAsService();
            }
            else
            {
                CreateHostBuilder(args).Build().Run();
            }
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .UseContentRoot(Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName))
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                    webBuilder.UseKestrel((context, serverOptions) =>
                    {
                        serverOptions.ListenAnyIP(1042);
                        serverOptions.Limits.KeepAliveTimeout = TimeSpan.FromMinutes(1.5);
                    });
                }).UseWindowsService();
    }
</code>```

Just to make sure that the service builds with a specific version of .Net Core SDK I added the following global.json

```<code>{
  "sdk": {
    "version": "3.0.100",
    "rollForward": "disable"
  }
}
</code>```

I then  built and published.

NOTE : I have also noted InstallUtil does not work with ASP.NET Worker Service. So, you have to change and use SC to install your service.Like so;

SC {SERVICENAME} binpath="{path-to-exe}"

Body:
I have Worker Services as Windows services which I am trying to install on a machine however it throws the below error when I try Installing it

Microsoft (R) .NET Framework Installation utility Version 4.8.3752.0
Copyright (C) Microsoft Corporation.  All rights reserved.

Exception occurred while initializing the installation:
System.BadImageFormatException: Could not load file or assembly 'file:///C:\Users\JNyingi\source\repos\SeSPWS\SeSPWS\bin\Release\netcoreapp3.0\SeSPWS.exe' or one of its dependencies. The module was expected to contain an assembly manifest..

Below is the .csproj file content of the packages in use

<Project Sdk="Microsoft.NET.Sdk.Worker">
  <PropertyGroup>
    <TargetFramework>netcoreapp3.0</TargetFramework>
    <UserSecretsId>dotnet-SeSPWS-00EEA7BA-8CD9-4E72-B073-FB0FB7B9192A</UserSecretsId>
    <ApplicationIcon />
    <OutputType>WinExe</OutputType>
    <StartupObject />
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="AutoMapper" Version="9.0.0" />
    <PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="7.0.0" />
    <PackageReference Include="Microsoft.AspNetCore" Version="2.2.0" />
    <PackageReference Include="Microsoft.AspNetCore.Hosting" Version="2.2.7" />
    <PackageReference Include="Microsoft.AspNetCore.Hosting.WindowsServices" Version="3.0.0" />
    <PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="3.0.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="3.0.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.0.0" />
    <PackageReference Include="Microsoft.Extensions.Hosting" Version="3.0.1" />
    <PackageReference Include="System.ServiceModel.Duplex" Version="4.4.*" />
    <PackageReference Include="System.ServiceModel.Http" Version="4.4.*" />
    <PackageReference Include="System.ServiceModel.NetTcp" Version="4.4.*" />
    <PackageReference Include="System.ServiceModel.Security" Version="4.4.*" />
  </ItemGroup>

  <ItemGroup>
    <WCFMetadata Include="Connected Services" />
  </ItemGroup>
</Project>

While looking at assembly binding log viewer I this error log.

** Assembly Binder Log Entry  (2/14/2020 @ 1:41:17 PM) ***

The operation failed.
Bind result: hr = 0x80131018. No description available.

Assembly manager loaded from:  C:\Windows\Microsoft.NET\Framework64\v4.0.30319\clr.dll
Running under executable  C:\Windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe
--- A detailed error log follows.

=== Pre-bind state information ===
LOG: Where-ref bind. Location = C:\Users\JNyingi\source\repos\SeSPWS\SeSPWS\bin\Release\netcoreapp3.0\SeSPWS.exe
LOG: Appbase = file:///C:/Windows/Microsoft.NET/Framework64/v4.0.30319/
LOG: Initial PrivatePath = NULL
LOG: Dynamic Base = NULL
LOG: Cache Base = NULL
LOG: AppName = InstallUtil.exe
Calling assembly : (Unknown).
===
LOG: This bind starts in LoadFrom load context.
WRN: Native image will not be probed in LoadFrom context. Native image will only be probed in default load context, like with Assembly.Load().
LOG: Using application configuration file: C:\Windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe.Config
LOG: Using host configuration file:
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework64\v4.0.30319\config\machine.config.
LOG: Attempting download of new URL file:///C:/Users/JNyingi/source/repos/SeSPWS/SeSPWS/bin/Release/netcoreapp3.0/SeSPWS.exe.
LOG: Assembly download was successful. Attempting setup of file: C:\Users\JNyingi\source\repos\SeSPWS\SeSPWS\bin\Release\netcoreapp3.0\SeSPWS.exe
LOG: Entering run-from-source setup phase.
ERR: Error extracting manifest import from file (hr = 0x80131018).
ERR: Run-from-source setup phase failed with hr = 0x80131018.
ERR: Failed to complete setup of assembly (hr = 0x80131018). Probing terminated.

I have installed the following runtime; .NET Core 3.0, ASP.NET Core 3.0 and Windows desktop 3.0. However, the service still fails to install even after upgrading to .NET Core 3.1 runtime.

Below is my build profile

I have built a similar worker service before which installed without any hustle; kindly I wish to resolve this error and deploy the service to the machine.

EDIT
Below is My Program Class

public class Program
    {
        public static void Main(string[] args)
        {
            var isService = !(Debugger.IsAttached || args.Contains("--console"));
            if (isService)
            {
                CreateWebHostBuilder(args).Build().RunAsService();
            }
            else
            {
                CreateWebHostBuilder(args).Build().Run();
            }
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseContentRoot(Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName))
                .UseStartup<Startup>()
                .UseKestrel((context, serverOptions) =>
                {
                    serverOptions.ListenAnyIP(1042);
                    serverOptions.Limits.KeepAliveTimeout = TimeSpan.FromMinutes(1.5);
                });
    }

EDIT2

These are the NuGet packages in use for the service

Body:
So after much frustrating dead ends, our Lady showed me how to resolve the error. It's really simple, I made three main changes to my application.

.csproj was updated to;

<Project Sdk="Microsoft.NET.Sdk.Worker">

  <PropertyGroup>
    <TargetFramework>netcoreapp3.0</TargetFramework>
    <IsTransformWebConfigDisabled>true</IsTransformWebConfigDisabled>
    <UserSecretsId>dotnet-SeSPWS-00EEA7BA-8CD9-4E72-B073-FB0FB7B9192A</UserSecretsId>
    <ApplicationIcon />
    <OutputType>WinExe</OutputType>
    <StartupObject />
    <RuntimeIdentifiers>win-x64</RuntimeIdentifiers>
    <Platforms>AnyCPU;x64</Platforms>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="AutoMapper" Version="9.0.0" />
    <PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="7.0.0" />
    <PackageReference Include="Microsoft.AspNet.WebApi.Core" Version="5.2.7" />
    <PackageReference Include="Microsoft.AspNetCore" Version="2.2.0" />
    <PackageReference Include="Microsoft.AspNetCore.Hosting" Version="2.2.7" />
    <PackageReference Include="Microsoft.AspNetCore.Hosting.WindowsServices" Version="3.0.0" />
    <PackageReference Include="Microsoft.AspNetCore.Mvc.Core" Version="2.2.5" />
    <PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="3.0.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="3.0.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.0.0" />
    <PackageReference Include="Microsoft.Extensions.Hosting" Version="3.0.1" />
    <PackageReference Include="Microsoft.Extensions.Hosting.WindowsServices" Version="3.0.0" />
    <PackageReference Include="System.ServiceModel.Duplex" Version="4.4.*" />
    <PackageReference Include="System.ServiceModel.Http" Version="4.4.*" />
    <PackageReference Include="System.ServiceModel.NetTcp" Version="4.4.*" />
    <PackageReference Include="System.ServiceModel.Security" Version="4.4.*" />
  </ItemGroup>

  <ItemGroup>
    <WCFMetadata Include="Connected Services" />
  </ItemGroup>
</Project>

I also changed my program.cs and changed from IWebHostBuilder to IHostBuilder as shown below;

public class Program
    {
        public static void Main(string[] args)
        {
            var isService = !(Debugger.IsAttached || args.Contains("--console"));
            if (isService)
            {
                CreateHostBuilder(args).Build().Run();//.RunAsService();
            }
            else
            {
                CreateHostBuilder(args).Build().Run();
            }
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .UseContentRoot(Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName))
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                    webBuilder.UseKestrel((context, serverOptions) =>
                    {
                        serverOptions.ListenAnyIP(1042);
                        serverOptions.Limits.KeepAliveTimeout = TimeSpan.FromMinutes(1.5);
                    });
                }).UseWindowsService();
    }

Just to make sure that the service builds with a specific version of .Net Core SDK I added the following global.json

{
  "sdk": {
    "version": "3.0.100",
    "rollForward": "disable"
  }
}

I then  built and published.

NOTE : I have also noted InstallUtil does not work with ASP.NET Worker Service. So, you have to change and use SC to install your service.Like so;

SC {SERVICENAME} binpath="{path-to-exe}"


来源: stackexchange

问:
How do I use a row count in an @if in a Laravel view?
I am brand new to Laravel and I'm running Version 6.

I want my view to display a button if one of my MySQL tables has rows that meet a specific condition but I'm having trouble figuring out how to code it - and even WHERE to code it - within my Laravel application.

My MySQL table is called diary_entries and various users of the system will contribute zero to n  rows to it. Each row of the table contains a user id called client. When a given user goes to the Welcome view, I want the view to determine if that user currently has any rows in the diary_entries table. If he does, I want to display a button that will take him to another page where the entries can be displayed or edited or deleted.

I think I want to construct an @if that counts the number of records for that user; if the count is greater than zero, I want to display the button, otherwise the button is not displayed.

The problem is that I can't figure out how to code this. I've looked at the examples in the Eloquent section of the manual but they aren't particularly clear to me. I found a note near the top that said the count() function expects a Collection as an argument and that the result of an Eloquent statement is always a Collection so I guessed that I just have to execute an Eloquent query, then apply count() to the resulting Collection. But every variation of that idea which I've tried has thrown exceptions.

Here was the guess that seemed most logical to me:

```<code>@extends('layout');

@section('content');
<div class="content">
    <img class="centered" src="/images/sleeping-cat.jpg" alt="sleeping cat" height="250">
    <div class="title m-b-md">
        <h1> Sleep Diary </h1>
    </div>
    <div>
        <h3>{{Auth::user()->name }}</h3>
    </div>
    <div>
        @if (count(App\DiaryEntry::select('*')->where('client', Auth::user()->name) > 0))
            <p>
                <a class="btn btn-primary"> View / edit existing sleep diary entries </a>
            </p>
        @endif
    </div>
    <div>
        <p>
            <a class="btn btn-primary" href="/diaryEntries"> Create a new sleep diary entry </a>
    </div>
</div>
@endsection
</code>```

This is obviously wrong because it throws an exception so how do I make it right? Does the building of the collection have to move into the Controller? If so, how do I invoke the method and see its result? Or can I do something like I have already done but just adjust the syntax a bit?

EDIT

I've imitated Sehdev's suggestion but I get this error:

```<code>$count is undefined

Make the variable optional in the blade template. Replace {{ $count }} with {{ $count ?? '' }}
</code>```

Here is my welcome view:

```<code> @extends('layout');

 @section('content');
   <div class="content">
    <img class="centered" src="/images/sleeping-cat.jpg" alt="sleeping cat" height="250">
    <div class="title m-b-md">
        <h1>Sleep Diary</h1>
    </div>
    <div>
      <h3>{{ Auth::user()->name }}</h3>
    </div>
    <div>
        @if ($count) > 0))
        <p>
            <a class="btn btn-primary">View/edit existing sleep diary entries</a>
        </p>
        @endif
    </div>
    <div>
        <p><a class="btn btn-primary" href="/diaryEntries">Create a new sleep diary entry</a>
    </div>
    </div>
    @endsection
</code>```

And this is the relevant function from DiaryEntryController:

```<code> public function countEntriesOneUser()
 {
    $count = DiaryEntry::select('*')->where('client', Auth::user()->name)->count();
     view("welcome", compact("count"));
    }
</code>```

Should the compact function be returning $count instead of count? I can't find the compact function in the manual with the search function so I'm not clear what it does or what the proper syntax is. I just tried changing the last line of the function to

```<code>view("welcome", $count);
</code>```

but that produced the same error.

答:
Using App\DiaryEntry::select('*')->where('client', Auth::user()->name) directly on your blade template is a bad practise.

You can execute your question in your controllers method and then pass the result on your view file

Your function

```<code>function test(){

    $count = DiaryEntry::select('*')->where('client', Auth::user()->name)->count();  // get the total no of records using count
    view("index", compact("count")) // pass your count variable here

}
</code>```

then you can directly use $count in your @if condition

Your blade template

```<code><div>
    @if ($count > 0)
    <p><a class="btn btn-primary">View/edit existing sleep diary entries</a></p>
    @endif
</div>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am brand new to Laravel and I'm running Version 6.

I want my view to display a button if one of my MySQL tables has rows that meet a specific condition but I'm having trouble figuring out how to code it - and even WHERE to code it - within my Laravel application.

My MySQL table is called diary_entries and various users of the system will contribute zero to n  rows to it. Each row of the table contains a user id called client. When a given user goes to the Welcome view, I want the view to determine if that user currently has any rows in the diary_entries table. If he does, I want to display a button that will take him to another page where the entries can be displayed or edited or deleted.

I think I want to construct an @if that counts the number of records for that user; if the count is greater than zero, I want to display the button, otherwise the button is not displayed.

The problem is that I can't figure out how to code this. I've looked at the examples in the Eloquent section of the manual but they aren't particularly clear to me. I found a note near the top that said the count() function expects a Collection as an argument and that the result of an Eloquent statement is always a Collection so I guessed that I just have to execute an Eloquent query, then apply count() to the resulting Collection. But every variation of that idea which I've tried has thrown exceptions.

Here was the guess that seemed most logical to me:

@extends('layout');

@section('content');

 Sleep Diary

{{Auth::user()->name }}

        @if (count(App\DiaryEntry::select('*')->where('client', Auth::user()->name) > 0))

                 View / edit existing sleep diary entries

        @endif

             Create a new sleep diary entry

@endsection

This is obviously wrong because it throws an exception so how do I make it right? Does the building of the collection have to move into the Controller? If so, how do I invoke the method and see its result? Or can I do something like I have already done but just adjust the syntax a bit?

EDIT

I've imitated Sehdev's suggestion but I get this error:

$count is undefined

Make the variable optional in the blade template. Replace {{ $count }} with {{ $count ?? '' }}

Here is my welcome view:

 @extends('layout');

 @section('content');

Sleep Diary

{{ Auth::user()->name }}

        @if ($count) > 0))

            View/edit existing sleep diary entries

        @endif

Create a new sleep diary entry

    @endsection

And this is the relevant function from DiaryEntryController:

 public function countEntriesOneUser()
 {
    $count = DiaryEntry::select('*')->where('client', Auth::user()->name)->count();
     view("welcome", compact("count"));
    }

Should the compact function be returning $count instead of count? I can't find the compact function in the manual with the search function so I'm not clear what it does or what the proper syntax is. I just tried changing the last line of the function to

view("welcome", $count);

but that produced the same error.

Body:
Using App\DiaryEntry::select('*')->where('client', Auth::user()->name) directly on your blade template is a bad practise.

You can execute your question in your controllers method and then pass the result on your view file

Your function

function test(){

    $count = DiaryEntry::select('*')->where('client', Auth::user()->name)->count();  // get the total no of records using count
    view("index", compact("count")) // pass your count variable here

}

then you can directly use $count in your @if condition

Your blade template

<div>
    @if ($count > 0)
    <p><a class="btn btn-primary">View/edit existing sleep diary entries</a></p>
    @endif
</div>


问:
Python Regex: Apostrophes only when placed within letters, not as quotation marks
define each word to be the longest contiguous sequence of alphabetic characters (or just letters), including up to one apostrophe if that apostrophe is sandwiched between two letters. </p>

```<code>[a-z]+[a-z/'?a-z]*[a-z$]
</code>```

<p>It doesn't match the letter 'a'. </p>

答:
Something like this should work

```<code>[a-zA-Z]*(?:[a-zA-Z]\'[a-zA-Z]|[a-zA-Z])[a-zA-Z]*
</code>```

Match 0 or more letters [a-zA-Z]*? followed by either an apostrophe surrounded by 2 letters or a single letter (?:[a-zA-Z]\'[a-zA-Z]|[a-zA-Z]) then match 0 or more letters [a-zA-Z]*

For just lowercase letters

```<code>[a-z]*(?:[a-z]\'[a-z]|[a-z])[a-z]*
</code>```

Body:
define each word to be the longest contiguous sequence of alphabetic characters (or just letters), including up to one apostrophe if that apostrophe is sandwiched between two letters.

[a-z]+[a-z/'?a-z]*[a-z$]

It doesn't match the letter 'a'.

Body:
Something like this should work

[a-zA-Z]*(?:[a-zA-Z]\'[a-zA-Z]|[a-zA-Z])[a-zA-Z]*

Match 0 or more letters [a-zA-Z]*? followed by either an apostrophe surrounded by 2 letters or a single letter (?:[a-zA-Z]\'[a-zA-Z]|[a-zA-Z]) then match 0 or more letters [a-zA-Z]*

For just lowercase letters

[a-z]*(?:[a-z]\'[a-z]|[a-z])[a-z]*


问:
Karate framework: Look for child API response(which is dynamic) in parent API
I have a scenario where a portion of the Parent API response is from a child API. If the child API response(which is dynamic) has only one array element then no need to match that in parent API response, if array size > 1 then I need to match from index 1 on wards with parent API response.

```<code>* def child =  {"array1":[{"mbr1":{"id":"A1"}},{"mbr2":{"id":"A2"}}]}
</code>```

There is no specific order for the child api response and array1 can have "n" number of array elements(mbr1,mbr2,mbr3, etc)

If the child API response is like above then the parent will look like below:

```<code>* def parent =  {"parent":{"muid":"1234"},"elg":[{"EID":"E123"},{"members":[{"mbr2":{"id":"A2"}}]}]}
</code>```

So in parent API response towards the end child api response is populated, only if the above mentioned conditions are satisfied.
If child API returns only one element then the parent API response will look like the below:

```<code>* def parent = {"parent":{"muid":"1234"},"elg":[{"EID":"E123"}]}
</code>```

So how do I do a match to see whether the child is present in parent if child returns 200 OK and the child array length > 1?
So I am looking for the solution of the below scenario:

```<code>if (child responseStatus == 200){
    if (child.array1.length > 1){
        for (i = 1;i <= child.array1.length; i++){
            parent.elg[1].members[i] contains child.arrays1[i]
        }
    }
}
</code>```

答:
Here you go, and please read the docs: https://github.com/intuit/karate#conditional-logic</p>

```<code>* def parentArray = parent.elg[1].array1
* def expected = child.array1.length > 1 ? child.array1 : parentArray
* match parentArray contains only expected
</code>```

Body:
I have a scenario where a portion of the Parent API response is from a child API. If the child API response(which is dynamic) has only one array element then no need to match that in parent API response, if array size > 1 then I need to match from index 1 on wards with parent API response.

* def child =  {"array1":[{"mbr1":{"id":"A1"}},{"mbr2":{"id":"A2"}}]}

There is no specific order for the child api response and array1 can have "n" number of array elements(mbr1,mbr2,mbr3, etc)

If the child API response is like above then the parent will look like below:

* def parent =  {"parent":{"muid":"1234"},"elg":[{"EID":"E123"},{"members":[{"mbr2":{"id":"A2"}}]}]}

So in parent API response towards the end child api response is populated, only if the above mentioned conditions are satisfied.
If child API returns only one element then the parent API response will look like the below:

* def parent = {"parent":{"muid":"1234"},"elg":[{"EID":"E123"}]}

So how do I do a match to see whether the child is present in parent if child returns 200 OK and the child array length > 1?
So I am looking for the solution of the below scenario:

if (child responseStatus == 200){
    if (child.array1.length > 1){
        for (i = 1;i <= child.array1.length; i++){
            parent.elg[1].members[i] contains child.arrays1[i]
        }
    }
}

Body:
Here you go, and please read the docs: https://github.com/intuit/karate#conditional-logic

* def parentArray = parent.elg[1].array1
* def expected = child.array1.length > 1 ? child.array1 : parentArray
* match parentArray contains only expected


问:
Program using ceil() in C
I did the following code using ceil()

```<code>#include<stdio.h>
#include<math.h>
int main()
{
  float val;
  float cVal;

  val=23.4;

  cVal =ceil(val);
  printf("ceil value:%f\n",cVal);
  return 0;
}
</code>```

I am getting th following error
In function main':
test1.c:(.text+0x1b): undefined reference toceil'
collect2: error: ld returned 1 exit status

What is wrong in this code??Please help!

I compiled it using makefile

```<code>>>cmake .
>>make
>>./hello.out
</code>```

答:
From https://askubuntu.com/a/745199/513302

If you are going to compile a C program with math.h library in Linux using gcc you will have to use –lm option in the compiler command-line

```<code>gcc xyz.c -o xyz -lm
</code>```

The -lm option is actually -l (for "link a module") and m is shorthand for the built-in math library.

Title: Program using ceil() in C

Body:
I did the following code using ceil()

#include<stdio.h>
#include<math.h>
int main()
{
  float val;
  float cVal;

  val=23.4;

  cVal =ceil(val);
  printf("ceil value:%f\n",cVal);
  return 0;
}

I am getting th following error
In function main':
test1.c:(.text+0x1b): undefined reference toceil'
collect2: error: ld returned 1 exit status

What is wrong in this code??Please help!

I compiled it using makefile

>>cmake .
>>make
>>./hello.out

Body:
From https://askubuntu.com/a/745199/513302

If you are going to compile a C program with math.h library in Linux using gcc you will have to use –lm option in the compiler command-line

gcc xyz.c -o xyz -lm

The -lm option is actually -l (for "link a module") and m is shorthand for the built-in math library.


问:
Can I specify the dates and times of a time series in R?
I have a dataset that contains times and dates in the first column, and the stock prices in the second column.

I used the following format.

```<code>      Time              Price
2015-02-01 10:00         50
</code>```

I want to turn this into a time series object. I tried ts(data) function, but when I plot the data I cannot observe the dates in the x-axis. Also I tried ts(data, start=) function. Because I have some hours with missing prices, and those hours are not included in my data set, if I set start date and frequency, my plot will be misleading.

Here is the sample data that I have. It is called df.

```<code>           time         price

1   2013-05-01 00:00:00 124.30
2   2013-05-01 01:00:00 98.99
3   2013-05-01 02:00:00 64.00
4   2013-05-01 03:00:00 64.00
</code>```

This is the code that I used

```<code>Time1 <- ts(df)
autoplot(Time1)
</code>```

Also tried this,

```<code>Time1 <- zoo(Time_series_data[,2], order.by = Time_series_data[,1])
Time_n <- ts(Time1)
autoplot(Time1)
</code>```

However, when I plot the graph with autoplot(Time1) the x-axis doesn't show the times that I specified but numbers from 0 to 4. I want to have plot of a ts object that includes the date columns in the x-axis and values in Y

Is there any way to convert it to a time series object in R. Thanks.

答:
Try the following:

Create some data using the nifty tribble function from the tibble package.

```<code>library(tibble)
df <- tribble(~time,      ~price,
   "2013-05-01 00:00:00", 124.30,
   "2013-05-01 01:00:00", 98.99,
   "2013-05-01 02:00:00", 64.00,
   "2013-05-01 03:00:00", 64.00)
</code>```

The time column is a character class and cannot be plotted in the usual way. So convert it using as.Posixct. I'll use the dplyr package here but that's optional.

```<code>library(dplyr)

df <- df %>%
  mutate(time=as.POSIXct(time))
</code>```

Next, convert the data to a time series object. This requires the xts package, although I'm sure there are other options including zoo.

```<code>library(xts)
df.ts <- xts(df[, -1], order.by=df$time)
</code>```

Now you can visualise the data.

```<code>plot(df.ts)  # This should call the `plot.xts` method
</code>```

And if you prefer ggplot2.

```<code>library(ggplot2)
autoplot(df.ts)
</code>```

Body:
I have a dataset that contains times and dates in the first column, and the stock prices in the second column.

I used the following format.

      Time              Price
2015-02-01 10:00         50

I want to turn this into a time series object. I tried ts(data) function, but when I plot the data I cannot observe the dates in the x-axis. Also I tried ts(data, start=) function. Because I have some hours with missing prices, and those hours are not included in my data set, if I set start date and frequency, my plot will be misleading.

Here is the sample data that I have. It is called df.

           time         price

1   2013-05-01 00:00:00 124.30
2   2013-05-01 01:00:00 98.99
3   2013-05-01 02:00:00 64.00
4   2013-05-01 03:00:00 64.00

This is the code that I used

Time1 <- ts(df)
autoplot(Time1)

Also tried this,

Time1 <- zoo(Time_series_data[,2], order.by = Time_series_data[,1])
Time_n <- ts(Time1)
autoplot(Time1)

However, when I plot the graph with autoplot(Time1) the x-axis doesn't show the times that I specified but numbers from 0 to 4. I want to have plot of a ts object that includes the date columns in the x-axis and values in Y

Is there any way to convert it to a time series object in R. Thanks.

Body:
Try the following:

Create some data using the nifty tribble function from the tibble package.

library(tibble)
df <- tribble(~time,      ~price,
   "2013-05-01 00:00:00", 124.30,
   "2013-05-01 01:00:00", 98.99,
   "2013-05-01 02:00:00", 64.00,
   "2013-05-01 03:00:00", 64.00)

The time column is a character class and cannot be plotted in the usual way. So convert it using as.Posixct. I'll use the dplyr package here but that's optional.

library(dplyr)

df <- df %>%
  mutate(time=as.POSIXct(time))

Next, convert the data to a time series object. This requires the xts package, although I'm sure there are other options including zoo.

library(xts)
df.ts <- xts(df[, -1], order.by=df$time)

Now you can visualise the data.

plot(df.ts)  # This should call the `plot.xts` method

And if you prefer ggplot2.

library(ggplot2)
autoplot(df.ts)


问:
C++ memory Alignment on a 64 bit machine
```<code>Class A
{
  public:
    void fun1();
    void fun2();

  private:
     uint16 temp_var;
};
</code>```

Is there any reason why I shouldn't just make this variable uint16 to full uint64?  Doing it this way (uin16), do I leave memory "holes" in the object ?, and I'm told the processor is more efficient in dealing with full uint64s.
for clarification, temp_var is the only member variable. And no where i was using it for size(temp_var) or as a counter to loop back to zero

Thank you all for your inputs, appreciate it..

答:
If the question is, can the compiler do the substitution:

You asked for a uint16 so it gave you a uint16. It would be surprising to get something else.

For instance, imagine if a developer was counting on a behavior of integer overflow or underflow. In that case, if the compiler substituted a uint64 behind the scenes, then that would be problematically surprising for the developer.

Along the same lines, one would expect sizeof(temp_var) to equal sizeof(uint16).

There are probably further cases in which such a substitution could lead to unexpected behavior that wouldn't be anticipated by the developer.

If the question is, can you the developer pick something else:

Sure, you can if you want a variable of that size. So then how about some possibilities where you wouldn't...

If you rely on overflow/underflow behavior of a uint16 then of course you would want to stick to that.

Or perhaps this data is going to be passed along to some further location that only supports values in the range of a uint16, so leaving it that size may make logical sense to try to implicitly document what's valid and/or avoid compiler warnings.

Similarly you might want for sizeof(temp_var) to be 2 bytes instead of 8 for some logical reason relevant to other parts of the program.

I also expect there are some games one could play with the packing pragma, but I presume that isn't relevant to the intended question.

Depending on the goal of your program, logical consistency or clarity of code may be more important than maximum possible performance (especially at the micro level of being concerned about size/type of a member variable). To phrase that another way, uint16 is still fast enough for many many use cases.

In some situations though, there won't be any compelling reason to make the decision one way or the other. At that point, I would go with whatever seems to make the most sense as per personal sensibilities.

Body:
Class A
{
  public:
    void fun1();
    void fun2();

  private:
     uint16 temp_var;
};

Is there any reason why I shouldn't just make this variable uint16 to full uint64?  Doing it this way (uin16), do I leave memory "holes" in the object ?, and I'm told the processor is more efficient in dealing with full uint64s.
for clarification, temp_var is the only member variable. And no where i was using it for size(temp_var) or as a counter to loop back to zero

Thank you all for your inputs, appreciate it..


问:
How to move mediawiki 'Echo' extension icons?
so I'm a bit stuck. I have my own private mediawiki and until now I could find everything by myself out. There is an extension called 'Echo' and I find it pretty useful. I don't want to have the extension icons in the 'mw-head -> p-personal' section. I want to move it to my own customized navigation bar. But I don't know how, it looks like it is designed to only work with the stock skin. Maybe someone here can help and has some experience with that extension.

Best Regards

答: Probably you can use the PersonalUrls hook. Register it so that it runs after Echo (e.g. via Hooks::register which is always called later than the normal hook registration mechanism), remove the notifications-alert and notifications-notice elements of the array, and render them on your own toolbar.


问:
How to map a DTO with a many-to-many relationship to a EF core entity with a relationship table using automapper?
I have two entities in my DB. A and B. I also have a relationship table representing a many to many relation between these entities AB:

```<code>public class A
{
    public ICollection<AB> ABs { get; set; }
}

public class B
{
    public ICollection<AB> ABs { get; set; }
}

public class AB
{
    public A A { get; set; }
    public B B { get; set; }
}
</code>```

Now I want to hide this relation table in my dto like so:

```<code>public class ADTO
{
    public ICollection<B> Bs { get; set; }
}
</code>```

I want a single collection of Bs with my instances represented directly, not as a relation table. I want to have an automapper profile that maps from a list of entities B to a list of previously not existing entities AB with B as an attribute, as well as the instance A itself.

I already have implemented the mapper from A to ADTO like so:

```<code>public class AProfile : Profile
{
    public AProfile()
    {
        CreateMap<A, ADTO>()
            .ForMember(dest => dest.B, opt => opt.MapFrom(src => src.AB.Select(y => y.B).ToList()));
        CreateMap<ADTO, A>();
    }
}
</code>```

What I am missing is the reverse direction: From ADTO with its list of entities to A with its reference to the relationship table entity.

答:
Make your profile like below:</p>

```<code>  CreateMap<ADTO, A>()
            .ForMember(dest => dest.AName, opt => opt.MapFrom(src => src.AName))
            .ForMember(dest => dest.ABs, opt => opt.MapFrom(src => src.Bs))
            .AfterMap((src, dest) =>{
                foreach(var b in dest.ABs)
                {
                    b.AId = src.Id;
                }
            });
  CreateMap<B, AB>()
            .ForMember(dest=>dest.BId,opt=>opt.MapFrom(src=>src.Id))
            .ForMember(dest=>dest.B,opt=>opt.MapFrom(src=>src));
</code>```

Body:
I have two entities in my DB. A and B. I also have a relationship table representing a many to many relation between these entities AB:

public class A
{
    public ICollection<AB> ABs { get; set; }
}

public class B
{
    public ICollection<AB> ABs { get; set; }
}

public class AB
{
    public A A { get; set; }
    public B B { get; set; }
}

Now I want to hide this relation table in my dto like so:

public class ADTO
{
    public ICollection Bs { get; set; }
}

I want a single collection of Bs with my instances represented directly, not as a relation table. I want to have an automapper profile that maps from a list of entities B to a list of previously not existing entities AB with B as an attribute, as well as the instance A itself.

I already have implemented the mapper from A to ADTO like so:

public class AProfile : Profile
{
    public AProfile()
    {
        CreateMap()
            .ForMember(dest => dest.B, opt => opt.MapFrom(src => src.AB.Select(y => y.B).ToList()));
        CreateMap<ADTO, A>();
    }
}

What I am missing is the reverse direction: From ADTO with its list of entities to A with its reference to the relationship table entity.

Body:
Make your profile like below:

  CreateMap<ADTO, A>()
            .ForMember(dest => dest.AName, opt => opt.MapFrom(src => src.AName))
            .ForMember(dest => dest.ABs, opt => opt.MapFrom(src => src.Bs))
            .AfterMap((src, dest) =>{
                foreach(var b in dest.ABs)
                {
                    b.AId = src.Id;
                }
            });
  CreateMap<B, AB>()
            .ForMember(dest=>dest.BId,opt=>opt.MapFrom(src=>src.Id))
            .ForMember(dest=>dest.B,opt=>opt.MapFrom(src=>src));


问:
How to restrict the selection of one Radio Button in C#?
This is my code to select one item at a time.
But both the options are getting selected. How can I solve this issue?

function initializehrm__documentidRadiobuttonlist(documentid) {
    debugger
    ajaxCall("/Client/SysType/GetSysTypeByTypeGroupCodeAndSyslevel", { "typeGroupCode": sysTypeGroupCodeEmployeeImmigrationDocument }, "POST", "callback_initializehrm__documentidRadiobuttonlist", documentid);
}
function callback_initializehrm__documentidRadiobuttonlist(data, documentid) {debugger
    data = data.data;
    var hrm__documentidRadiobuttonlisthtml = "";
    $.each(data, function (index, item) {
        item = removeVirtualObjectPropertiesFromJsonObject(item);
        hrm__documentidRadiobuttonlisthtml += "
<input type='radio' id='documentid" + index + "' value=" + item.id + " />" + item.title + "
"
    });

    $("#rdohrm__documentid").html(hrm__documentidRadiobuttonlisthtml);
}```

答:
Multiple radio buttons must share the same name (the value of the name attribute), so that it is treated as a group, and only one selection is allowed.

Modify your < input > tag something like below:

```<code>"<div><input type='radio' id='documentid" + index + "' value=" + item.id + " name='documents' /><span>" + item.title + "</span></div>"
</code>```

Body:
Multiple radio buttons must share the same name (the value of the name attribute), so that it is treated as a group, and only one selection is allowed.

Modify your < input > tag something like below:

"<div><input type='radio' id='documentid" + index + "' value=" + item.id + " name='documents' /><span>" + item.title + "</span></div>"


问:
Inheriting and overriding ostream operator in C++
I've been trying to find an answer to this, but no one seems to have exactly the same problem as I do.

I am working with several derived classes. The ostream operator << for each of these should print out some things common to each, and some things specific to each.  Later on, I would like to further derive from these derived classes, and again the new derived classes need to print out some things that are in the "generations" above them.

For example:

The Base class .h file

```<code>class Base

{

 int FirstClassNumber;

//The declaration I'm currently working with, that a friend gave me
//I'm pretty sure my problem lies here.

public:

friend ostream& operator << (ostream& os, const Base &base)
{
    base << os ;

    return os;
}

virtual void operator << (ostream& os) const = 0;

};
</code>```

The Base.cpp file includes these lines:

```<code>void Base::operator << (ostream& os)
{
  os << FirstClassNumber;
}
</code>```

Then I derive: (FirstDerived.h)

```<code>class FirstDerived : Public Base

{

int SecondClassNumber;

};
</code>```

FirstDerived.cpp:

```<code>FirstDerived::operator << (ostream& os)
{
  os <<

  "The first Number is:

 //This is the line that isn't working - someone else gave me this syntax

  << Base::operator<<

  << "The second number is"

  << SecondClassNumber;
}
</code>```

Then I want to derive:

```<code>class SecondDerived: Public FirstDerived
{

int ThirdClassNumber;

};
</code>```

Second.cpp:

```<code>FirstDerived::operator << (ostream& os)
{
  os <<

 FirstDerived::operator<<

 << "The third number is "

 << ThirdClassNumber;

 }
</code>```

I think the problem is most likely either the declaration in the very start of the program, or the lines like Base::operator<<.

Another possibility is that I'm not redeclaring it in the .h file of every inherited class.  Should I be, and if so what syntax should I use?

It was suggested to me to use the static_cast method, but my professor (the one who wrote the assignment, and therefore won't give us too much help with it) said that there's a better way to do it.  Any suggestions?

答:
To call a method from base class you can use:

```<code>Base::method(/*parameters*/)
</code>```

But operator<< is a free function. The only possibility without static_cast I can see is to define the operator as a template and then explicitly call the specialization like this:

```<code>template<typename T>
void function(T const &t);

template<>
void function<Base>(Base const &t) {
    // own implementation ...
}

template<>
void function<Derived>(Derived const &t) {
    function<Base>(t);
    // own implementation ...
}
</code>```

This could be done the same way for operator<<, just change the name function for operator<< and add required parameters.

Another possibility is to make a virtual member function:

```<code>class Base {
    virtual void print(ostream &os) const {
        // print self
    }
};
</code>```

In Derived class this could call the Base print function:

```<code>class Derived {
    virtual void print(ostream &os) const {
        Base::print(os);
        // print self
    }
};
</code>```

Then it is enough to have operator<< only for the Base class and it will call appropriate print method polymorphicaly. Note that the operator<< is a free function.

```<code>ostream &operator<< (ostream &os, Base const &b) {
    b.print(os);
    return os;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I've been trying to find an answer to this, but no one seems to have exactly the same problem as I do.

I am working with several derived classes. The ostream operator << for each of these should print out some things common to each, and some things specific to each.  Later on, I would like to further derive from these derived classes, and again the new derived classes need to print out some things that are in the "generations" above them.

For example:

The Base class .h file

class Base

{

 int FirstClassNumber;

//The declaration I'm currently working with, that a friend gave me
//I'm pretty sure my problem lies here.

public:

friend ostream& operator << (ostream& os, const Base &base)
{
    base << os ;

    return os;
}

virtual void operator << (ostream& os) const = 0;

};

The Base.cpp file includes these lines:

void Base::operator << (ostream& os)
{
  os << FirstClassNumber;
}

Then I derive: (FirstDerived.h)

class FirstDerived : Public Base

{

int SecondClassNumber;

};

FirstDerived.cpp:

FirstDerived::operator << (ostream& os)
{
  os <<

  "The first Number is:

 //This is the line that isn't working - someone else gave me this syntax

  << Base::operator<<

  << "The second number is"

  << SecondClassNumber;
}

Then I want to derive:

class SecondDerived: Public FirstDerived
{

int ThirdClassNumber;

};

Second.cpp:

FirstDerived::operator << (ostream& os)
{
  os <<

 FirstDerived::operator<<

 << "The third number is "

 << ThirdClassNumber;

 }

I think the problem is most likely either the declaration in the very start of the program, or the lines like Base::operator<<.

Another possibility is that I'm not redeclaring it in the .h file of every inherited class.  Should I be, and if so what syntax should I use?

It was suggested to me to use the static_cast method, but my professor (the one who wrote the assignment, and therefore won't give us too much help with it) said that there's a better way to do it.  Any suggestions?

Body:
To call a method from base class you can use:

Base::method(/*parameters*/)

But operator<< is a free function. The only possibility without static_cast I can see is to define the operator as a template and then explicitly call the specialization like this:

template<typename T>
void function(T const &t);

template<>
void function<Base>(Base const &t) {
    // own implementation ...
}

template<>
void function<Derived>(Derived const &t) {
    function<Base>(t);
    // own implementation ...
}

This could be done the same way for operator<<, just change the name function for operator<< and add required parameters.

Another possibility is to make a virtual member function:

class Base {
    virtual void print(ostream &os) const {
        // print self
    }
};

In Derived class this could call the Base print function:

class Derived {
    virtual void print(ostream &os) const {
        Base::print(os);
        // print self
    }
};

Then it is enough to have operator<< only for the Base class and it will call appropriate print method polymorphicaly. Note that the operator<< is a free function.

ostream &operator<< (ostream &os, Base const &b) {
    b.print(os);
    return os;
}


问:
Why my github connection stopped working without any change
I had been using Github on my personal Mac and IntelliJ for long time.
In fact, I run spring-boot config server also on local backed by Git repo on github, and all had been working fine .until today.
Today suddenly, my local config server stopped working.
I tried and not able to use IntelliJ to push code to Github

So I tried using the terminal, but I've got the following error today.

```<code>MacBook-Pro ~ %  ssh -T -p 443 git@ssh.github.com
The authenticity of host '[ssh.github.com]:443 ([192.30.253.123]:443)' can't be established.
RSA key fingerprint is SHA256:nThbg6kXUpJWGl7E1IGOCspRomTxdCARLviKw6E5SY8.
Are you sure you want to continue connecting (yes/no)?
Host key verification failed.
</code>```

Until yesterday all was working fine. I was not even using the Terminal, I had been committing and pushing code through Intellij. But today everything is failing.

I pressed yes in the above command. And got the following message

```<code>Warning: Permanently added '[ssh.github.com]:443,[192.30.253.123]:443' (RSA) to the list of known hosts.
Hi xxxxxx! You've successfully authenticated, but GitHub does not provide shell access.
</code>```

But I'm still not able to push or infect connect the GitHub.
I checked the files in ~/.ssh folder. Nothing was changed since December.
I checked my Github Profile settings ssh key, nothing changed since December.

But suddenly today everything stopped working.
Any help is appreciated.

答:
The only difference is, I was using public wifi in a coffee shop.

Double-check if this is working again (at the coffee shop); at least from command-line:

```<code>git ls-remote git@github.com:me/myrepo
# or
export GIT_SSH_COMMAND='ssh -p 443'
git ls-remote git@ssh.github.com:me/myrepo
</code>```

Body:
I had been using Github on my personal Mac and IntelliJ for long time.
In fact, I run spring-boot config server also on local backed by Git repo on github, and all had been working fine .until today.
Today suddenly, my local config server stopped working.
I tried and not able to use IntelliJ to push code to Github

So I tried using the terminal, but I've got the following error today.

MacBook-Pro ~ %  ssh -T -p 443 git@ssh.github.com
The authenticity of host '[ssh.github.com]:443 ([192.30.253.123]:443)' can't be established.
RSA key fingerprint is SHA256:nThbg6kXUpJWGl7E1IGOCspRomTxdCARLviKw6E5SY8.
Are you sure you want to continue connecting (yes/no)?
Host key verification failed.

Until yesterday all was working fine. I was not even using the Terminal, I had been committing and pushing code through Intellij. But today everything is failing.

I pressed yes in the above command. And got the following message

Warning: Permanently added '[ssh.github.com]:443,[192.30.253.123]:443' (RSA) to the list of known hosts.
Hi xxxxxx! You've successfully authenticated, but GitHub does not provide shell access.

But I'm still not able to push or infect connect the GitHub.
I checked the files in ~/.ssh folder. Nothing was changed since December.
I checked my Github Profile settings ssh key, nothing changed since December.

But suddenly today everything stopped working.
Any help is appreciated.

Body:
The only difference is, I was using public wifi in a coffee shop.

Double-check if this is working again (at the coffee shop); at least from command-line:

git ls-remote git@github.com:me/myrepo
# or
export GIT_SSH_COMMAND='ssh -p 443'
git ls-remote git@ssh.github.com:me/myrepo


问:
How to configure Apache NiFi with WSO2 IS for SSO
I have integrated NiFi with Apache Knox but I'm not getting how to integrate NiFi with WSO2 IS using SAML2. How can I integrate Apache NiFi with WSO2 Identity server using SAML for SSO.

答:
It seems like, NiFi doesn't support SAML authentication. But support the OIDC flow. Refer to this

So to integrate with WSO2 IS, you can create a service provider with OAuth in WSO2 IS side and set up with the NiFi. You can also refer to this, which explains how to integrate the OIDC with NiFi using google as an example. Here only different with the WSO2 is how the OAuth application is created.


问:
Webpack generate css file for each import
Im using webpack and this to compile scss files:

```<code>{
  test: /\.scss$/i,
  use: [
    // Creates css files
    {
      loader: MiniCssExtractPlugin.loader,
      options: {
        esModule: true,
      },
    },
    "@teamsupercell/typings-for-css-modules-loader",
    // Translates CSS into CommonJS
    {
      loader: 'css-loader',
      options: {
        modules: true
      }
    },
    // Compiles Sass to CSS
    'sass-loader',
  ],
},
</code>```

This is generating only one CSS file called main. I want to generate a CSS file for each SCSS file in my source so I can implement lazy loading of CSS.

I need a way to generate them individually and also generate the JavaScript to download them from the server when required.

Is this possible with the plugins that exist today?

答:
I want to generate a CSS file for each SCSS file in my source so I can
  implement lazy loading of CSS.

With this requirement, you don't need webpack. node-sass package is enough for you.

In the package.json file, you configure the scripts like this:

```<code>{
    "name": "your_project_name",
    "version": "1.0.0",
    "private": true,
    "dependencies": {
        "node-sass": "^4.13.1"
    },
    "scripts": {
        "sass": "node-sass -w scss_folder -o css_folder --output-style compressed"
    }
}
</code>```

Explanation:

sass: This is your command name

node-sass, -w, -o, --output-style, compressed: You can find their explanations via the link above.

Your project structure looks like:

```<code>Your_project
|
|_ css_folder
|
|_ scss_folder
|
|___ file01.scss
|
|___ file02.scss
|
|_ package.json
</code>```

In your project, open command prompt (or Terminal on Mac) and type:

```<code>npm run sass
</code>```

When it's ready to listen, you can try to create new scss file inside scss_folder. When you hit ctrl+s (or command+s on Mac), a new file with the same name will be generated in the folder css_folder, and the extension of the new file is .css. It's also compressed.

Body:
Im using webpack and this to compile scss files:

{
  test: /\.scss$/i,
  use: [
    // Creates css files
    {
      loader: MiniCssExtractPlugin.loader,
      options: {
        esModule: true,
      },
    },
    "@teamsupercell/typings-for-css-modules-loader",
    // Translates CSS into CommonJS
    {
      loader: 'css-loader',
      options: {
        modules: true
      }
    },
    // Compiles Sass to CSS
    'sass-loader',
  ],
},

This is generating only one CSS file called main. I want to generate a CSS file for each SCSS file in my source so I can implement lazy loading of CSS.

I need a way to generate them individually and also generate the JavaScript to download them from the server when required.

Is this possible with the plugins that exist today?

Body:
I want to generate a CSS file for each SCSS file in my source so I can
  implement lazy loading of CSS.

With this requirement, you don't need webpack. node-sass package is enough for you.

In the package.json file, you configure the scripts like this:

{
    "name": "your_project_name",
    "version": "1.0.0",
    "private": true,
    "dependencies": {
        "node-sass": "^4.13.1"
    },
    "scripts": {
        "sass": "node-sass -w scss_folder -o css_folder --output-style compressed"
    }
}

Explanation:

sass: This is your command name

node-sass, -w, -o, --output-style, compressed: You can find their explanations via the link above.

Your project structure looks like:

Your_project
|
|_ css_folder
|
|_ scss_folder
|
|___ file01.scss
|
|___ file02.scss
|
|_ package.json

In your project, open command prompt (or Terminal on Mac) and type:

npm run sass

When it's ready to listen, you can try to create new scss file inside scss_folder. When you hit ctrl+s (or command+s on Mac), a new file with the same name will be generated in the folder css_folder, and the extension of the new file is .css. It's also compressed.


问:
Scroll positioning behaves differently at different zoom levels
I have a multicolumn layout where the column on the right will update with the details of the item selected in the column on the left.

At a zoom level of 110% and below in Chrome, the column on the right will be scrolled to the top when selecting a different item on the left as in the gif below (this is the desired behavior).

However, at 125% zoom level and up, the scroll position of the column on the right is maintained when a new item on the left is selected (or worse, appears to scroll to the top, and then back down).

What could be causing this behavior? I am at a loss as to how to even debug this issue. I have tried messing with the overflow on several elements, and have looked through our styles for things related to scroll, but have come up short so far. The behavior doesn't appear to be specific to Chrome, as I am able to reproduce in Safari as well, but strangely it happens at a higher zoom level in Safari.

答:
Your issue could be due to the height of the section which gets varied at different zoom levels. Varying in heights may be due to increase in the width of the section after zooming.

If your current scrolling is achieved through plugins,
then kindly do reload the browser at different zoom levels and check if the issue still continues.
because, most plugins will be configured in a way to effect at page reload only.

If the above mentioned doesn't help, then do share your code snippet or any other info related to the development of this output


问:
How can I split a string and get just key part with regexp?
I have a string like <code>"A < -5.9 AND B >= 6 OR (C < 3)"</code> I have to get keys part.(A,B,C). So I thought I should split first AND and OR then I should get key part? Could you help me? I wrote just A,B,C but in my real example A can be any string. The important thing is that is value on the right side of
<,>,<=,>=  </p>

答:
Without regex you caniterate the string and match the character > or <. If the character matches then create a substring and then get the last character of the substring. Also note trim() will remove any white space from the string

let str = 'A < -5.9 AND B >= 6 OR (C < 3)';
let arr = [];
for (let i = 0; i < str.length; i++) {
  if (str[i] === '<' || str[i] === '>') {
    let subStr = str.substring(0, i).trim();
    arr.push(subStr.charAt(subStr.length - 1))
  }
};
console.log(arr);```

Body:
I have a string like "A < -5.9 AND B >= 6 OR (C < 3)" I have to get keys part.(A,B,C). So I thought I should split first AND and OR then I should get key part? Could you help me? I wrote just A,B,C but in my real example A can be any string. The important thing is that is value on the right side of
<,>,<=,>=


问:
How do i call a dictionary value from user input
I am new to programming, this is also my first post.

The problem is;

Ask the user how their weight is from a 1 to 4 scale.

```<code>1 = 0.5, 2 = 1.2, 3 = 1.7, 4 = 2.4.
</code>```

I set up my dictionary like this.

So when the user inputs 2

When I execute print, it prints 2 and not 1.2.
how do I update the new value?

答:
IIUC you need

```<code> scal3 = {"1":0.5, "2":1.2, "3":1.7, "4":2.4}

 n = input("enter a number: ")

 print(scal3[n])
</code>```

or if you don't want it to throw error if user enters wrong key

```<code>print(scal3.get(n))
</code>```

Body:
I am new to programming, this is also my first post.

The problem is;

Ask the user how their weight is from a 1 to 4 scale.

1 = 0.5, 2 = 1.2, 3 = 1.7, 4 = 2.4.

I set up my dictionary like this.

So when the user inputs 2

When I execute print, it prints 2 and not 1.2.
how do I update the new value?

Body:
IIUC you need

 scal3 = {"1":0.5, "2":1.2, "3":1.7, "4":2.4}

 n = input("enter a number: ")

 print(scal3[n])

or if you don't want it to throw error if user enters wrong key

print(scal3.get(n))


问:
Show User Name but hide everything else on the SharePoint Ribbon
On SharePoint 2010 I was able to figure out how to hide the SharePoint Ribbon links (site actions -- page --browse) with the following code on the master page:

```<code><SharePoint:SPSecurityTrimmedControl ID="SPSecurityTrimmedControl2" runat="server" PermissionsString="ManageLists">

<SharePoint:SPRibbon>
...
</SharePoint:SPRibbon>

</SharePoint:SPSecurityTrimmedControl>
</code>```

But this also hides the domain\username

Where do I put the code to hide everything except the username?
I am ok with creating more than one trimmedControl.

答:
You can simply open your Master Page using Sharepoint Designer 2010 and add Asp.Net:LoginName control instead of SharePoint Ribbon as following

```<code><asp:LoginName runat="server" id="LoginName"></asp:LoginName>
</code>```

I hope that help

Regards.

Body:
On SharePoint 2010 I was able to figure out how to hide the SharePoint Ribbon links (site actions -- page --browse) with the following code on the master page:

<SharePoint:SPSecurityTrimmedControl ID="SPSecurityTrimmedControl2" runat="server" PermissionsString="ManageLists">

<SharePoint:SPRibbon>
...
</SharePoint:SPRibbon>

</SharePoint:SPSecurityTrimmedControl>

But this also hides the domain\username

Where do I put the code to hide everything except the username?
I am ok with creating more than one trimmedControl.

Body:
You can simply open your Master Page using Sharepoint Designer 2010 and add Asp.Net:LoginName control instead of SharePoint Ribbon as following

<asp:LoginName runat="server" id="LoginName"></asp:LoginName>

I hope that help

Regards.


问:
Delete padding or Force fitting or Delete empty space from square Vector asset to Fit a Rectangular button?
I'm trying to adjust the all_inclusive svg image to my rectangular button. The shape itself is rectangular as well but the vector asset is square (24x24) with white spaces above and under the shape. These spaces force the shape itself to be very small. How to make the all inclusive svg rectangular by deleting that padding on top and on bottom?

In this picture the image is set to fit the guidelines on the left, top and right side:

```<code>    <ImageView
        android:id="@+id/imgInfinity"
        app:srcCompat="@drawable/ic_infinity"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintDimensionRatio="1:1"
        app:layout_constraintTop_toTopOf="0.75"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toEndOf="0.75"
        app:layout_constraintEnd_toEndOf="0.25" />
</code>```

Things that did not work:

pivot vector asset with a group -> I just cant figure out the dimensions without messing up the original shape. Same storty with scaleX/Y or translateX/Y. I got it to work on my other buttons with simpler shapes though.

adjusting android:viewportheight or android:height -> it deshapes the picture to a weird form

crop svg online --> as Googles original SVG pathData is already 580 characters long, cropping tools only make it to large for android to deal with (above 1000 charactes)

crop svg picture with word and extract from zip file-> it doesnt compress svg images so it stays rectangular with the white spaces above and under.

Set a seperate horizontal guideline for the top of the picture. It does the trick but one or multiple guidelines for each image gets very messy. There must be a better way, right?..

ACCEPTED SOLUTION (edit with InkShape):

Install InkShape

Open SVG

Click on picture once to select it

Go to File-> Document Properties and click 'Resize pager to drawing or selection' (this button is hidden on the first tab, click +Resize page to content to show the option);

Save

extract pathData and (viewport)width/heights from saved file.

答:
The viewportHeight attribute defines the size of the "canvas" that the path is drawn on (i.e., it defines what the coordinates in the path data actually "mean").

The height attribute defines the intrinsic size of the drawable.

The original vector has 6.5 units (in the viewport) of white space at the top and the bottom. That means that you can look for any pathData command that uses a capital letter, and subtract 6.5 from the y coordinate. That leaves you with this:

```<code><vector xmlns:android="http://schemas.android.com/apk/res/android"
        android:width="24dp"
        android:height="13dp"
        android:viewportWidth="24.0"
        android:viewportHeight="13.0">
    <path
        android:fillColor="#FF000000"
        android:pathData="M18.6,0.12c-1.44,0 -2.8,0.56 -3.77,1.53L12,4.16 10.48,5.5h0.01L7.8,7.89c-0.64,0.64 -1.49,0.99 -2.4,0.99 -1.87,0 -3.39,-1.51 -3.39,-3.38S3.53,2.12 5.4,2.12c0.91,0 1.76,0.35 2.44,1.03l1.13,1 1.51,-1.34L9.22,1.7C8.2,0.68 6.84,0.12 5.4,0.12 2.42,0.12 0,2.54 0,5.5s2.42,5.38 5.4,5.38c1.44,0 2.8,-0.56 3.77,-1.53l2.83,-2.5 0.01,0.01L13.52,5.5h-0.01l2.69,-2.39c0.64,-0.64 1.49,-0.99 2.4,-0.99 1.87,0 3.39,1.51 3.39,3.38s-1.52,3.38 -3.39,3.38c-0.9,0 -1.76,-0.35 -2.44,-1.03l-1.14,-1.01 -1.51,1.34 1.27,1.12c1.02,1.01 2.37,1.57 3.82,1.57 2.98,0 5.4,-2.41 5.4,-5.38s-2.42,-5.37 -5.4,-5.37z"/>
</vector>
</code>```

Then, once the whole shape has been moved "up" by 6.5 units, you can subtract 11 (6.5 * 2) from both the viewport and the intrinsic height.

The end result is a 24x13dp shape, which should scale much better in wide views.

Body:
I'm trying to adjust the all_inclusive svg image to my rectangular button. The shape itself is rectangular as well but the vector asset is square (24x24) with white spaces above and under the shape. These spaces force the shape itself to be very small. How to make the all inclusive svg rectangular by deleting that padding on top and on bottom?

In this picture the image is set to fit the guidelines on the left, top and right side:

    <ImageView
        android:id="@+id/imgInfinity"
        app:srcCompat="@drawable/ic_infinity"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintDimensionRatio="1:1"
        app:layout_constraintTop_toTopOf="0.75"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toEndOf="0.75"
        app:layout_constraintEnd_toEndOf="0.25" />

Things that did not work:

pivot vector asset with a group -> I just cant figure out the dimensions without messing up the original shape. Same storty with scaleX/Y or translateX/Y. I got it to work on my other buttons with simpler shapes though.

adjusting android:viewportheight or android:height -> it deshapes the picture to a weird form

crop svg online --> as Googles original SVG pathData is already 580 characters long, cropping tools only make it to large for android to deal with (above 1000 charactes)

crop svg picture with word and extract from zip file-> it doesnt compress svg images so it stays rectangular with the white spaces above and under.

Set a seperate horizontal guideline for the top of the picture. It does the trick but one or multiple guidelines for each image gets very messy. There must be a better way, right?..

ACCEPTED SOLUTION (edit with InkShape):

Install InkShape

Open SVG

Click on picture once to select it

Go to File-> Document Properties and click 'Resize pager to drawing or selection' (this button is hidden on the first tab, click +Resize page to content to show the option);

Save

extract pathData and (viewport)width/heights from saved file.

Body:
The viewportHeight attribute defines the size of the "canvas" that the path is drawn on (i.e., it defines what the coordinates in the path data actually "mean").

The height attribute defines the intrinsic size of the drawable.

The original vector has 6.5 units (in the viewport) of white space at the top and the bottom. That means that you can look for any pathData command that uses a capital letter, and subtract 6.5 from the y coordinate. That leaves you with this:

<vector xmlns:android="http://schemas.android.com/apk/res/android"
        android:width="24dp"
        android:height="13dp"
        android:viewportWidth="24.0"
        android:viewportHeight="13.0">
    <path
        android:fillColor="#FF000000"
        android:pathData="M18.6,0.12c-1.44,0 -2.8,0.56 -3.77,1.53L12,4.16 10.48,5.5h0.01L7.8,7.89c-0.64,0.64 -1.49,0.99 -2.4,0.99 -1.87,0 -3.39,-1.51 -3.39,-3.38S3.53,2.12 5.4,2.12c0.91,0 1.76,0.35 2.44,1.03l1.13,1 1.51,-1.34L9.22,1.7C8.2,0.68 6.84,0.12 5.4,0.12 2.42,0.12 0,2.54 0,5.5s2.42,5.38 5.4,5.38c1.44,0 2.8,-0.56 3.77,-1.53l2.83,-2.5 0.01,0.01L13.52,5.5h-0.01l2.69,-2.39c0.64,-0.64 1.49,-0.99 2.4,-0.99 1.87,0 3.39,1.51 3.39,3.38s-1.52,3.38 -3.39,3.38c-0.9,0 -1.76,-0.35 -2.44,-1.03l-1.14,-1.01 -1.51,1.34 1.27,1.12c1.02,1.01 2.37,1.57 3.82,1.57 2.98,0 5.4,-2.41 5.4,-5.38s-2.42,-5.37 -5.4,-5.37z"/>
</vector>

Then, once the whole shape has been moved "up" by 6.5 units, you can subtract 11 (6.5 * 2) from both the viewport and the intrinsic height.

The end result is a 24x13dp shape, which should scale much better in wide views.


问:
How to count a same data in JSON?
JSON to count:

```<code>[{"thn":"2017","jumlah":"30"},{"thn":"2018","jumlah":"80"},{"thn":"2018","jumlah":"64"},{"thn":"2018","jumlah":"5"},{"thn":"2018","jumlah":"1"},{"thn":"2018","jumlah":"1"},{"thn":"2018","jumlah":"4"},{"thn":"2018","jumlah":"5"},{"thn":"2018","jumlah":"198"},{"thn":"2018","jumlah":"2"},{"thn":"2018","jumlah":"202"},{"thn":"2019","jumlah":"31"},{"thn":"2019","jumlah":"1"}]
</code>```

this is my code

```<code>var data_nama=[];
var data_jumlah=[];

$.post("<?=base_url('Welcome/checkData')?>",
    function(data){
        var obj = JSON.parse(data);
        $.each(obj,function(test,item){
            data_nama.push(item.thn);
            data_jumlah.push(item.jumlah);
        });
</code>```

How to add the same year for example

2018 is must 562 , not 80 , 64

sorry for my bad english ><

答:
Since it tagged with PHP, below is the process:

1.Decode your json data through json_decode()

2.Iterate over this decode array.

3.Add values of jumlah based on thn by creating new array (using thn as index).

4.Re-index array through array_values().

5.Encode new array data through json_encode().

```<code>$array = json_decode($json,true);

$finalArray = array();

foreach($array as $arr){

    $finalArray[$arr['thn']]['jumlah'] = (isset($finalArray[$arr['thn']]['jumlah']) ? $finalArray[$arr['thn']]['jumlah'] + $arr['jumlah']: $arr['jumlah']);
    $finalArray[$arr['thn']]['thn'] = $arr['thn'];
}
$finalArray = array_values($finalArray);
echo json_encode($finalArray);
</code>```

Output: https://3v4l.org/hZWUh

Note:- Do above at PHP end, and no need to change jQuery code. Thanks

Title: How to count a same data in JSON?

Body:
JSON to count:

[{"thn":"2017","jumlah":"30"},{"thn":"2018","jumlah":"80"},{"thn":"2018","jumlah":"64"},{"thn":"2018","jumlah":"5"},{"thn":"2018","jumlah":"1"},{"thn":"2018","jumlah":"1"},{"thn":"2018","jumlah":"4"},{"thn":"2018","jumlah":"5"},{"thn":"2018","jumlah":"198"},{"thn":"2018","jumlah":"2"},{"thn":"2018","jumlah":"202"},{"thn":"2019","jumlah":"31"},{"thn":"2019","jumlah":"1"}]

this is my code

var data_nama=[];
var data_jumlah=[];

$.post("<?=base_url('Welcome/checkData')?>",
    function(data){
        var obj = JSON.parse(data);
        $.each(obj,function(test,item){
            data_nama.push(item.thn);
            data_jumlah.push(item.jumlah);
        });

How to add the same year for example

2018 is must 562 , not 80 , 64

sorry for my bad english ><

Body:
Since it tagged with PHP, below is the process:

1.Decode your json data through json_decode()

2.Iterate over this decode array.

3.Add values of jumlah based on thn by creating new array (using thn as index).

4.Re-index array through array_values().

5.Encode new array data through json_encode().

$array = json_decode($json,true);

$finalArray = array();

foreach($array as $arr){

    $finalArray[$arr['thn']]['jumlah'] = (isset($finalArray[$arr['thn']]['jumlah']) ? $finalArray[$arr['thn']]['jumlah'] + $arr['jumlah']: $arr['jumlah']);
    $finalArray[$arr['thn']]['thn'] = $arr['thn'];
}
$finalArray = array_values($finalArray);
echo json_encode($finalArray);

Output: https://3v4l.org/hZWUh

Note:- Do above at PHP end, and no need to change jQuery code. Thanks


问:
How to Look-up values in Pandas dataframe
I have a dataframe like this.

```<code>Date        Ticker      Price
2019-03-21    AAPL        100
2019-03-21    GOOG        101
2019-03-21    IBM         102
2019-03-25    AAPL         90
2019-03-25    GOOG         91
2019-03-25    IBM          92
2019-03-27    AAPL        110
2019-03-27    GOOG        111
2019-03-27    IBM         112
</code>```

I am trying to add a column called 'LastPrice' which finds the Ticker's last date price. Dates are not consecutive. Thanks.

```<code>Date        Ticker      Price      LastPrice
2019-03-21    AAPL        100
2019-03-21    GOOG        101
2019-03-21    IBM         102
2019-03-25    AAPL         90            100
2019-03-25    GOOG         91            101
2019-03-25    IBM          92            102
2019-03-27    AAPL        110             90
2019-03-27    GOOG        111             91
2019-03-27    IBM         112             92
</code>```

答:
Suppose your data is ordered by date, you can use groupby and shift.</p>

```<code>df['LastPrice'] = (
    df.groupby('Ticker')
    .apply(lambda x: x.Price.shift())
    .reset_index(0, drop=True)
)

    Date        Ticker  Price   LastPrice
0   2019-03-21  AAPL    100     NaN
1   2019-03-21  GOOG    101     NaN
2   2019-03-21  IBM     102     NaN
3   2019-03-25  AAPL    90      100.0
4   2019-03-25  GOOG    91      101.0
5   2019-03-25  IBM     92      102.0
6   2019-03-27  AAPL    110     90.0
7   2019-03-27  GOOG    111     91.0
8   2019-03-27  IBM     112     92.0
</code>```

Body:
I have a dataframe like this.

Date        Ticker      Price
2019-03-21    AAPL        100
2019-03-21    GOOG        101
2019-03-21    IBM         102
2019-03-25    AAPL         90
2019-03-25    GOOG         91
2019-03-25    IBM          92
2019-03-27    AAPL        110
2019-03-27    GOOG        111
2019-03-27    IBM         112

I am trying to add a column called 'LastPrice' which finds the Ticker's last date price. Dates are not consecutive. Thanks.

Date        Ticker      Price      LastPrice
2019-03-21    AAPL        100
2019-03-21    GOOG        101
2019-03-21    IBM         102
2019-03-25    AAPL         90            100
2019-03-25    GOOG         91            101
2019-03-25    IBM          92            102
2019-03-27    AAPL        110             90
2019-03-27    GOOG        111             91
2019-03-27    IBM         112             92

Body:
Suppose your data is ordered by date, you can use groupby and shift.

df['LastPrice'] = (
    df.groupby('Ticker')
    .apply(lambda x: x.Price.shift())
    .reset_index(0, drop=True)
)

    Date        Ticker  Price   LastPrice
0   2019-03-21  AAPL    100     NaN
1   2019-03-21  GOOG    101     NaN
2   2019-03-21  IBM     102     NaN
3   2019-03-25  AAPL    90      100.0
4   2019-03-25  GOOG    91      101.0
5   2019-03-25  IBM     92      102.0
6   2019-03-27  AAPL    110     90.0
7   2019-03-27  GOOG    111     91.0
8   2019-03-27  IBM     112     92.0


问:
Laravel - changing email settings on the fly is not working
All of my email settings for my app are stored in the database.  The user has the option to change those settings, and it all works great.  But I am trying to setup a "Send Test Email" function to allow users to test their settings before saving them.  When they submit the form for to send the test email, the email is sent via the original settings rather than the new settings.

The form is submitted to SettingsController.php

```<code>//  Send a test email
public function sendTestEmail(Request $request)
{
   Log::info(config('mail.host'));
   //  Just to check the current email host - shows the proper host
   //  from the database - i.e. smtp.mailtrap.io

   //  Make sure that all of the information properly validates
   $request->validate([
       'host'       => 'required',
       'port'       => 'required|numeric',
       'encryption' => 'required',
       'username'   => 'required'
   ]);

   //  Temporarily set the email settings
   config([
       'mail.host'       => $request->host,
       'mail.port'       => $request->port,
       'mail.encryption' => $request->encryption,
       'mail.username'   => $request->username,
   ]);
   //  Only update the password if it has been changed
   if(!empty($request->password))
   {
       config(['mail.password' => $request->password]);
   }

   //  Try and send the test email
   try
   {
       Log::info(config('mail.host'));
       //  Just to check the new setting - this also shows the correct
       //  email host - which is the newly assigned one via the form
       //  i.e. smtp.google.com

       Mail::to(Auth::user()->email)->send(new TestEmail());
       return response()->json([
           'success' => true,
           'sentTo'  => Auth::user()->email
       ]);
   }
   catch(Exception $e)
   {
       Log::notice('Test Email Failed.  Message: '.$e);
       $msg = '['.$e->getCode().'] "'.$e->getMessage().'" on line '.
            $e->getTrace()[0]['line'].' of file '.$e->getTrace()[0]['file'];
       return response()->json(['message' => $msg]);
   }
}
</code>```

In my TestEmail class, I have brought it down to the basics

```<code>namespace App\Mail;

//use Illuminate\Bus\Queueable;  //  Commented out to be sure it is not queuing
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
//use Illuminate\Contracts\Queue\ShouldQueue;  //  Commented out to be sure it is not queuing

class TestEmail extends Mailable
{
//    use Queueable, SerializesModels;  //  Commented out to be sure it is not queuing

 /**
 * Create a new message instance.
 *
 * @return void
 */
public function __construct()
{
    //
}

/**
 * Build the message.
 *
 * @return $this
 */
public function build()
{
    return $this->subject('Test Email From '.config('app.name'))->markdown('email.testEmail');
}
}
</code>```

Even though the logs are showing the updated smtp host for the config setting, the message is still being sent out via the original setting - i.e. smtp.mailtrap.io.

答:
TL;DR

An immediate answer to your question, please refer to this following code tested on Laravel 5.8:

```<code>$transport = app('swift.transport');
$smtp = $transport->driver('smpt');
$smpt->setHost('PUT_YOUR_HOST_HERE');
$smpt->setPort('THE_PORT_HERE');
$smpt->setUsername('YOUR_USERNAME_HERE');
$smpt->setPassword('YOUR_PASSWORD_HERE');
$smpt->setEncryption('YOUR_ENCRYPTION_HERE');
</code>```

Why setting up config on the fly does not work?

In laravel architecture, it is first had all the service providers registered and that includes the MailServiceProvider. See your config/app.php

```<code>    // inside config/app.php
    ...
    Illuminate\Mail\MailServiceProvider::class,
    ...
</code>```

And the config will be loaded before it reaches your route, see Illuminate\Mail\TransportManager

```<code>    /**
     * Create an instance of the SMTP Swift Transport driver.
     *
     * @return \Swift_SmtpTransport
     */
    protected function createSmtpDriver()
    {
        $config = $this->app->make('config')->get('mail');

        // The Swift SMTP transport instance will allow us to use any SMTP backend
        // for delivering mail such as Sendgrid, Amazon SES, or a custom server
        // a developer has available. We will just pass this configured host.
        $transport = new SmtpTransport($config['host'], $config['port']);

        if (isset($config['encryption'])) {
            $transport->setEncryption($config['encryption']);
        }
        //... rest of the code
   }
</code>```

so the way I deal with this using TransportManager's drivers method to pick up desired driver and set the config I want, since above code we can see lots of usage of its api.

Hope this helps

Body:
All of my email settings for my app are stored in the database.  The user has the option to change those settings, and it all works great.  But I am trying to setup a "Send Test Email" function to allow users to test their settings before saving them.  When they submit the form for to send the test email, the email is sent via the original settings rather than the new settings.

The form is submitted to SettingsController.php

//  Send a test email
public function sendTestEmail(Request $request)
{
   Log::info(config('mail.host'));
   //  Just to check the current email host - shows the proper host
   //  from the database - i.e. smtp.mailtrap.io

   //  Make sure that all of the information properly validates
   $request->validate([
       'host'       => 'required',
       'port'       => 'required|numeric',
       'encryption' => 'required',
       'username'   => 'required'
   ]);

   //  Temporarily set the email settings
   config([
       'mail.host'       => $request->host,
       'mail.port'       => $request->port,
       'mail.encryption' => $request->encryption,
       'mail.username'   => $request->username,
   ]);
   //  Only update the password if it has been changed
   if(!empty($request->password))
   {
       config(['mail.password' => $request->password]);
   }

   //  Try and send the test email
   try
   {
       Log::info(config('mail.host'));
       //  Just to check the new setting - this also shows the correct
       //  email host - which is the newly assigned one via the form
       //  i.e. smtp.google.com

       Mail::to(Auth::user()->email)->send(new TestEmail());
       return response()->json([
           'success' => true,
           'sentTo'  => Auth::user()->email
       ]);
   }
   catch(Exception $e)
   {
       Log::notice('Test Email Failed.  Message: '.$e);
       $msg = '['.$e->getCode().'] "'.$e->getMessage().'" on line '.
            $e->getTrace()[0]['line'].' of file '.$e->getTrace()[0]['file'];
       return response()->json(['message' => $msg]);
   }
}

In my TestEmail class, I have brought it down to the basics

namespace App\Mail;

//use Illuminate\Bus\Queueable;  //  Commented out to be sure it is not queuing
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
//use Illuminate\Contracts\Queue\ShouldQueue;  //  Commented out to be sure it is not queuing

class TestEmail extends Mailable
{
//    use Queueable, SerializesModels;  //  Commented out to be sure it is not queuing

 /**
 * Create a new message instance.
 *
 * @return void
 */
public function __construct()
{
    //
}

/**
 * Build the message.
 *
 * @return $this
 */
public function build()
{
    return $this->subject('Test Email From '.config('app.name'))->markdown('email.testEmail');
}
}

Even though the logs are showing the updated smtp host for the config setting, the message is still being sent out via the original setting - i.e. smtp.mailtrap.io.

Body:
TL;DR

An immediate answer to your question, please refer to this following code tested on Laravel 5.8:

$transport = app('swift.transport');
$smtp = $transport->driver('smpt');
$smpt->setHost('PUT_YOUR_HOST_HERE');
$smpt->setPort('THE_PORT_HERE');
$smpt->setUsername('YOUR_USERNAME_HERE');
$smpt->setPassword('YOUR_PASSWORD_HERE');
$smpt->setEncryption('YOUR_ENCRYPTION_HERE');

Why setting up config on the fly does not work?

In laravel architecture, it is first had all the service providers registered and that includes the MailServiceProvider. See your config/app.php

    // inside config/app.php
    ...
    Illuminate\Mail\MailServiceProvider::class,
    ...

And the config will be loaded before it reaches your route, see Illuminate\Mail\TransportManager

    /**
     * Create an instance of the SMTP Swift Transport driver.
     *
     * @return \Swift_SmtpTransport
     */
    protected function createSmtpDriver()
    {
        $config = $this->app->make('config')->get('mail');

        // The Swift SMTP transport instance will allow us to use any SMTP backend
        // for delivering mail such as Sendgrid, Amazon SES, or a custom server
        // a developer has available. We will just pass this configured host.
        $transport = new SmtpTransport($config['host'], $config['port']);

        if (isset($config['encryption'])) {
            $transport->setEncryption($config['encryption']);
        }
        //... rest of the code
   }

so the way I deal with this using TransportManager's drivers method to pick up desired driver and set the config I want, since above code we can see lots of usage of its api.

Hope this helps