问:
How do I test if a string is empty in Objective-C?
How do I test if an NSString is empty in Objective-C?

答:
I put this:

```<code>@implementation NSObject (AdditionalMethod)
-(BOOL) isNotEmpty
{
    return !(self == nil
    || [self isKindOfClass:[NSNull class]]
    || ([self respondsToSelector:@selector(length)]
        && [(NSData *)self length] == 0)
    || ([self respondsToSelector:@selector(count)]
        && [(NSArray *)self count] == 0));

};
@end
</code>```

The problem is that if self is nil, this function is never called. It'll return false, which is desired.

Body:
I put this:

@implementation NSObject (AdditionalMethod)
-(BOOL) isNotEmpty
{
    return !(self == nil
    || [self isKindOfClass:[NSNull class]]
    || ([self respondsToSelector:@selector(length)]
        && [(NSData *)self length] == 0)
    || ([self respondsToSelector:@selector(count)]
        && [(NSArray *)self count] == 0));

};
@end

The problem is that if self is nil, this function is never called. It'll return false, which is desired.


来源: stackexchange

问:
Pinescript alert for strategy.exit
I am having  a problem in tradingview, pinescript.

I am stuck at a point, I have converted my strategy into study for alerts. Buy and Sell alerts are converted into alerts but the main problem is, I cannot convert strategy.exit code in study with alert condition. Is there a way I can convert this also in alert?

Below is my code:

```<code>//@version=4
strategy("My Strategy", overlay=true)

strategy.entry("Buy", strategy.long, when=crossover(sma(close, 14), sma(close, 28)), comment="Buy")
strategy.exit("Buy", trail_points=100, loss=100, comment="Exit")

strategy.entry("Sell", strategy.short, when=crossover(sma(close, 14), sma(close, 28)), comment="Sell")
strategy.exit("Sell", trail_points=100, loss=100, comment="Exit")
</code>```

loss = When price comes 100 ticks away from the trigger buy/sell in loss, then exit condition comes. So loss is fixed at 100.

trail_points = When price comes, 100 ticks positive from the buy/sell order, then at the closing of candle, the exit condition comes. Profit is variable at candle close, but trigger at 100.

Can these two exit strategies be given in alert condition? I am not able to convert this whole strategy in alert.

答:
you'll have to keep track of your position and stop losses in variables. (isLong, isShort, stopPrice, etc etc) then update then based on your entry and exit conditions.
for the trailing stop you'll have to update it every candle and check if its hit on every candle.
When you have everything tracked as variables properly, then you can call alertcondition as desired.

maybe this article can help: https://marketscripters.com/pine-script-strategy-vs-study/

ContentLicense: CC BY-SA 4.0

Title: Pinescript alert for strategy.exit

Body:
I am having  a problem in tradingview, pinescript.

I am stuck at a point, I have converted my strategy into study for alerts. Buy and Sell alerts are converted into alerts but the main problem is, I cannot convert strategy.exit code in study with alert condition. Is there a way I can convert this also in alert?

Below is my code:

//@version=4
strategy("My Strategy", overlay=true)

strategy.entry("Buy", strategy.long, when=crossover(sma(close, 14), sma(close, 28)), comment="Buy")
strategy.exit("Buy", trail_points=100, loss=100, comment="Exit")

strategy.entry("Sell", strategy.short, when=crossover(sma(close, 14), sma(close, 28)), comment="Sell")
strategy.exit("Sell", trail_points=100, loss=100, comment="Exit")

loss = When price comes 100 ticks away from the trigger buy/sell in loss, then exit condition comes. So loss is fixed at 100.

trail_points = When price comes, 100 ticks positive from the buy/sell order, then at the closing of candle, the exit condition comes. Profit is variable at candle close, but trigger at 100.

Can these two exit strategies be given in alert condition? I am not able to convert this whole strategy in alert.


问:
Nuxt EventBus - usage for many events
in my Nuxt app I have a Canvas that listens for mouse events. Now I want to send those mouse events to the DOM, everything is working fine. But I'm concerned that there are too many events for Vue, because there is like thousands of them. When I switch to the Vue dev tools, my Computer already begins to stutter. I feel like Vue is only made for simple click events, but I'm using it for a ton. Is there a better way to handle that? </p>

```<code>init(){
    document.addEventListener("mousemove", this.mouseMove.bind(this));
}
mouseMove(e){
    EventBus.$emit("MOUSEMOVE", e);
}
</code>```

答:
It's okay if you need to add certain event listeners here and there. Just make sure you remove them when to component is destroyed, e.g.</p>

```<code>mounted() {
  window.addEventListener('eventName', yourMethod);
},

beforeDestroy() {
  window.removeEventListener('eventName', yourMethod);
}
</code>```

Title: Nuxt EventBus - usage for many events

Body:
in my Nuxt app I have a Canvas that listens for mouse events. Now I want to send those mouse events to the DOM, everything is working fine. But I'm concerned that there are too many events for Vue, because there is like thousands of them. When I switch to the Vue dev tools, my Computer already begins to stutter. I feel like Vue is only made for simple click events, but I'm using it for a ton. Is there a better way to handle that?

init(){
    document.addEventListener("mousemove", this.mouseMove.bind(this));
}
mouseMove(e){
    EventBus.$emit("MOUSEMOVE", e);
}

Body:
It's okay if you need to add certain event listeners here and there. Just make sure you remove them when to component is destroyed, e.g.

mounted() {
  window.addEventListener('eventName', yourMethod);
},

beforeDestroy() {
  window.removeEventListener('eventName', yourMethod);
}


问:
Blazor hosted client - error on published web application on azure app service
When calling the xxxxxxxx.azurewebsites.net, the following appears in the browser console. Can anyone help. Thanks.

```<code>blazor.webassembly.js:1 System.InvalidOperationException: A suitable constructor for type 'Microsoft.Extensions.Logging.LoggerFactory' could not be located. Ensure the type is concrete and services are registered for all parameters of a public constructor.
(anonymous) @ blazor.webassembly.js:1
blazor.webassembly.js:1   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateConstructorCallSite (Microsoft.Extensions.DependencyInjection.ServiceLookup.ResultCache lifetime, System.Type serviceType, System.Type implementationType, Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteChain callSiteChain) <0x1ef0ee0 + 0x00086> in <filename unknown>:0
(anonymous) @ blazor.webassembly.js:1
blazor.webassembly.js:1   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateExact (Microsoft.Extensions.DependencyInjection.ServiceDescriptor descriptor, System.Type serviceType, Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteChain callSiteChain, System.Int32 slot) <0x1ee9cc0 + 0x000f2> in <filename unknown>:0
(anonymous) @ blazor.webassembly.js:1
blazor.webassembly.js:1   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateExact (System.Type serviceType, Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteChain callSiteChain) <0x1ee9878 + 0x00034> in <filename unknown>:0
(anonymous) @ blazor.webassembly.js:1
blazor.webassembly.js:1   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateCallSite (System.Type serviceType, Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteChain callSiteChain) <0x1ee91b0 + 0x0005a> in <filename unknown>:0
(anonymous) @ blazor.webassembly.js:1
blazor.webassembly.js:1   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory+<>c__DisplayClass7_0.<GetCallSite>b__0 (System.Type type) <0x1ee8ce8 + 0x00010> in <filename unknown>:0
(anonymous) @ blazor.webassembly.js:1
blazor.webassembly.js:1   at System.Collections.Concurrent.ConcurrentDictionary`2[TKey,TValue].GetOrAdd (TKey key, System.Func`2[T,TResult] valueFactory) <0x1ed0ea0 + 0x0006c> in <filename unknown>:0
(anonymous) @ blazor.webassembly.js:1
blazor.webassembly.js:1   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.GetCallSite (System.Type serviceType, Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteChain callSiteChain) <0x1ed0d28 + 0x00040> in <filename unknown>:0
(anonymous) @ blazor.webassembly.js:1
blazor.webassembly.js:1   at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.CreateServiceAccessor (System.Type serviceType) <0x1ed0790 + 0x00018> in <filename unknown>:0
(anonymous) @ blazor.webassembly.js:1
blazor.webassembly.js:1   at System.Collections.Concurrent.ConcurrentDictionary`2[TKey,TValue].GetOrAdd (TKey key, System.Func`2[T,TResult] valueFactory) <0x1ed0018 + 0x0006c> in <filename unknown>:0
(anonymous) @ blazor.webassembly.js:1
blazor.webassembly.js:1   at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService (System.Type serviceType, Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope serviceProviderEngineScope) <0x1ecfdd8 + 0x00024> in <filename unknown>:0
(anonymous) @ blazor.webassembly.js:1
blazor.webassembly.js:1   at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService (System.Type serviceType) <0x1ee8c18 + 0x00020> in <filename unknown>:0
(anonymous) @ blazor.webassembly.js:1
blazor.webassembly.js:1   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService (System.IServiceProvider provider, System.Type serviceType) <0x1ecf710 + 0x00062> in <filename unknown>:0
(anonymous) @ blazor.webassembly.js:1
blazor.webassembly.js:1   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T] (System.IServiceProvider provider) <0x1ee8b20 + 0x0001e> in <filename unknown>:0
(anonymous) @ blazor.webassembly.js:1
blazor.webassembly.js:1   at Microsoft.AspNetCore.Components.WebAssembly.Hosting.WebAssemblyHost.RunAsyncCore (System.Threading.CancellationToken cancellationToken) <0x1ee81e0 + 0x0016a> in <filename unknown>:0
(anonymous) @ blazor.webassembly.js:1
blazor.webassembly.js:1   at TakeOut.Client.Program.Main (System.String[] args) <0x1e12b18 + 0x00152> in <filename unknown>:0
(anonymous) @ blazor.webassembly.js:1
blazor.webassembly.js:1   at Microsoft.AspNetCore.Components.WebAssembly.Hosting.EntrypointInvoker.InvokeEntrypoint (System.String assemblyName, System.String[] args, Microsoft.AspNetCore.Components.WebAssembly.Hosting.SatelliteResourcesLoader satelliteResourcesLoader) <0x1d29ea8 + 0x001d6> in <filename unknown>:0
</code>```

The client project:

```<code>    -PropertyGroup-
    -TargetFramework-netstandard2.1-/TargetFramework-
    -RazorLangVersion-3.0-/RazorLangVersion-
    -ServiceWorkerAssetsManifest-service-worker-assets.js-/ServiceWorkerAssetsManifest-
  -/PropertyGroup-

  -ItemGroup-
    -PackageReference Include="Blazored.LocalStorage" Version="2.1.5" /-
    -PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly" Version="3.2.0-preview5.20216.8" /-
    -PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.Build" Version="3.2.0-preview5.20216.8" PrivateAssets="all" /-
    -PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.DevServer" Version="3.2.0-preview5.20216.8" PrivateAssets="all" /-
    -PackageReference Include="Microsoft.AspNetCore.Blazor.HttpClient" Version="3.2.0-preview2.20160.5" /-
    -PackageReference Include="Microsoft.AspNetCore.SignalR.Client" Version="3.1.4" /-
  -/ItemGroup-
  -ItemGroup-
    -ProjectReference Include="..\Shared\TakeOut.Shared.csproj" /-
  -/ItemGroup-

  -!-- When publishing, swap service-worker.published.js in place of service-worker.js ---
  -ItemGroup Condition="'$(DesignTimeBuild)' != 'true'"-
    -Content Remove="wwwroot\service-worker.js" /-
    -Content Update="wwwroot\service-worker.published.js" Link="wwwroot\service-worker.js" /-
  -/ItemGroup-
  -ItemGroup-
    -Folder Include="wwwroot\Images\" /-
  -/ItemGroup-
</Project>
</code>```

The server project:

```<code>-Project Sdk="Microsoft.NET.Sdk.Web"-

  -PropertyGroup-
    -TargetFramework-netcoreapp3.1-/TargetFramework-
    -DisableImplicitComponentsAnalyzers-true-/DisableImplicitComponentsAnalyzers-
  -/PropertyGroup-

  -ItemGroup-
    -PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.Server" Version="3.2.0-preview5.20216.8" /-
    -PackageReference Include="Microsoft.Azure.Cosmos" Version="3.8.0" /-
    -PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="3.1.2" /-
  -/ItemGroup-

  -ItemGroup-
    -ProjectReference Include="..\Client\TakeOut.Client.csproj" /-
    -ProjectReference Include="..\Shared\TakeOut.Shared.csproj" /-
  -/ItemGroup-

-/Project-
</code>```

答:
This looks like a linker issue. Does it work if you disable linking?

```<code><PropertyGroup>
  <BlazorWebAssemblyEnableLinking>false</BlazorWebAssemblyEnableLinking>
</PropertyGroup>
</code>```

Also you are using the older (Microsoft.AspNetCore.Components.WebAssembly" Version="3.2.0-preview5.20216.8") version of WebAssembly.

I would suggest to upgrade to latest version.

```<code><PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly" Version="3.2.0" />
</code>```

You may also try clearing cached files locally.

Body:
When calling the xxxxxxxx.azurewebsites.net, the following appears in the browser console. Can anyone help. Thanks.

blazor.webassembly.js:1 System.InvalidOperationException: A suitable constructor for type 'Microsoft.Extensions.Logging.LoggerFactory' could not be located. Ensure the type is concrete and services are registered for all parameters of a public constructor.
(anonymous) @ blazor.webassembly.js:1
blazor.webassembly.js:1   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateConstructorCallSite (Microsoft.Extensions.DependencyInjection.ServiceLookup.ResultCache lifetime, System.Type serviceType, System.Type implementationType, Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteChain callSiteChain) <0x1ef0ee0 + 0x00086> in <filename unknown>:0
(anonymous) @ blazor.webassembly.js:1
blazor.webassembly.js:1   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateExact (Microsoft.Extensions.DependencyInjection.ServiceDescriptor descriptor, System.Type serviceType, Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteChain callSiteChain, System.Int32 slot) <0x1ee9cc0 + 0x000f2> in <filename unknown>:0
(anonymous) @ blazor.webassembly.js:1
blazor.webassembly.js:1   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateExact (System.Type serviceType, Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteChain callSiteChain) <0x1ee9878 + 0x00034> in <filename unknown>:0
(anonymous) @ blazor.webassembly.js:1
blazor.webassembly.js:1   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateCallSite (System.Type serviceType, Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteChain callSiteChain) <0x1ee91b0 + 0x0005a> in <filename unknown>:0
(anonymous) @ blazor.webassembly.js:1
blazor.webassembly.js:1   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory+<>c__DisplayClass7_0.<GetCallSite>b__0 (System.Type type) <0x1ee8ce8 + 0x00010> in <filename unknown>:0
(anonymous) @ blazor.webassembly.js:1
blazor.webassembly.js:1   at System.Collections.Concurrent.ConcurrentDictionary`2[TKey,TValue].GetOrAdd (TKey key, System.Func`2[T,TResult] valueFactory) <0x1ed0ea0 + 0x0006c> in <filename unknown>:0
(anonymous) @ blazor.webassembly.js:1
blazor.webassembly.js:1   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.GetCallSite (System.Type serviceType, Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteChain callSiteChain) <0x1ed0d28 + 0x00040> in <filename unknown>:0
(anonymous) @ blazor.webassembly.js:1
blazor.webassembly.js:1   at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.CreateServiceAccessor (System.Type serviceType) <0x1ed0790 + 0x00018> in <filename unknown>:0
(anonymous) @ blazor.webassembly.js:1
blazor.webassembly.js:1   at System.Collections.Concurrent.ConcurrentDictionary`2[TKey,TValue].GetOrAdd (TKey key, System.Func`2[T,TResult] valueFactory) <0x1ed0018 + 0x0006c> in <filename unknown>:0
(anonymous) @ blazor.webassembly.js:1
blazor.webassembly.js:1   at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService (System.Type serviceType, Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope serviceProviderEngineScope) <0x1ecfdd8 + 0x00024> in <filename unknown>:0
(anonymous) @ blazor.webassembly.js:1
blazor.webassembly.js:1   at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService (System.Type serviceType) <0x1ee8c18 + 0x00020> in <filename unknown>:0
(anonymous) @ blazor.webassembly.js:1
blazor.webassembly.js:1   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService (System.IServiceProvider provider, System.Type serviceType) <0x1ecf710 + 0x00062> in <filename unknown>:0
(anonymous) @ blazor.webassembly.js:1
blazor.webassembly.js:1   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T] (System.IServiceProvider provider) <0x1ee8b20 + 0x0001e> in <filename unknown>:0
(anonymous) @ blazor.webassembly.js:1
blazor.webassembly.js:1   at Microsoft.AspNetCore.Components.WebAssembly.Hosting.WebAssemblyHost.RunAsyncCore (System.Threading.CancellationToken cancellationToken) <0x1ee81e0 + 0x0016a> in <filename unknown>:0
(anonymous) @ blazor.webassembly.js:1
blazor.webassembly.js:1   at TakeOut.Client.Program.Main (System.String[] args) <0x1e12b18 + 0x00152> in <filename unknown>:0
(anonymous) @ blazor.webassembly.js:1
blazor.webassembly.js:1   at Microsoft.AspNetCore.Components.WebAssembly.Hosting.EntrypointInvoker.InvokeEntrypoint (System.String assemblyName, System.String[] args, Microsoft.AspNetCore.Components.WebAssembly.Hosting.SatelliteResourcesLoader satelliteResourcesLoader) <0x1d29ea8 + 0x001d6> in <filename unknown>:0

The client project:

    -PropertyGroup-
    -TargetFramework-netstandard2.1-/TargetFramework-
    -RazorLangVersion-3.0-/RazorLangVersion-
    -ServiceWorkerAssetsManifest-service-worker-assets.js-/ServiceWorkerAssetsManifest-
  -/PropertyGroup-

  -ItemGroup-
    -PackageReference Include="Blazored.LocalStorage" Version="2.1.5" /-
    -PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly" Version="3.2.0-preview5.20216.8" /-
    -PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.Build" Version="3.2.0-preview5.20216.8" PrivateAssets="all" /-
    -PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.DevServer" Version="3.2.0-preview5.20216.8" PrivateAssets="all" /-
    -PackageReference Include="Microsoft.AspNetCore.Blazor.HttpClient" Version="3.2.0-preview2.20160.5" /-
    -PackageReference Include="Microsoft.AspNetCore.SignalR.Client" Version="3.1.4" /-
  -/ItemGroup-
  -ItemGroup-
    -ProjectReference Include="..\Shared\TakeOut.Shared.csproj" /-
  -/ItemGroup-

  -!-- When publishing, swap service-worker.published.js in place of service-worker.js ---
  -ItemGroup Condition="'$(DesignTimeBuild)' != 'true'"-
    -Content Remove="wwwroot\service-worker.js" /-
    -Content Update="wwwroot\service-worker.published.js" Link="wwwroot\service-worker.js" /-
  -/ItemGroup-
  -ItemGroup-
    -Folder Include="wwwroot\Images\" /-
  -/ItemGroup-
</Project>

The server project:

-Project Sdk="Microsoft.NET.Sdk.Web"-

  -PropertyGroup-
    -TargetFramework-netcoreapp3.1-/TargetFramework-
    -DisableImplicitComponentsAnalyzers-true-/DisableImplicitComponentsAnalyzers-
  -/PropertyGroup-

  -ItemGroup-
    -PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.Server" Version="3.2.0-preview5.20216.8" /-
    -PackageReference Include="Microsoft.Azure.Cosmos" Version="3.8.0" /-
    -PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="3.1.2" /-
  -/ItemGroup-

  -ItemGroup-
    -ProjectReference Include="..\Client\TakeOut.Client.csproj" /-
    -ProjectReference Include="..\Shared\TakeOut.Shared.csproj" /-
  -/ItemGroup-

-/Project-

Body:
This looks like a linker issue. Does it work if you disable linking?

<PropertyGroup>
  <BlazorWebAssemblyEnableLinking>false</BlazorWebAssemblyEnableLinking>
</PropertyGroup>

Also you are using the older (Microsoft.AspNetCore.Components.WebAssembly" Version="3.2.0-preview5.20216.8") version of WebAssembly.

I would suggest to upgrade to latest version.

<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly" Version="3.2.0" />

You may also try clearing cached files locally.


问:
continue for loop inside internal function
I'd like to do the following:

```<code>for line in lines:
   handle(line)
   if cond:
      handle_lines_cond() # will handle multiple lines. for loop will continue where handle_cond() left off
</code>```

I need to do this with a decent performance, if possible

答:
To do this it will be better to use while: </p>

```<code>i = 0
while i < len(lines):
    handle(lines[i])
    if cond:
      i = handle_lines_cond()  # where handle_lines_cond returns the last line index which was processed
    else:
      i = i + 1
</code>```

Body:
I'd like to do the following:

for line in lines:
   handle(line)
   if cond:
      handle_lines_cond() # will handle multiple lines. for loop will continue where handle_cond() left off

I need to do this with a decent performance, if possible

Body:
To do this it will be better to use while:

i = 0
while i < len(lines):
    handle(lines[i])
    if cond:
      i = handle_lines_cond()  # where handle_lines_cond returns the last line index which was processed
    else:
      i = i + 1


问:
How can I run Tensorboard on a remote server?
I'm new to Tensorflow and would greatly benefit from some visualizations of what I'm doing. I understand that Tensorboard is a useful visualization tool, but how do I run it on my remote Ubuntu machine?</p>

答:
--bind_all option is useful.

```<code>$ tensorboard --logdir runs --bind_all
</code>```

The port will be automatically selected from 6006 incrementally.(6006, 6007, 6008... )

ContentLicense: CC BY-SA 3.0

Body:
--bind_all option is useful.

$ tensorboard --logdir runs --bind_all

The port will be automatically selected from 6006 incrementally.(6006, 6007, 6008... )


问:
Split pandas column with list of item and values, into separate columns with item as column header
I have a column in a pandas DataFrame that looks like the below:

```<code>[Apple X 1, Orange X 2, Watermelon X 1, Pineapple X 3]
</code>```

There are 100k+ rows, and it represents things our customers have ordered.

I'd like to go through this column and split these into separate columns so that the items become column names and the number becomes the value, for that particular row.

E.g

```<code>Apple   Orange   Watermelon   Pineapple
    1       2        1            3
</code>```

答:
IIUC, you can we can use split and set_index, then T, for transpose:

```<code>import pandas as pd
s = pd.Series(['Apple X 1', 'Orange X 2', 'Watermelon X 1', 'Pineapple X 3'])
s.str.split(' ', expand=True).set_index(0).T.drop(1)
</code>```

Output:

```<code>0 Apple Orange Watermelon Pineapple
2     1      2          1         3
</code>```

Body:
I have a column in a pandas DataFrame that looks like the below:

[Apple X 1, Orange X 2, Watermelon X 1, Pineapple X 3]

There are 100k+ rows, and it represents things our customers have ordered.

I'd like to go through this column and split these into separate columns so that the items become column names and the number becomes the value, for that particular row.

E.g

Apple   Orange   Watermelon   Pineapple
    1       2        1            3

Body:
IIUC, you can we can use split and set_index, then T, for transpose:

import pandas as pd
s = pd.Series(['Apple X 1', 'Orange X 2', 'Watermelon X 1', 'Pineapple X 3'])
s.str.split(' ', expand=True).set_index(0).T.drop(1)

Output:

0 Apple Orange Watermelon Pineapple
2     1      2          1         3


问:
For a large project, what planning should be done before coding and how should it be approached?
What is your method of "mapping out" an idea before creating it?

Say I wanted to take on a big project, for example at the scale of a site like Facebook or MySpace.  What planning/design steps should I take before I start the actual work?

For example, should I map everything out page by page (their functionalities, data, etc.)?

答:
Make a list of all the features that site have.

Make a list of nice to have features.

Make a list of the weakness of the site.

Order that list and prioritize the items that will be built first.

Identify what will be possible to do and what is not.

Meet with your customer and present these results.

OwnerDisplayName: sarmenhb

LastEditorDisplayName: Hanno Fietz

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Oscar Reyes


问:
Tag Position in Org Mode
When I create a tag next to a heading it aligns and moves to the right but not as far as I'd like.

How can I make sure the tags are aligned further away from the heading?

Thanks.

答:
In Emacs 23.3.1 (Org-mode version 6.33x), tags for a heading are right-aligned in accordance with the org-tags-column variable.

You can use M-x customize-variable RET org-tags-column RET to change this to suit your requirements.

Title: Tag Position in Org Mode


问:
RealmSwift: Count number of unique words
Given the following setup:

```<code>class Message: Object {

    @objc dynamic var name: String = ""
    @objc dynamic var message: String = ""
}

class Chat: Object {

    var messages = List<Message>()
    var people = List<Person>()

    @objc dynamic var name:String = ""
    @objc dynamic var path:String = ""
}
</code>```

Is there a more efficient way using functional programming to calculate teh number of unique words within the message variable within Message?

```<code>let messages = Array(chat.messages)
let wordDictionary = [String:Int]()
let peopleDictionary = [String]()

for messageObject in messages {

   let words = messageObject.message.components(separatedBy: " ")
   for word in words {
      if wordDictionary[word] != nil {
          wordDictionary[word] += 1
      }else{
         wordDictionary[word] = 0
      }
   }
}
</code>```

答:
You asked for functional programming and you're using .componentsSeparatedBy(" ") so the assumption is that all the words have space between them.

Lets use the power of a .map, .flatmap and a Set, which are guaranteed to be unique elements. For example:

```<code>let sentence = "Every good boy does fine does" //6 total words, 5 unique
let words = sentence.components(separatedBy: " ")
let wordSet = Set(words)
print(wordSet.count)
</code>```

output is

```<code>5
</code>```

So then applying that to the question:

```<code>let messages = Array(chat.messages) //makes the Realm list a Swift Array
let x = messages.map { msgString -> [String] in
    let y = msgString.message.components(separatedBy: " ")
    return y
}
let uniqueWords = Set( x.flatMap { $0 } )
print(uniqueWords.count)
</code>```

The map function will take each message in the array of messages and break it down into an array of array strings so it looks like this

```<code>[ [word0, word1, word2], [word3, word4, word5] ]
</code>```

Then the flatMap maps the array of arrays into a single array of words

Finally Set takes all of the words and creates a set of unique words.

Body:
Given the following setup:

class Message: Object {

    @objc dynamic var name: String = ""
    @objc dynamic var message: String = ""
}

class Chat: Object {

    var messages = List<Message>()
    var people = List<Person>()

    @objc dynamic var name:String = ""
    @objc dynamic var path:String = ""
}

Is there a more efficient way using functional programming to calculate teh number of unique words within the message variable within Message?

let messages = Array(chat.messages)
let wordDictionary = [String:Int]()
let peopleDictionary = [String]()

for messageObject in messages {

   let words = messageObject.message.components(separatedBy: " ")
   for word in words {
      if wordDictionary[word] != nil {
          wordDictionary[word] += 1
      }else{
         wordDictionary[word] = 0
      }
   }
}

Body:
You asked for functional programming and you're using .componentsSeparatedBy(" ") so the assumption is that all the words have space between them.

Lets use the power of a .map, .flatmap and a Set, which are guaranteed to be unique elements. For example:

let sentence = "Every good boy does fine does" //6 total words, 5 unique
let words = sentence.components(separatedBy: " ")
let wordSet = Set(words)
print(wordSet.count)

output is

5

So then applying that to the question:

let messages = Array(chat.messages) //makes the Realm list a Swift Array
let x = messages.map { msgString -> [String] in
    let y = msgString.message.components(separatedBy: " ")
    return y
}
let uniqueWords = Set( x.flatMap { $0 } )
print(uniqueWords.count)

The map function will take each message in the array of messages and break it down into an array of array strings so it looks like this

[ [word0, word1, word2], [word3, word4, word5] ]

Then the flatMap maps the array of arrays into a single array of words

Finally Set takes all of the words and creates a set of unique words.


问:
Swiftui - only show a percentage of a view
I have a RoundedRectangle, and my objective is to lay another RoundedRectangle over it such that the overlay shows a "percentage complete". I can't seem to find the proper incantation to do so, though.

I think that ideally, the overlay should somehow only show a percentage of itself. Resizing itself to match the percentage skews the shape of the overlay.

```<code>import PlaygroundSupport

struct ContentView: View {

    @State private var value: Double = 0

    var body: some View {
        GeometryReader { geom in
            VStack {
                Slider(value: self.$value, in: 0...1, step: 0.01)

                ZStack {
                    ZStack(alignment: .leading) {

                        // The main rectangle
                        RoundedRectangle(cornerRadius: 10)
                            .fill(Color.blue)
                            .frame(width: geom.size.width,
                                   height: 200)

                        // The progress indicator...
                        RoundedRectangle(cornerRadius: 10)
                            .fill(Color.red)
                            .opacity(0.5)
                            .frame(width: CGFloat(self.value) * geom.size.width,
                                   height: 200)
                    }

                    Text("\(Int(self.value * 100)) %")
                }
            }
        }
        .padding()
    }
}

PlaygroundPage.current.setLiveView(ContentView())
</code>```

In the above playground, if you look at 1, 2, or even 3 %, you can see that the red overlay is out of the blue background rectangle bounds in the upper and lower left. See image below.

I feel like this is not the proper solution, but I also couldn't find the right mix of things (trying scaleEffect, a bunch of offset and position math) to really nail it.

To me, like I said above, it feels like the overlay should be able to say "only make my left-most 40% visible" when the value is 0.4.

That was long-winded, I apologize for that. If you've read this far, and have any advice to impart, I'd be incredibly appreciative.

Thanks!

答:
This how I approach it so I don't have to manage more than one cornerRadius.

```<code>VStack {
    ZStack(alignment: .leading) {

        // The main rectangle
        Rectangle()
            .fill(Color.blue)
            .frame(width: geom.size.width,
                   height: 200)

        // The progress indicator...
        Rectangle()
            .fill(Color.red)
            .opacity(0.5)
            .frame(width: CGFloat(self.value) * geom.size.width,
                   height: 200)
    }
    .cornerRadius(10)
</code>```

Body:
I have a RoundedRectangle, and my objective is to lay another RoundedRectangle over it such that the overlay shows a "percentage complete". I can't seem to find the proper incantation to do so, though.

I think that ideally, the overlay should somehow only show a percentage of itself. Resizing itself to match the percentage skews the shape of the overlay.

import PlaygroundSupport

struct ContentView: View {

    @State private var value: Double = 0

    var body: some View {
        GeometryReader { geom in
            VStack {
                Slider(value: self.$value, in: 0...1, step: 0.01)

                ZStack {
                    ZStack(alignment: .leading) {

                        // The main rectangle
                        RoundedRectangle(cornerRadius: 10)
                            .fill(Color.blue)
                            .frame(width: geom.size.width,
                                   height: 200)

                        // The progress indicator...
                        RoundedRectangle(cornerRadius: 10)
                            .fill(Color.red)
                            .opacity(0.5)
                            .frame(width: CGFloat(self.value) * geom.size.width,
                                   height: 200)
                    }

                    Text("\(Int(self.value * 100)) %")
                }
            }
        }
        .padding()
    }
}

PlaygroundPage.current.setLiveView(ContentView())

In the above playground, if you look at 1, 2, or even 3 %, you can see that the red overlay is out of the blue background rectangle bounds in the upper and lower left. See image below.

I feel like this is not the proper solution, but I also couldn't find the right mix of things (trying scaleEffect, a bunch of offset and position math) to really nail it.

To me, like I said above, it feels like the overlay should be able to say "only make my left-most 40% visible" when the value is 0.4.

That was long-winded, I apologize for that. If you've read this far, and have any advice to impart, I'd be incredibly appreciative.

Thanks!

Body:
This how I approach it so I don't have to manage more than one cornerRadius.

VStack {
    ZStack(alignment: .leading) {

        // The main rectangle
        Rectangle()
            .fill(Color.blue)
            .frame(width: geom.size.width,
                   height: 200)

        // The progress indicator...
        Rectangle()
            .fill(Color.red)
            .opacity(0.5)
            .frame(width: CGFloat(self.value) * geom.size.width,
                   height: 200)
    }
    .cornerRadius(10)


问:
Mac can't find chromedriver when running python script from launchctl
I've been trying to schedule one of my python scripts through launchctl and am coming up against an error. The intention is that this runs at a given time past the hour, every hour.

I've created my plist, loaded it in launchctl but it's not working properly. After doing some digging I debugged and got the following error messages:
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/selenium/webdriver/common/service.py", line 72, in start
    self.process = subprocess.Popen(cmd, env=self.env,
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/subprocess.py", line 854, in init
    self._execute_child(args, executable, preexec_fn, close_fds,
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/subprocess.py", line 1702, in _execute_child
    raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: 'chromedriver'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/petersmith/Documents/Python/thenewsproject/link_getters/link_getter.py", line 3, in
    import myfile
  File "/Users/directories/myfile.py", line 51, in
    browser = webdriver.Chrome('chromedriver', options=chrome_options)

  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/selenium/webdriver/chrome/webdriver.py", line 73, in init
    self.service.start()
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/selenium/webdriver/common/service.py", line 81, in start
    raise WebDriverException(
selenium.common.exceptions.WebDriverException: Message: 'chromedriver' executable needs to be in PATH. Please see https://sites.google.com/a/chromium.org/chromedriver/home

I've updated the items in bold when pasting.

This is the line that it's fussing about:
browser = webdriver.Chrome('chromedriver', options=chrome_options)

Now, chromedriver lives in my usr/local/bin folder and I've checked my path file and see:
-bash: /Library/Frameworks/Python.framework/Versions/3.8/bin:/usr/local/mysql/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/share/dotnet:~/.dotnet/tools:/Library/Frameworks/Mono.framework/Versions/Current/Commands:/Applications/Xamarin: No such file or directory

You can see in bold that it's there so I'm a little lost.

Any ideas?

答:
OK - so after a huge amount of searching I finally figured this out. There were actually two things causing me a problem when getting this working and they both related to the way that launchctl executes the work on behalf of the user.

The key things to remember are that launchctl will execute a process on your behalf and that means:

It has it’s own PATH variable (which you need to update with your chromedriver location), and

It executes your script from it’s own working directory, rather than the one your python script lives in. This will give you an issue for any other files you want to include or relative paths you use in your script(s)

To amend launchctl’s path you therefore need to run the following command from the terminal:

```<code>launchctl setenv PATH /usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin
</code>```

Can’t remember if you then needed a restart or not but definitely unload and then reload your plist file

```<code>launchctl load ~Library/LaunchAgents/your.own.plist
</code>```

You should then be good to go.

Fixing the second point is then a simple key-string pair to add yo your plist file

```<code><key>WorkingDirectory</key>
<string>/Users/you/path/to/mypythonfile/</string>
</code>```

Hope this is helpful for others!

Body:
OK - so after a huge amount of searching I finally figured this out. There were actually two things causing me a problem when getting this working and they both related to the way that launchctl executes the work on behalf of the user.

The key things to remember are that launchctl will execute a process on your behalf and that means:

It has it’s own PATH variable (which you need to update with your chromedriver location), and

It executes your script from it’s own working directory, rather than the one your python script lives in. This will give you an issue for any other files you want to include or relative paths you use in your script(s)

To amend launchctl’s path you therefore need to run the following command from the terminal:

launchctl setenv PATH /usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin

Can’t remember if you then needed a restart or not but definitely unload and then reload your plist file

launchctl load ~Library/LaunchAgents/your.own.plist

You should then be good to go.

Fixing the second point is then a simple key-string pair to add yo your plist file

<key>WorkingDirectory</key>
<string>/Users/you/path/to/mypythonfile/</string>

Hope this is helpful for others!


问:
database timeout error resolution problem
Hi I am having some problems in my app for the database timeout. Due to some network glitches the query takes more than 45 sec to return the resultset which has about 10,000 rows. Most of the time its fast upto 11-12 secs. My app is runs as a scheduled job in the background.

The problem is I need to try three times if i get the timeout exception before writing the error to the error log or exiting. I know i can set the command timeout property to 60 seconds but still i want to try three times before exiting. I have written a method for that but I think there is some flaw in my method.

For now i specifically set the timeout to be 5 seconds as i know well that it takes more than 25 seconds for this stored proc to run. I just want to get that timeout expired exception and write ways to handle it.

My problem is if after 2 times I set the connection timeout to 50 so my method goes and get the correct list but it again goes inside the methodname which i have called inside the catch statement and finally returns nothing. It looks like its getting into recursion or something but i am confused as to where i am wrong.

Any hints or pointers will be helpful in clarifying my concept.

```<code>Private Shared timeoutcounter As Integer = 0
Private Shared dbConnectionString As String = ConfigurationManager.AppSettings("DBConn")

Public Shared Function GetPurgeList() As DestList

    Dim AcInfo As DestInfo = Nothing
    Dim tempList As DestList= Nothing
    Dim ConnectionString As String = dbConnectionString
    Dim cn As New SqlConnection(ConnectionString)
    Dim cmd As SqlCommand = Nothing
    Dim dr As SqlDataReader = Nothing

    Try
        cn.Open()
        cmd = New SqlCommand
        With cmd
            .Connection = cn
            .CommandType = CommandType.StoredProcedure
            .CommandText = "usp_abcd"
            .CommandTimeout = 5
            dr = .ExecuteReader
            If dr.HasRows Then
                tempList = New DestList()
                While dr.Read()
                    If dr.GetName(0).ToString() = "errnum" Then
                        ErrorLogger.WriteToErrorLog("Error from stored proc usp_abcd" + CStr(dr("errnum")), dr("errmsg"))
                    Else
                        AcInfo = New DestInfo
...
//fill object
...
                           tempList.Add(AccountInfo)
                    End If
                End While
            End If
        End With

    Catch ex As Exception
       If ex.Message.ToUpper.Contains("Timeout Expired".ToUpper) Then
            timeoutcounter = timeoutcounter + 1
            If timeoutcounter > 2 Then
                timeoutcounter = 0
                ErrorLogger.WriteToErrorLog("Exception from method GetPurgeList timeoutCounter > 3 : " + ex.Message, ex.StackTrace)
            Else
------------>  GetPurgeList() 'it gets here after getting the correct list and I am confused why does it come back here again and then finally return nothing
            End If
        Else
            ErrorLogger.WriteToErrorLog("Exception from method GetPurgeList : " + ex.Message, ex.StackTrace)

        End If

    Finally
        If dr IsNot Nothing Then
            dr.Close()
            dr = Nothing
        End If
        If cmd IsNot Nothing Then
            cmd.Dispose()
            cmd = Nothing
        End If
        If cn IsNot Nothing Then
            cn.Close()
            cn.Dispose()
            cn = Nothing
        End If
    End Try
    Return tempList
End Function
</code>```

答:
You aren't saving the return value of GetPurgeList when called from the exception.  My suggestion would be to drop the recursion entirely.  Create a loop and extract the datareader portion into it's own function and simply call that when the sproc succeeds.

What I am showing below is NOT what I recommend, but rather intended to show the general FLOW.  I'm not sure if it will work without reopening the connection.  If I was doing this for myself, I'd put just about everything in the GetPurgeList into a loop that terminated after X iteration or tempList is not Nothing (it would actually be easier to write it that way, but I hope this makes the IDEA clearer).

```<code>Private Shared timeoutcounter As Integer = 0
Private Shared dbConnectionString As String = ConfigurationManager.AppSettings("DBConn")

Private Shared Sub ReadFromDataReader(ByVal dr as DataReader, ByRef tempList as DestList)
        If dr IsNot Nothing AndAlso dr.HasRows Then
            tempList = New DestList()
            While dr.Read()
                Dim AcInfo As DestInfo = Nothing
                If dr.GetName(0).ToString() = "errnum" Then
                    ErrorLogger.WriteToErrorLog("Error from stored proc usp_abcd" + CStr(dr("errnum")), dr("errmsg"))
                Else
                    AcInfo = New DestInfo
...
//fill object
...
                       tempList.Add(AccountInfo)
                End If
            End While
        End If

End Sub

Public Shared Function GetPurgeList() As DestList

Dim tempList As DestList= Nothing
Dim ConnectionString As String = dbConnectionString
Dim cn As New SqlConnection(ConnectionString)
Dim cmd As SqlCommand = Nothing
Dim dr As SqlDataReader = Nothing

try
   cn.Open()
    cmd = New SqlCommand
    With cmd
        .Connection = cn
        .CommandType = CommandType.StoredProcedure
        .CommandText = "usp_abcd"
    End With
Catch ex as exception
  return Nothing ' possibly rethrow error here instead, in any case, do not continue
End Try

Try
        cmd.CommandTimeout = 5
        dr = cmd.ExecuteReader
        ReadFromDataReader(dr, tempList)

Catch ex As Exception
   If ex.Message.ToUpper.Contains("Timeout Expired".ToUpper) Then
        try
           cmd.CommandTimeout = 15
           dr = cmd.ExecuteReader
           ReadFromDataReader(dr, tempList)
        Catch ex1 as Exception
           If ex.Message.ToUpper.Contains("Timeout Expired".ToUpper) Then
              Try
                cmd.CommandTimeout =25
                dr = cmd.ExecuteReader
                ReadFromDataReader(dr, tempList)

              Catch ex As Exception
                ErrorLogger.WriteToErrorLog("Exception from method GetPurgeList : " + ex.Message, ex.StackTrace)

          End Try
          Else
            ErrorLogger.WriteToErrorLog("Exception from method GetPurgeList : " + ex.Message, ex.StackTrace)

          End If
        End Try
    End If

Finally
    If dr IsNot Nothing Then
        dr.Close()
        dr = Nothing
    End If
    If cmd IsNot Nothing Then
        cmd.Dispose()
        cmd = Nothing
    End If
    If cn IsNot Nothing Then
        cn.Close()
        cn.Dispose()
        cn = Nothing
    End If
End Try
Return tempList
End Function
</code>```

Body:
Hi I am having some problems in my app for the database timeout. Due to some network glitches the query takes more than 45 sec to return the resultset which has about 10,000 rows. Most of the time its fast upto 11-12 secs. My app is runs as a scheduled job in the background.

The problem is I need to try three times if i get the timeout exception before writing the error to the error log or exiting. I know i can set the command timeout property to 60 seconds but still i want to try three times before exiting. I have written a method for that but I think there is some flaw in my method.

For now i specifically set the timeout to be 5 seconds as i know well that it takes more than 25 seconds for this stored proc to run. I just want to get that timeout expired exception and write ways to handle it.

My problem is if after 2 times I set the connection timeout to 50 so my method goes and get the correct list but it again goes inside the methodname which i have called inside the catch statement and finally returns nothing. It looks like its getting into recursion or something but i am confused as to where i am wrong.

Any hints or pointers will be helpful in clarifying my concept.

Private Shared timeoutcounter As Integer = 0
Private Shared dbConnectionString As String = ConfigurationManager.AppSettings("DBConn")

Public Shared Function GetPurgeList() As DestList

    Dim AcInfo As DestInfo = Nothing
    Dim tempList As DestList= Nothing
    Dim ConnectionString As String = dbConnectionString
    Dim cn As New SqlConnection(ConnectionString)
    Dim cmd As SqlCommand = Nothing
    Dim dr As SqlDataReader = Nothing

    Try
        cn.Open()
        cmd = New SqlCommand
        With cmd
            .Connection = cn
            .CommandType = CommandType.StoredProcedure
            .CommandText = "usp_abcd"
            .CommandTimeout = 5
            dr = .ExecuteReader
            If dr.HasRows Then
                tempList = New DestList()
                While dr.Read()
                    If dr.GetName(0).ToString() = "errnum" Then
                        ErrorLogger.WriteToErrorLog("Error from stored proc usp_abcd" + CStr(dr("errnum")), dr("errmsg"))
                    Else
                        AcInfo = New DestInfo
...
//fill object
...
                           tempList.Add(AccountInfo)
                    End If
                End While
            End If
        End With

    Catch ex As Exception
       If ex.Message.ToUpper.Contains("Timeout Expired".ToUpper) Then
            timeoutcounter = timeoutcounter + 1
            If timeoutcounter > 2 Then
                timeoutcounter = 0
                ErrorLogger.WriteToErrorLog("Exception from method GetPurgeList timeoutCounter > 3 : " + ex.Message, ex.StackTrace)
            Else
------------>  GetPurgeList() 'it gets here after getting the correct list and I am confused why does it come back here again and then finally return nothing
            End If
        Else
            ErrorLogger.WriteToErrorLog("Exception from method GetPurgeList : " + ex.Message, ex.StackTrace)

        End If

    Finally
        If dr IsNot Nothing Then
            dr.Close()
            dr = Nothing
        End If
        If cmd IsNot Nothing Then
            cmd.Dispose()
            cmd = Nothing
        End If
        If cn IsNot Nothing Then
            cn.Close()
            cn.Dispose()
            cn = Nothing
        End If
    End Try
    Return tempList
End Function

Body:
You aren't saving the return value of GetPurgeList when called from the exception.  My suggestion would be to drop the recursion entirely.  Create a loop and extract the datareader portion into it's own function and simply call that when the sproc succeeds.

What I am showing below is NOT what I recommend, but rather intended to show the general FLOW.  I'm not sure if it will work without reopening the connection.  If I was doing this for myself, I'd put just about everything in the GetPurgeList into a loop that terminated after X iteration or tempList is not Nothing (it would actually be easier to write it that way, but I hope this makes the IDEA clearer).

Private Shared timeoutcounter As Integer = 0
Private Shared dbConnectionString As String = ConfigurationManager.AppSettings("DBConn")

Private Shared Sub ReadFromDataReader(ByVal dr as DataReader, ByRef tempList as DestList)
        If dr IsNot Nothing AndAlso dr.HasRows Then
            tempList = New DestList()
            While dr.Read()
                Dim AcInfo As DestInfo = Nothing
                If dr.GetName(0).ToString() = "errnum" Then
                    ErrorLogger.WriteToErrorLog("Error from stored proc usp_abcd" + CStr(dr("errnum")), dr("errmsg"))
                Else
                    AcInfo = New DestInfo
...
//fill object
...
                       tempList.Add(AccountInfo)
                End If
            End While
        End If

End Sub

Public Shared Function GetPurgeList() As DestList

Dim tempList As DestList= Nothing
Dim ConnectionString As String = dbConnectionString
Dim cn As New SqlConnection(ConnectionString)
Dim cmd As SqlCommand = Nothing
Dim dr As SqlDataReader = Nothing

try
   cn.Open()
    cmd = New SqlCommand
    With cmd
        .Connection = cn
        .CommandType = CommandType.StoredProcedure
        .CommandText = "usp_abcd"
    End With
Catch ex as exception
  return Nothing ' possibly rethrow error here instead, in any case, do not continue
End Try

Try
        cmd.CommandTimeout = 5
        dr = cmd.ExecuteReader
        ReadFromDataReader(dr, tempList)

Catch ex As Exception
   If ex.Message.ToUpper.Contains("Timeout Expired".ToUpper) Then
        try
           cmd.CommandTimeout = 15
           dr = cmd.ExecuteReader
           ReadFromDataReader(dr, tempList)
        Catch ex1 as Exception
           If ex.Message.ToUpper.Contains("Timeout Expired".ToUpper) Then
              Try
                cmd.CommandTimeout =25
                dr = cmd.ExecuteReader
                ReadFromDataReader(dr, tempList)

              Catch ex As Exception
                ErrorLogger.WriteToErrorLog("Exception from method GetPurgeList : " + ex.Message, ex.StackTrace)

          End Try
          Else
            ErrorLogger.WriteToErrorLog("Exception from method GetPurgeList : " + ex.Message, ex.StackTrace)

          End If
        End Try
    End If

Finally
    If dr IsNot Nothing Then
        dr.Close()
        dr = Nothing
    End If
    If cmd IsNot Nothing Then
        cmd.Dispose()
        cmd = Nothing
    End If
    If cn IsNot Nothing Then
        cn.Close()
        cn.Dispose()
        cn = Nothing
    End If
End Try
Return tempList
End Function


问:
google AI platform read history on local
After training model i would like to save history in mine bucket or any location which i can access later on local

when i run code below on google colab all work fine

```<code>history = model.fit(training_dataset, steps_per_epoch=steps_per_epoch, epochs=EPOCHS,
                validation_data=validation_dataset, validation_steps=validation_steps)
#model.summary()
model.save(BUCKET)
#save as pickle
with open('/trainHistoryDict', 'wb') as file_pi:
      pickle.dump(history.history, file_pi)
</code>```

I can read later using

```<code>history = pickle.load(open('/trainHistoryDict', "rb"))
</code>```

however when run code as a job on  google cloud AI-Platform ( using %%wrotefile) I cannot retrieve history on google colab using pickle load   - im getting 'no such directory'
So how i can run training on AI platform on google cloud and then access history on google colab?
Can i save history.history in bucket ? i tried to use PACKAGE_STAGING_PATH but it didnt worked

答:
found solution</p>

```<code>subprocess.Popen('gsutil cp history gs://bigdatapart2-storage/history1', shell=True, stdout=subprocess.PIPE)
</code>```

Body:
After training model i would like to save history in mine bucket or any location which i can access later on local

when i run code below on google colab all work fine

history = model.fit(training_dataset, steps_per_epoch=steps_per_epoch, epochs=EPOCHS,
                validation_data=validation_dataset, validation_steps=validation_steps)
#model.summary()
model.save(BUCKET)
#save as pickle
with open('/trainHistoryDict', 'wb') as file_pi:
      pickle.dump(history.history, file_pi)

I can read later using

history = pickle.load(open('/trainHistoryDict', "rb"))

however when run code as a job on  google cloud AI-Platform ( using %%wrotefile) I cannot retrieve history on google colab using pickle load   - im getting 'no such directory'
So how i can run training on AI platform on google cloud and then access history on google colab?
Can i save history.history in bucket ? i tried to use PACKAGE_STAGING_PATH but it didnt worked

Body:
found solution

subprocess.Popen('gsutil cp history gs://bigdatapart2-storage/history1', shell=True, stdout=subprocess.PIPE)


问:
how can i change the header and the data in the mat table angular to be on the right side of the page?
i am trying to use mat table in angular so i can have a table with data the problem is that the headers of the table fields are not in the right side but i want them to be  i used RTl but i did not work what should i do?
this is my table right now

this is my html code

```<code><table mat-table [dataSource]="dataSource" class="mat-elevation-z8"  class="table"  >

    <!--- Note that these columns can be defined in any order.
          The actual rendered columns are set as a property on the row definition" -->

    <!-- Position Column -->
    <ng-container matColumnDef="position">
      <th mat-header-cell *matHeaderCellDef > NO </th>
      <td mat-cell *matCellDef="let element"> {{element.position}} </td>
    </ng-container>

    <!-- Name Column -->
    <ng-container matColumnDef="name">
      <th mat-header-cell *matHeaderCellDef> name </th>
      <td mat-cell *matCellDef="let element"> {{element.name}} </td>
    </ng-container>

    <!-- Weight Column -->
    <ng-container matColumnDef="weight">
      <th mat-header-cell *matHeaderCellDef> weight </th>
      <td mat-cell *matCellDef="let element"> {{element.weight}} </td>
    </ng-container>

    <!-- Symbol Column -->
    <ng-container matColumnDef="symbol">
      <th mat-header-cell *matHeaderCellDef> symbol </th>
      <td mat-cell *matCellDef="let element"> {{element.symbol}} </td>
    </ng-container>

    <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
    <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
  </table>
</code>```

this is css

```<code> table {
        direction: rtl;
        width: 1300px;

      }
</code>```

Body:
i am trying to use mat table in angular so i can have a table with data the problem is that the headers of the table fields are not in the right side but i want them to be  i used RTl but i did not work what should i do?
this is my table right now

this is my html code

    <ng-container matColumnDef="position">
       NO
       {{element.position}}
    </ng-container>

    <ng-container matColumnDef="name">
       name
       {{element.name}}
    </ng-container>

    <ng-container matColumnDef="weight">
       weight
       {{element.weight}}
    </ng-container>

    <ng-container matColumnDef="symbol">
       symbol
       {{element.symbol}}
    </ng-container>

this is css

 table {
        direction: rtl;
        width: 1300px;

      }

Body:
Here a small Stackblitz: https://stackblitz.com/edit/angular-cunndn?file=src/app/table-basic-example.html

You just need to add dir="rtl" to your html tag like...

<table mat-table [dataSource]="dataSource" class="mat-elevation-z8" dir="rtl">


问:
global variable not defined inside async function
I have an async function that is supposed to add reactions to a list until a certain reaction is pressed then it will add all appropriate roles. to do this I have a global variable "reactions = []" that gets reset when the "ok" reaction is pressed. VS Code is telling me this on the line "for react in reactions:" : "reactions is used before it is defined. Move the definition before." this is confusing because roleEmojis is another global variable but that works fine.
here is my code:

```<code>import os
import discord
import time
from discord.utils import get
from discord.ext import commands

token = "TOKEN"
BOT = commands.Bot("£")
reactions_list = []

@BOT.event
async def on_reaction_add(reaction , user):
    if reaction.emoji in roleEmojis.keys() and user != BOT.user:
        if reaction == get(reaction.message.guild.emojis, name = "OK"):
            for react in reactions_list:
                await user.add_roles(roleEmojis[react.emoji])
            reactions_list = []
        else:
            reactions_list.append(reaction)

BOT.run(token)
</code>```

Side note: I haven't yet figured out how to detect when someone has "un-reacted" to a message, id appreciate any help there

答:
In addition to global variables, you can also create variables accessible from anywhere like so:

BOT = commands.Bot("£")
BOT.reactions_list = []

@BOT.event
async def on_reaction_add(reaction , user):
    print(BOT.reactions_list) # proves it's accessible from anywhere
    # rest of your code
```

Body:
I have an async function that is supposed to add reactions to a list until a certain reaction is pressed then it will add all appropriate roles. to do this I have a global variable "reactions = []" that gets reset when the "ok" reaction is pressed. VS Code is telling me this on the line "for react in reactions:" : "reactions is used before it is defined. Move the definition before." this is confusing because roleEmojis is another global variable but that works fine.
here is my code:

import os
import discord
import time
from discord.utils import get
from discord.ext import commands

token = "TOKEN"
BOT = commands.Bot("£")
reactions_list = []

@BOT.event
async def on_reaction_add(reaction , user):
    if reaction.emoji in roleEmojis.keys() and user != BOT.user:
        if reaction == get(reaction.message.guild.emojis, name = "OK"):
            for react in reactions_list:
                await user.add_roles(roleEmojis[react.emoji])
            reactions_list = []
        else:
            reactions_list.append(reaction)

BOT.run(token)

Side note: I haven't yet figured out how to detect when someone has "un-reacted" to a message, id appreciate any help there


问:
I want efficient data structure to store items and their counts and search for min of them?
I want efficient data structure to store items and their counts and search for min of them?

I have a number of items, and a count of each item, I want a data sturucture to store the items and their counts. in my script each time i will search about an item and update its count, also I want to find the item that has the min count, and some times I want the count of some items. would you please tell me which data structure to use with low space and low cost search operations?

答:
Well, a Map, or, more specifically, a HashMap is probably what you're looking for. The lookup complexity is O(1), and finding the lowest or highest is O(n).

```<code>Map<Item, Long> items = new HashMap<>();
items.put(Item.BANANA, 3L);
items.put(Item.APPLE, 4L);

// Count the bananas
long bananasCount = items.getOrDefault(Item.BANANAS, 0L);
// Get the item with the highest count
items.entrySet().stream()
    .max(Comparator.comparing(Map.Entry::getValue))
    .map(Map.Entry::getKey);
</code>```

There are also other structures, which lets you calculate the minimum and maximum even faster (with complexity O(1)), but at the cost of updating probably.

Body:
Well, a Map, or, more specifically, a HashMap is probably what you're looking for. The lookup complexity is O(1), and finding the lowest or highest is O(n).

Map<Item, Long> items = new HashMap<>();
items.put(Item.BANANA, 3L);
items.put(Item.APPLE, 4L);

// Count the bananas
long bananasCount = items.getOrDefault(Item.BANANAS, 0L);
// Get the item with the highest count
items.entrySet().stream()
    .max(Comparator.comparing(Map.Entry::getValue))
    .map(Map.Entry::getKey);

There are also other structures, which lets you calculate the minimum and maximum even faster (with complexity O(1)), but at the cost of updating probably.


问:
How can I populate the 'Spinner' with a list of associated node names from the Firebase Realtime Database?
Let's say I have the following firebase realtime database structure:

```<code>{
    "Object1" : {
        "A" : "exampleData",
        "B" : "exampleData",
        "C" : "exampleData",
        "D" : "exampleData"
    }
}
</code>```

I'm trying to get a list of associated node names from "Object1".
I'm trying Inflate Spinner (which is part of my layout.xml) with this list of associated node names. The spinner will therefore contain items to choose from: A, B, C, D

I'm trying like this:
(Just a snippet)

```<code>@Override
protected void onCreate(@Nullable Bundle savedInstanceState {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.MyActivity);

      Spinner spinner = findViewById(R.id.MySpinner);
      database = FirebaseDatabase.getInstance();
      dbRef = database.getReference("Object1");

      dbRef.addValueEventListener(new ValueEventListener() {
           @Override
           public void onDataChange (@NonNull DataSnapshot dataSnapshot) {
                ArrayList<String> arrList = new ArrayList<String>();
                    for (DataSnapshot snap : dataSnapshot.getChildren()) {
                        arrList.add(snap.getKey());
                    }

                    ArrayAdapter<String> arrAdapter = new ArrayAdapter<String>(MyActivity.this,R.layout.MyActivity, arrList);
                    spinner.setAdapter(arrAdapter);
          }
      });
}
</code>```

After running this activity, the application "crashes" and an error occurs.
If necessary, I am also able to supply an extract from LogCat.

Expectation:
  Retrieve a list of nodes associated with Object1, populate the spinner with this list.

Here is a report from Logcat:

(just errors)

```<code>E/RunLoop: Uncaught exception in Firebase Database runloop (3.0.0). Please report to firebase-database-client@google.com
java.lang.NoClassDefFoundError: com.google.firebase.database.android.AndroidAuthTokenProvider$3
    at com.google.firebase.database.android.AndroidAuthTokenProvider.produceIdTokenListener(com.google.firebase:firebase-database@@16.0.4:85)
    at com.google.firebase.database.android.AndroidAuthTokenProvider.addTokenChangeListener(com.google.firebase:firebase-database@@16.0.4:80)
    at com.google.firebase.database.core.Repo.deferredInitialization(com.google.firebase:firebase-database@@16.0.4:109)
    at com.google.firebase.database.core.Repo.access$000(com.google.firebase:firebase-database@@16.0.4:55)
    at com.google.firebase.database.core.Repo$1.run(com.google.firebase:firebase-database@@16.0.4:94)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:423)
    at java.util.concurrent.FutureTask.run(FutureTask.java:237)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:154)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:269)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
    at java.lang.Thread.run(Thread.java:818)
</code>```

答:
You have supplied the layout file of your activity in

```<code>  ArrayAdapter<String> arrAdapter = new ArrayAdapter<String>(MyActivity.this,R.layout.MyActivity, arrList);
</code>```

The Second argument of the ArrayAdapter<>() requires a resource ID of a TextView as stated in the Error Message

java.lang.IllegalStateException: ArrayAdapter requires the resource ID to be a TextView

You can use R.layout.support_simple_spinner_dropdown_item instead as below

```<code>ArrayAdapter<String> arrAdapter = new ArrayAdapter<String>(MyActivity.this,R.layout.support_simple_spinner_dropdown_item,arrList);
</code>```

Body:
Let's say I have the following firebase realtime database structure:

{
    "Object1" : {
        "A" : "exampleData",
        "B" : "exampleData",
        "C" : "exampleData",
        "D" : "exampleData"
    }
}

I'm trying to get a list of associated node names from "Object1".
I'm trying Inflate Spinner (which is part of my layout.xml) with this list of associated node names. The spinner will therefore contain items to choose from: A, B, C, D

I'm trying like this:
(Just a snippet)

@Override
protected void onCreate(@Nullable Bundle savedInstanceState {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.MyActivity);

      Spinner spinner = findViewById(R.id.MySpinner);
      database = FirebaseDatabase.getInstance();
      dbRef = database.getReference("Object1");

      dbRef.addValueEventListener(new ValueEventListener() {
           @Override
           public void onDataChange (@NonNull DataSnapshot dataSnapshot) {
                ArrayList<String> arrList = new ArrayList<String>();
                    for (DataSnapshot snap : dataSnapshot.getChildren()) {
                        arrList.add(snap.getKey());
                    }

                    ArrayAdapter<String> arrAdapter = new ArrayAdapter<String>(MyActivity.this,R.layout.MyActivity, arrList);
                    spinner.setAdapter(arrAdapter);
          }
      });
}

After running this activity, the application "crashes" and an error occurs.
If necessary, I am also able to supply an extract from LogCat.

Expectation:
  Retrieve a list of nodes associated with Object1, populate the spinner with this list.

Here is a report from Logcat:

(just errors)

E/RunLoop: Uncaught exception in Firebase Database runloop (3.0.0). Please report to firebase-database-client@google.com
java.lang.NoClassDefFoundError: com.google.firebase.database.android.AndroidAuthTokenProvider$3
    at com.google.firebase.database.android.AndroidAuthTokenProvider.produceIdTokenListener(com.google.firebase:firebase-database@@16.0.4:85)
    at com.google.firebase.database.android.AndroidAuthTokenProvider.addTokenChangeListener(com.google.firebase:firebase-database@@16.0.4:80)
    at com.google.firebase.database.core.Repo.deferredInitialization(com.google.firebase:firebase-database@@16.0.4:109)
    at com.google.firebase.database.core.Repo.access$000(com.google.firebase:firebase-database@@16.0.4:55)
    at com.google.firebase.database.core.Repo$1.run(com.google.firebase:firebase-database@@16.0.4:94)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:423)
    at java.util.concurrent.FutureTask.run(FutureTask.java:237)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:154)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:269)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
    at java.lang.Thread.run(Thread.java:818)

Body:
You have supplied the layout file of your activity in

  ArrayAdapter<String> arrAdapter = new ArrayAdapter<String>(MyActivity.this,R.layout.MyActivity, arrList);

The Second argument of the ArrayAdapter<>() requires a resource ID of a TextView as stated in the Error Message

java.lang.IllegalStateException: ArrayAdapter requires the resource ID to be a TextView

You can use R.layout.support_simple_spinner_dropdown_item instead as below

ArrayAdapter<String> arrAdapter = new ArrayAdapter<String>(MyActivity.this,R.layout.support_simple_spinner_dropdown_item,arrList);


问:
switcher php. my question is with switcher. when I switch and form should be changed dynamically

I have 3 options. They are chair , war and peace, acme disc. switcher php. my question is with switcher. when I switch and form should be changed dynamically. I am beginner on php.

```<code><!DOCTYPE html>
    <html>
    <head>
        <title>Product add</title>
        <link rel="stylesheet" href="style.css">
    </head>
    <body>
        <div class="PrAd">
            <h2>
                <b>Product Add</b>
                <button class="button">Save</button>
            </h2>
            <hr>
        </div>
        <div class="form">
            <form>
                <label for="SKU">SKU</label>
                <input type="text" id="formbox" name="SKU"><br>
                <label for="Name ">Name</label>
                <input type="text" id="formbox" name="Name"><br>
                <label for="Price">Price</label>
                <input type="number" id="formbox" name="Price"><br>
                <label>Type Switcher</label>
                <select id="type" name="product">
                    <option value="Acme Disc">Acme Disc</option>
                    <option value="War and Peace">War and Peace</option>
                    <option value="Chair">Chair</option>
                </select>
            </form>
        </div>
        <?php

        ?>
    </body>
    </html>
</code>```

答:
function prodType(prod){
  var acmeAttributes = document.getElementById("acme_disc_attributes");
  var warPeaceAttributes = document.getElementById("war_peace_attributes");
  var chairAttributes = document.getElementById("chair_attributes");

  acmeAttributes.style.display="none";
  warPeaceAttributes.style.display="none";
  chairAttributes.style.display="none";

  if(prod=="Acme Disc"){
    acmeAttributes.style.display="block";
  }else if(prod=="War and Peace"){
    warPeaceAttributes.style.display="block";
  }else if(prod=="Chair"){
  chairAttributes.style.display="block";
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.fieldbox{
display:none;
}</code>```

<!DOCTYPE html>

        <title>Product add</title>
        <link rel="stylesheet" href="style.css">

                Product Add
                <button class="button">Save</button>

            <form>
                SKU
                <input type="text" id="formbox" name="SKU">

                Name
                <input type="text" id="formbox" name="Name">

                Price
                <input type="number" id="formbox" name="Price">

                Type Switcher
                <select id="type" name="product" onChange="prodType(this.value);">
                    <option value="">Choose Switcher</option>
                    <option value="Acme Disc">Acme Disc</option>
                    <option value="War and Peace">War and Peace</option>
                    <option value="Chair">Chair</option>
                </select>

                  Size
                  <input type="text" name="size" value="">

                  Weight
                  <input type="text" name="weight" value="">

                  Length
                  <input type="text" name="length">

                 Width
                <input type="text" name="width">

            </form>

    ```

Body:
I have 3 options. They are chair , war and peace, acme disc. switcher php. my question is with switcher. when I switch and form should be changed dynamically. I am beginner on php.

<!DOCTYPE html>

        <title>Product add</title>
        <link rel="stylesheet" href="style.css">

                Product Add
                <button class="button">Save</button>

            <form>
                SKU
                <input type="text" id="formbox" name="SKU">

                Name
                <input type="text" id="formbox" name="Name">

                Price
                <input type="number" id="formbox" name="Price">

                Type Switcher
                <select id="type" name="product">
                    <option value="Acme Disc">Acme Disc</option>
                    <option value="War and Peace">War and Peace</option>
                    <option value="Chair">Chair</option>
                </select>
            </form>

        <?php

        ?>

Body:
function prodType(prod){
  var acmeAttributes = document.getElementById("acme_disc_attributes");
  var warPeaceAttributes = document.getElementById("war_peace_attributes");
  var chairAttributes = document.getElementById("chair_attributes");

  acmeAttributes.style.display="none";
  warPeaceAttributes.style.display="none";
  chairAttributes.style.display="none";

  if(prod=="Acme Disc"){
    acmeAttributes.style.display="block";
  }else if(prod=="War and Peace"){
    warPeaceAttributes.style.display="block";
  }else if(prod=="Chair"){
  chairAttributes.style.display="block";
  }
}

.fieldbox{
display:none;
}

<!DOCTYPE html>
    <html>
    <head>
        <title>Product add</title>
        <link rel="stylesheet" href="style.css">
    </head>
    <body>
        <div class="PrAd">
            <h2>
                <b>Product Add</b>
                <button class="button">Save</button>
            </h2>
            <hr>
        </div>
        <div class="form">
            <form>
                <label for="SKU">SKU</label>
                <input type="text" id="formbox" name="SKU"><br>
                <label for="Name ">Name</label>
                <input type="text" id="formbox" name="Name"><br>
                <label for="Price">Price</label>
                <input type="number" id="formbox" name="Price"><br>
                <label>Type Switcher</label>
                <select id="type" name="product" onChange="prodType(this.value);">
                    <option value="">Choose Switcher</option>
                    <option value="Acme Disc">Acme Disc</option>
                    <option value="War and Peace">War and Peace</option>
                    <option value="Chair">Chair</option>
                </select>

                <div class="fieldbox" id="acme_disc_attributes">
                  <label>Size</label>
                  <input type="text" name="size" value="">
                </div>

                <div class="fieldbox" id="war_peace_attributes">
                  <label>Weight</label>
                  <input type="text" name="weight" value="">
                </div>

                <div class="fieldbox" id="chair_attributes">
                  <label>Length</label>
                  <input type="text" name="length"><br>
                 <label>Width</label>
                <input type="text" name="width"><br>
                </div>
            </form>
        </div>
    </body>
    </html>


问:
How to set the id of document of firestore using google sheets
I've got a table in google sheets which I want to upload to the firstore using a custom document id to prevent data duplication. How can I change the id of the document.

Full Code:

```<code>
function classRoutineFunction() {
   var firestore = FirestoreApp.getFirestore (email, key, projectId);

  // get document data from ther spreadsheet
   var ss = SpreadsheetApp.getActiveSpreadsheet();
   var sheetname = "Sheet1";
   var sheet = ss.getSheetByName(sheetname);
   // get the last row and column in order to define range
   var sheetLR = sheet.getLastRow(); // get the last row
   var sheetLC = sheet.getLastColumn(); // get the last column

   var dataSR = 2; // the first row of data
   // define the data range
   var sourceRange = sheet.getRange(2,1,sheetLR-dataSR+1,sheetLC);

   // get the data
   var sourceData = sourceRange.getValues();
   // get the number of length of the object in order to establish a loop value
   var sourceLen = sourceData.length;

  // Loop through the rows
   for (var i=0;i<sourceLen;i++){
     if(sourceData[i][1] !== '') {
       var data = {};
       var dateSt = sourceData[i][0].toString();
       var stDate = new Date(dateSt);
       var stringfied = JSON.stringify(stDate);
       var updatedDt = stringfied.slice(1,11);

       data.date = updatedDt;
       data.time = sourceData[i][1];
       data.batch = sourceData[i][2];
       data.topic = sourceData[i][3];
       data._id = dateStr + batch; // Want to set a custom id

       firestore.createDocument("classRoutine",data);
     }

  }
}

</code>```

答:
You can pass the name of the new document into the string argument when calling createDocument. From the documentation on creating documents in Firestore from your script:

Alternatively, we can create the document in the FirstCollection collection called FirstDocument:

```<code>firestore.createDocument("FirstCollection/FirstDocument", data)
</code>```

Here FirstDocument is the name of the document in FirstCollection.

So for you this would look something like:

```<code>firestore.createDocument("classRoutine/yourCustomId",data);
</code>```

Body:
I've got a table in google sheets which I want to upload to the firstore using a custom document id to prevent data duplication. How can I change the id of the document.

Full Code:

function classRoutineFunction() {
   var firestore = FirestoreApp.getFirestore (email, key, projectId);

  // get document data from ther spreadsheet
   var ss = SpreadsheetApp.getActiveSpreadsheet();
   var sheetname = "Sheet1";
   var sheet = ss.getSheetByName(sheetname);
   // get the last row and column in order to define range
   var sheetLR = sheet.getLastRow(); // get the last row
   var sheetLC = sheet.getLastColumn(); // get the last column

   var dataSR = 2; // the first row of data
   // define the data range
   var sourceRange = sheet.getRange(2,1,sheetLR-dataSR+1,sheetLC);

   // get the data
   var sourceData = sourceRange.getValues();
   // get the number of length of the object in order to establish a loop value
   var sourceLen = sourceData.length;

  // Loop through the rows
   for (var i=0;i<sourceLen;i++){
     if(sourceData[i][1] !== '') {
       var data = {};
       var dateSt = sourceData[i][0].toString();
       var stDate = new Date(dateSt);
       var stringfied = JSON.stringify(stDate);
       var updatedDt = stringfied.slice(1,11);

       data.date = updatedDt;
       data.time = sourceData[i][1];
       data.batch = sourceData[i][2];
       data.topic = sourceData[i][3];
       data._id = dateStr + batch; // Want to set a custom id

       firestore.createDocument("classRoutine",data);
     }

  }
}

Body:
You can pass the name of the new document into the string argument when calling createDocument. From the documentation on creating documents in Firestore from your script:

Alternatively, we can create the document in the FirstCollection collection called FirstDocument:

firestore.createDocument("FirstCollection/FirstDocument", data)

Here FirstDocument is the name of the document in FirstCollection.

So for you this would look something like:

firestore.createDocument("classRoutine/yourCustomId",data);


问:
Navbar toggle not working with Angular 4 / ng-bootstrap
I am using ng-bootstrap in my angular 4 project:

```<code><navbar class="navbar navbar-expand-lg navbar-dark bg-dark fixed-top">
    <button aria-controls="navbarsDefault" aria-expanded="false" aria-label="Toggle navigation" class="navbar-toggler navbar-toggler-right" data-target="#navbarsDefault" data-toggle="collapse" type="button">
        <span class="navbar-toggler-icon"></span>
    </button>
    <a class="navbar-brand" href="#">Navbar</a>
    <div class="collapse navbar-collapse" id="navbarsDefault">
        <ul class="navbar-nav mr-auto">
            <li class="nav-item">
                <a class="nav-link active" routerlink="/dashboard" routerlinkactive="active" ng-reflect-router-link="/dashboard" ng-reflect-router-link-active="active" href="/dashboard">Dashboard</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" routerlink="/program" routerlinkactive="active" ng-reflect-router-link="/program" ng-reflect-router-link-active="active" href="/program">Programm</a>
            </li>
        </ul>
    </div>
</navbar>
</code>```

The navbar is there, it is responsive, it seems to work fine. But the navbar-toggler button does not toggle the navbar, when it is collapsed and i can't find an error.

答: Add "./node_modules/jquery/dist/jquery.js", in Angular.json file under script tag and it will work.</p>

Body:
I am using ng-bootstrap in my angular 4 project:

<navbar class="navbar navbar-expand-lg navbar-dark bg-dark fixed-top">
    <button aria-controls="navbarsDefault" aria-expanded="false" aria-label="Toggle navigation" class="navbar-toggler navbar-toggler-right" data-target="#navbarsDefault" data-toggle="collapse" type="button">

    </button>
    Navbar

                Dashboard

                Programm

</navbar>

The navbar is there, it is responsive, it seems to work fine. But the navbar-toggler button does not toggle the navbar, when it is collapsed and i can't find an error.


问:
Label that is passed not appearing
I am trying to create a tableview where once a tableview cell is selected, it passes the name of the cell to a new view controller. When I run this and select a tableview cell, I am brought to another view controller, but the organization label is not there. How do I fix this?

Here is my code for the first view controller.

```<code>import UIKit

struct Organizations {
    var sectionTitle = String()
    var rowTitles = [String]()
}

class SearchOrganizationsViewController: UIViewController {
    @IBOutlet weak var tableView: UITableView!

    var searchOrganizations: Organizations?
    var organizations = [
        Organizations(sectionTitle: "section 1", rowTitles: ["organization 1", "organization 2", "organization 3"]),
        Organizations(sectionTitle: "section 2", rowTitles: ["organization 1", "organization 2"]),
        Organizations(sectionTitle: "section 3", rowTitles: ["organization 1"]),
    ]

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.delegate = self
        tableView.dataSource = self
    }

    extension SearchOrganizationsViewController: UITableViewDelegate, UITableViewDataSource {
        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: "searchCell")
            cell?.textLabel?.lineBreakMode = NSLineBreakMode.byWordWrapping
            cell?.textLabel?.numberOfLines = 3
            if searching {
                cell?.textLabel?.text = self.searchArray[indexPath.section].rowTitles[indexPath.row]
            } else {
                cell?.textLabel?.text = self.organizations[indexPath.section].rowTitles[indexPath.row]
            }
            return cell!
        }

        func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
            selectedOrganizations = organizations[indexPath.row]
            performSegue(withIdentifier: "organizationDetailSegue", sender: self)
        }

        override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
            if let destination = segue.destination as? OrganizationsDetailViewController {
                destination.organization = selectedOrganizations
            }
        }
    }
}
</code>```

Here is my code for the second view controller.

```<code>import UIKit

class OrganizationsDetailViewController: UIViewController {
    @IBOutlet weak var organizationNameLabel: UILabel!

    var organization: Organizations?

    var organizationName: String = ""

    override func viewDidLoad() {
        super.viewDidLoad()

        organizationNameLabel.text = organizationName
    }
}
</code>```

答:
You can pass the selected Organisation by just storing it in a variable like this:

class SearchOrganizationsViewController: UIViewController {
    var selectedOrganisation: Organization?
    var organizations = [Organizations(sectionTitle: "section 1", rowTitles: ["organization 1", "organization 2", "organization 3"]),
            Organizations(sectionTitle: "section 2", rowTitles: ["organization 1", "organization 2"]),
            Organizations(sectionTitle: "section 3", rowTitles: ["organization 1"])
    ]
    //...
}

extension SearchOrganizationsViewController: UITableViewDelegate, UITableViewDataSource {

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        selectedOrganizations = searching ? searchArray[indexPath.section] : organizations[indexPath.section]
        performSegue(withIdentifier: "organizationDetailSegue", sender: self)
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let destination = segue.destination as? OrganizationsDetailViewController {
            destination.organizationName = selectedOrganisation?. sectionTitle
        }
    }
}
```

Title: Label that is passed not appearing

Body:
I am trying to create a tableview where once a tableview cell is selected, it passes the name of the cell to a new view controller. When I run this and select a tableview cell, I am brought to another view controller, but the organization label is not there. How do I fix this?

Here is my code for the first view controller.

import UIKit

struct Organizations {
    var sectionTitle = String()
    var rowTitles = [String]()
}

class SearchOrganizationsViewController: UIViewController {
    @IBOutlet weak var tableView: UITableView!

    var searchOrganizations: Organizations?
    var organizations = [
        Organizations(sectionTitle: "section 1", rowTitles: ["organization 1", "organization 2", "organization 3"]),
        Organizations(sectionTitle: "section 2", rowTitles: ["organization 1", "organization 2"]),
        Organizations(sectionTitle: "section 3", rowTitles: ["organization 1"]),
    ]

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.delegate = self
        tableView.dataSource = self
    }

    extension SearchOrganizationsViewController: UITableViewDelegate, UITableViewDataSource {
        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: "searchCell")
            cell?.textLabel?.lineBreakMode = NSLineBreakMode.byWordWrapping
            cell?.textLabel?.numberOfLines = 3
            if searching {
                cell?.textLabel?.text = self.searchArray[indexPath.section].rowTitles[indexPath.row]
            } else {
                cell?.textLabel?.text = self.organizations[indexPath.section].rowTitles[indexPath.row]
            }
            return cell!
        }

        func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
            selectedOrganizations = organizations[indexPath.row]
            performSegue(withIdentifier: "organizationDetailSegue", sender: self)
        }

        override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
            if let destination = segue.destination as? OrganizationsDetailViewController {
                destination.organization = selectedOrganizations
            }
        }
    }
}

Here is my code for the second view controller.

import UIKit

class OrganizationsDetailViewController: UIViewController {
    @IBOutlet weak var organizationNameLabel: UILabel!

    var organization: Organizations?

    var organizationName: String = ""

    override func viewDidLoad() {
        super.viewDidLoad()

        organizationNameLabel.text = organizationName
    }
}