问:
How can I clear the hover and selection style of ListView in Xamarin.WPF
Here is the XAML:

```<code><?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:d="http://xamarin.com/schemas/2014/forms/design"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             mc:Ignorable="d"
             x:Class="App1.MainPage">

    <ListView ItemsSource="{Binding TestList}" SeparatorVisibility="None" HasUnevenRows="True">
        <ListView.ItemTemplate>
            <DataTemplate>
                <ViewCell>
                    <ViewCell.View>
                        <ContentView>
                            <Label Text="{Binding TestName}"></Label>
                        </ContentView>
                    </ViewCell.View>
                </ViewCell>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</ContentPage>
</code>```

Here is code-behind:

```<code>using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;

namespace App1
{
    // Learn more about making custom code visible in the Xamarin.Forms previewer
    // by visiting https://aka.ms/xamarinforms-previewer
    [DesignTimeVisible(false)]
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
            this.BindingContext = this;
            TestList.Add(new Test() { TestName = "aaa" });
            TestList.Add(new Test() { TestName = "bbb" });
            TestList.Add(new Test() { TestName = "ccc" });
            TestList.Add(new Test() { TestName = "ddd" });
        }
        public ObservableCollection<Test> TestList { get; set; } = new ObservableCollection<Test>();
        public class Test {
            public string TestName { get; set; }
        }
    }
}
</code>```

The project above will cross-platform running both in android and WPF.

In android:

When the item is hovered, there is not any style for true.

When the item is selected, it will change the color into orange and I can change it by changing the background of the Label.

Well, in WPF:

When selected or hovered the item, it will show a blue rectangle that I don't need.

I don't want to show the blue rectangle while selected or hovered the item in WPF, that's why I ask the question.

I probably know I should set some property in the WPF program while I don't know which property I should set it.

Would you please help me? Thank you.

答:
Have you tried something like this.

```<code>         <ListView.ItemContainerStyle>
            <Style TargetType="ListViewItem">
                <Setter Property="OverridesDefaultStyle" Value="True"/>
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="ListViewItem">
                            <ContentPresenter/>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Style>
        </ListView.ItemContainerStyle>
</code>```

But it loses all default behavior. U can use triggers and visual states incase customisation is required like mouse over effects and so on.

Body:
Here is the XAML:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:d="http://xamarin.com/schemas/2014/forms/design"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             mc:Ignorable="d"
             x:Class="App1.MainPage">

    <ListView ItemsSource="{Binding TestList}" SeparatorVisibility="None" HasUnevenRows="True">
        <ListView.ItemTemplate>
            <DataTemplate>
                <ViewCell>
                    <ViewCell.View>
                        <ContentView>

                        </ContentView>
                    </ViewCell.View>
                </ViewCell>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</ContentPage>

Here is code-behind:

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;

namespace App1
{
    // Learn more about making custom code visible in the Xamarin.Forms previewer
    // by visiting https://aka.ms/xamarinforms-previewer
    [DesignTimeVisible(false)]
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
            this.BindingContext = this;
            TestList.Add(new Test() { TestName = "aaa" });
            TestList.Add(new Test() { TestName = "bbb" });
            TestList.Add(new Test() { TestName = "ccc" });
            TestList.Add(new Test() { TestName = "ddd" });
        }
        public ObservableCollection<Test> TestList { get; set; } = new ObservableCollection<Test>();
        public class Test {
            public string TestName { get; set; }
        }
    }
}

The project above will cross-platform running both in android and WPF.

In android:

When the item is hovered, there is not any style for true.

When the item is selected, it will change the color into orange and I can change it by changing the background of the Label.

Well, in WPF:

When selected or hovered the item, it will show a blue rectangle that I don't need.

I don't want to show the blue rectangle while selected or hovered the item in WPF, that's why I ask the question.

I probably know I should set some property in the WPF program while I don't know which property I should set it.

Would you please help me? Thank you.

Body:
Have you tried something like this.

         <ListView.ItemContainerStyle>
            <Style TargetType="ListViewItem">
                <Setter Property="OverridesDefaultStyle" Value="True"/>
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="ListViewItem">
                            <ContentPresenter/>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Style>
        </ListView.ItemContainerStyle>

But it loses all default behavior. U can use triggers and visual states incase customisation is required like mouse over effects and so on.


来源: stackexchange

问:
how to convert 12hrs format time to utc in android
getting wrong results after converting 12hrs time format to utc.</p>

```<code> String inputPa = "hh:mm a";
            String OutPa = "yyyy-MM-dd'T'HH:mm:ss'Z'";
            SimpleDateFormat inputPatter = new SimpleDateFormat(inputPa);
            SimpleDateFormat outputPatter = new SimpleDateFormat(OutPa);

            Date date1 = null;
            String str1 = null;

            try {
                date1 = inputPatter.parse(txtStartTime.getText().toString());
                str1 = outputPatter.format(date1);
                Log.d("mycheck", str1);

            } catch (ParseException e) {
                e.printStackTrace();
            }
</code>```

答:
java.time and ThreeTenABP

I assumed you wanted today’s date in your time zone.

```<code>    String inputPa = "hh:mm a";
    DateTimeFormatter timeFormatter12Hours = DateTimeFormatter.ofPattern(inputPa, Locale.ENGLISH);
    ZoneId zone = ZoneId.of("America/Detroit");

    String timeString = "11:34 AM";

    LocalTime time = LocalTime.parse(timeString, timeFormatter12Hours);
    Instant inst = LocalDate.now(zone).atTime(time).atZone(zone).toInstant();

    System.out.println(inst);
</code>```

Output from this example is:

2020-05-30T15:34:00Z

I would not bother converting the Instant to a string explicitly. It prints in UTC in your desired format when you print it, thus implicitly invoking its toString method (the format is ISO 8601, the international standard).

Please fill in your desired time zone. To rely on the device’ time zone setting set zone to ZoneId.systemDefault().

I am of course happy to use java.time, the modern Java date and time API. You can do that on your Android version too, see the details below.

Question: Doesn’t java.time require Android API level 26?

java.time works nicely on both older and newer Android devices. It just requires at least Java 6.

In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.

In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).

On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.

Links

Oracle tutorial: Date Time explaining how to use java.time.

Java Specification Request (JSR) 310, where java.time was first described.

ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).

ThreeTenABP, Android edition of ThreeTen Backport

Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.

Wikipedia article: ISO 8601

ContentLicense: CC BY-SA 4.0

Body:
getting wrong results after converting 12hrs time format to utc.

 String inputPa = "hh:mm a";
            String OutPa = "yyyy-MM-dd'T'HH:mm:ss'Z'";
            SimpleDateFormat inputPatter = new SimpleDateFormat(inputPa);
            SimpleDateFormat outputPatter = new SimpleDateFormat(OutPa);

            Date date1 = null;
            String str1 = null;

            try {
                date1 = inputPatter.parse(txtStartTime.getText().toString());
                str1 = outputPatter.format(date1);
                Log.d("mycheck", str1);

            } catch (ParseException e) {
                e.printStackTrace();
            }

Body:
java.time and ThreeTenABP

I assumed you wanted today’s date in your time zone.

    String inputPa = "hh:mm a";
    DateTimeFormatter timeFormatter12Hours = DateTimeFormatter.ofPattern(inputPa, Locale.ENGLISH);
    ZoneId zone = ZoneId.of("America/Detroit");

    String timeString = "11:34 AM";

    LocalTime time = LocalTime.parse(timeString, timeFormatter12Hours);
    Instant inst = LocalDate.now(zone).atTime(time).atZone(zone).toInstant();

    System.out.println(inst);

Output from this example is:

2020-05-30T15:34:00Z

I would not bother converting the Instant to a string explicitly. It prints in UTC in your desired format when you print it, thus implicitly invoking its toString method (the format is ISO 8601, the international standard).

Please fill in your desired time zone. To rely on the device’ time zone setting set zone to ZoneId.systemDefault().

I am of course happy to use java.time, the modern Java date and time API. You can do that on your Android version too, see the details below.

Question: Doesn’t java.time require Android API level 26?

java.time works nicely on both older and newer Android devices. It just requires at least Java 6.

In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.

In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).

On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.

Links

Oracle tutorial: Date Time explaining how to use java.time.

Java Specification Request (JSR) 310, where java.time was first described.

ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).

ThreeTenABP, Android edition of ThreeTen Backport

Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.

Wikipedia article: ISO 8601


问:
SQL Server docker fails to start on Docker Mac Desktop using compose configuration
Use case:
I want to start SQL Server via docker on my mac for test and dev purposes.
As I do not want to loose my databases switching docker containers I want to use volumes.

Using docker volumes I can do that.

docker run --name 'mssql' -e 'ACCEPT_EULA=Y' -e 'MSSQL_SA_PASSWORD=SuperSecret' -p 1433:1433 -v mssqldata:/var/opt/mssql -d mcr.microsoft.com/mssql/server

But on mac the volume data is also stored inside the VM.

So next I tried to setup a docker compose configuration to store files on my favorite place.

```<code>version: '3'

volumes:
  dbdata:
    driver: local
    driver_opts:
      type: 'none'
      o: 'bind'
      device: '/Users/rausch/Documents/docker-volumes/mssql/data'

services:
  sql1:
    image: "mcr.microsoft.com/mssql/server"
    ports:
      - 1433:1433
    environment:
      PATH: '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin'
      ACCEPT_EULA: Y
      SA_PASSWORD: 1sa!1234
      MSSQL_PID: Standard
    volumes:
      - dbdata:/var/opt/mssql
</code>```

Starting this with

docker compose -f myconfig.yml up

The sql server starts and start copy the files to my defined location

But the docker image exists with error.
Here the output:

```<code>Creating volume "documents_dbdata" with local driver
Creating documents_sql1_1 ... done
Attaching to documents_sql1_1
sql1_1  | SQL Server 2019 will run as non-root by default.
sql1_1  | This container is running as user mssql.
sql1_1  | To learn more visit https://go.microsoft.com/fwlink/?linkid=2099216.
sql1_1  | 2020-05-30 07:27:18.60 Server      Setup step is copying system data file 'C:\templatedata\master.mdf' to '/var/opt/mssql/data/master.mdf'.
2020-05-30 07:27:19.67 Server      Did not find an existing master data file /var/opt/mssql/data/master.mdf, copying the missing default master and other system database files. If you have moved the database location, but not moved the database files, startup may fail. To repair: shutdown SQL Server, move the master database to configured location, and restart.
2020-05-30 07:27:19.70 Server      Setup step is copying system data file 'C:\templatedata\mastlog.ldf' to '/var/opt/mssql/data/mastlog.ldf'.
2020-05-30 07:27:19.79 Server      Setup step is copying system data file 'C:\templatedata\model.mdf' to '/var/opt/mssql/data/model.mdf'.
2020-05-30 07:27:19.98 Server      Setup step is copying system data file 'C:\templatedata\modellog.ldf' to '/var/opt/mssql/data/modellog.ldf'.
2020-05-30 07:27:20.17 Server      Setup step is copying system data file 'C:\templatedata\msdbdata.mdf' to '/var/opt/mssql/data/msdbdata.mdf'.
2020-05-30 07:27:20.47 Server      Setup step is copying system data file 'C:\templatedata\msdblog.ldf' to '/var/opt/mssql/data/msdblog.ldf'.
2020-05-30 07:27:20.55 Server      Setup step is FORCE copying system data file 'C:\templatedata\model_replicatedmaster.mdf' to '/var/opt/mssql/data/model_replicatedmaster.mdf'.
2020-05-30 07:27:20.70 Server      Setup step is FORCE copying system data file 'C:\templatedata\model_replicatedmaster.ldf' to '/var/opt/mssql/data/model_replicatedmaster.ldf'.
2020-05-30 07:27:20.78 Server      Setup step is FORCE copying system data file 'C:\templatedata\model_msdbdata.mdf' to '/var/opt/mssql/data/model_msdbdata.mdf'.
2020-05-30 07:27:21.02 Server      Setup step is FORCE copying system data file 'C:\templatedata\model_msdblog.ldf' to '/var/opt/mssql/data/model_msdblog.ldf'.
2020-05-30 07:27:22.99 Server      Microsoft SQL Server 2019 (RTM-CU4) (KB4548597) - 15.0.4033.1 (X64)
sql1_1  Mar 14 2020 16:10:35
sql1_1  Copyright (C) 2019 Microsoft Corporation
sql1_1  Standard Edition (64-bit) on Linux (Ubuntu 18.04.4 LTS) <X64>
2020-05-30 07:27:23.01 Server      UTC adjustment: 0:00
2020-05-30 07:27:23.02 Server      (c) Microsoft Corporation.
2020-05-30 07:27:23.03 Server      All rights reserved.
2020-05-30 07:27:23.04 Server      Server process ID is 36.
2020-05-30 07:27:23.05 Server      Logging SQL Server messages in file '/var/opt/mssql/log/errorlog'.
2020-05-30 07:27:23.06 Server      Registry startup parameters:
sql1_1   -d /var/opt/mssql/data/master.mdf
sql1_1   -l /var/opt/mssql/data/mastlog.ldf
sql1_1   -e /var/opt/mssql/log/errorlog
2020-05-30 07:27:23.10 Server      Error: 17113, Severity: 16, State: 1.
2020-05-30 07:27:23.10 Server      Error 87(The parameter is incorrect.) occurred while opening file '/var/opt/mssql/data/master.mdf' to obtain configuration information at startup. An invalid startup option might have caused the error. Verify your startup options, and correct or remove them if necessary.
documents_sql1_1 exited with code 1
</code>```

So, anyone can tell me what I do wrong?

答:
I was able to get it to start on macOS using a Docker volume. Note my compose.yml file requires at least version 3.2 to allow the service's volumes definition to work:

```<code>version: "3.2"
services:
  sql1:
    image: "mcr.microsoft.com/mssql/server"
    ports:
      - 1433:1433
    environment:
      PATH: "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
      ACCEPT_EULA: Y
      SA_PASSWORD: 1sa!1234
      MSSQL_PID: Standard
    volumes:
      - type: volume
        source: mssql
        target: /var/opt/mssql
volumes:
  mssql:
    external:
      name: mssql
</code>```

I then launched the container with:

$ docker volume create mssql
mssql

$ docker volume inspect mssql
[
    {
        "CreatedAt": "2020-05-30T09:36:31Z",
        "Driver": "local",
        "Labels": {},
        "Mountpoint": "/var/lib/docker/volumes/mssql/_data",
        "Name": "mssql",
        "Options": {},
        "Scope": "local"
    }
]

$ docker-compose -f compose.yml up
# lots of startup log...
```

Hope this helps.

Body:
Use case:
I want to start SQL Server via docker on my mac for test and dev purposes.
As I do not want to loose my databases switching docker containers I want to use volumes.

Using docker volumes I can do that.

docker run --name 'mssql' -e 'ACCEPT_EULA=Y' -e 'MSSQL_SA_PASSWORD=SuperSecret' -p 1433:1433 -v mssqldata:/var/opt/mssql -d mcr.microsoft.com/mssql/server

But on mac the volume data is also stored inside the VM.

So next I tried to setup a docker compose configuration to store files on my favorite place.

version: '3'

volumes:
  dbdata:
    driver: local
    driver_opts:
      type: 'none'
      o: 'bind'
      device: '/Users/rausch/Documents/docker-volumes/mssql/data'

services:
  sql1:
    image: "mcr.microsoft.com/mssql/server"
    ports:
      - 1433:1433
    environment:
      PATH: '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin'
      ACCEPT_EULA: Y
      SA_PASSWORD: 1sa!1234
      MSSQL_PID: Standard
    volumes:
      - dbdata:/var/opt/mssql

Starting this with

docker compose -f myconfig.yml up

The sql server starts and start copy the files to my defined location

But the docker image exists with error.
Here the output:

Creating volume "documents_dbdata" with local driver
Creating documents_sql1_1 ... done
Attaching to documents_sql1_1
sql1_1  | SQL Server 2019 will run as non-root by default.
sql1_1  | This container is running as user mssql.
sql1_1  | To learn more visit https://go.microsoft.com/fwlink/?linkid=2099216.
sql1_1  | 2020-05-30 07:27:18.60 Server      Setup step is copying system data file 'C:\templatedata\master.mdf' to '/var/opt/mssql/data/master.mdf'.
2020-05-30 07:27:19.67 Server      Did not find an existing master data file /var/opt/mssql/data/master.mdf, copying the missing default master and other system database files. If you have moved the database location, but not moved the database files, startup may fail. To repair: shutdown SQL Server, move the master database to configured location, and restart.
2020-05-30 07:27:19.70 Server      Setup step is copying system data file 'C:\templatedata\mastlog.ldf' to '/var/opt/mssql/data/mastlog.ldf'.
2020-05-30 07:27:19.79 Server      Setup step is copying system data file 'C:\templatedata\model.mdf' to '/var/opt/mssql/data/model.mdf'.
2020-05-30 07:27:19.98 Server      Setup step is copying system data file 'C:\templatedata\modellog.ldf' to '/var/opt/mssql/data/modellog.ldf'.
2020-05-30 07:27:20.17 Server      Setup step is copying system data file 'C:\templatedata\msdbdata.mdf' to '/var/opt/mssql/data/msdbdata.mdf'.
2020-05-30 07:27:20.47 Server      Setup step is copying system data file 'C:\templatedata\msdblog.ldf' to '/var/opt/mssql/data/msdblog.ldf'.
2020-05-30 07:27:20.55 Server      Setup step is FORCE copying system data file 'C:\templatedata\model_replicatedmaster.mdf' to '/var/opt/mssql/data/model_replicatedmaster.mdf'.
2020-05-30 07:27:20.70 Server      Setup step is FORCE copying system data file 'C:\templatedata\model_replicatedmaster.ldf' to '/var/opt/mssql/data/model_replicatedmaster.ldf'.
2020-05-30 07:27:20.78 Server      Setup step is FORCE copying system data file 'C:\templatedata\model_msdbdata.mdf' to '/var/opt/mssql/data/model_msdbdata.mdf'.
2020-05-30 07:27:21.02 Server      Setup step is FORCE copying system data file 'C:\templatedata\model_msdblog.ldf' to '/var/opt/mssql/data/model_msdblog.ldf'.
2020-05-30 07:27:22.99 Server      Microsoft SQL Server 2019 (RTM-CU4) (KB4548597) - 15.0.4033.1 (X64)
sql1_1  Mar 14 2020 16:10:35
sql1_1  Copyright (C) 2019 Microsoft Corporation
sql1_1  Standard Edition (64-bit) on Linux (Ubuntu 18.04.4 LTS) <X64>
2020-05-30 07:27:23.01 Server      UTC adjustment: 0:00
2020-05-30 07:27:23.02 Server      (c) Microsoft Corporation.
2020-05-30 07:27:23.03 Server      All rights reserved.
2020-05-30 07:27:23.04 Server      Server process ID is 36.
2020-05-30 07:27:23.05 Server      Logging SQL Server messages in file '/var/opt/mssql/log/errorlog'.
2020-05-30 07:27:23.06 Server      Registry startup parameters:
sql1_1   -d /var/opt/mssql/data/master.mdf
sql1_1   -l /var/opt/mssql/data/mastlog.ldf
sql1_1   -e /var/opt/mssql/log/errorlog
2020-05-30 07:27:23.10 Server      Error: 17113, Severity: 16, State: 1.
2020-05-30 07:27:23.10 Server      Error 87(The parameter is incorrect.) occurred while opening file '/var/opt/mssql/data/master.mdf' to obtain configuration information at startup. An invalid startup option might have caused the error. Verify your startup options, and correct or remove them if necessary.
documents_sql1_1 exited with code 1

So, anyone can tell me what I do wrong?

Body:
I was able to get it to start on macOS using a Docker volume. Note my compose.yml file requires at least version 3.2 to allow the service's volumes definition to work:

version: "3.2"
services:
  sql1:
    image: "mcr.microsoft.com/mssql/server"
    ports:
      - 1433:1433
    environment:
      PATH: "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
      ACCEPT_EULA: Y
      SA_PASSWORD: 1sa!1234
      MSSQL_PID: Standard
    volumes:
      - type: volume
        source: mssql
        target: /var/opt/mssql
volumes:
  mssql:
    external:
      name: mssql

I then launched the container with:

$ docker volume create mssql
mssql

$ docker volume inspect mssql
[
    {
        "CreatedAt": "2020-05-30T09:36:31Z",
        "Driver": "local",
        "Labels": {},
        "Mountpoint": "/var/lib/docker/volumes/mssql/_data",
        "Name": "mssql",
        "Options": {},
        "Scope": "local"
    }
]

$ docker-compose -f compose.yml up
# lots of startup log...

Hope this helps.


问:
Django ImportError: cannot import name 'ReporterProfile' from partially initialized module 'accounts.models' (most likely due to a circular import)
I have two apps: collection and accounts, with both having models defined. I'm importing a model ReporterProfile from accounts to collection. Similarly, I'm importing a model Report from collection to accounts.

The Report model from collection is called in a model class method in accounts like this:

```<code>from collection.models import Report

class ReporterProfile(models.Model):
    ....

    def published_articles_number(self):
        num = Report.objects.filter(reporterprofile=self.id).count()
        return num
</code>```

Similarly, I am importing ReporterProfile and User models from accounts to collection model like this:

```<code>from accounts.models import ReporterProfile, User
from <project_name> import settings

class Report(models.Model):
    reporterprofile = models.ForeignKey(ReporterProfile, on_delete=models.CASCADE, verbose_name="Report Author")
    ...

class Comment(models.Model):
    report = models.ForeignKey(Report, on_delete=models.CASCADE, related_name='comments')
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, verbose_name="Comment by")
    ...
</code>```

When running the server or makemigrations, I get the error:

```<code>File "F:\project_name\accounts\models.py", line 8, in <module>
    from collection.models import Report

File "F:\project_name\collection\models.py", line 2, in <module>
    from accounts.models import ReporterProfile, User

ImportError: cannot import name 'ReporterProfile' from partially initialized module 'accounts.models' (most likely due to a circular import) (F:\project_name\accounts\models.py)
</code>```

I think the error is coming because of a wrong importing pattern. What should I do?

答:
For ForeignKey:

Instead of using reporterprofile = models.ForeignKey(ReporterProfile, ...), you can use reporterprofile = models.ForeignKey("accounts.ReporterProfile", ...), so you don't have to import the model.

For preventing circulor import error :

Instead of using :

```<code>from accounts.models import ReporterProfile
[...]
foo = ReporterProfile()
</code>```

You can use:

```<code>import accounts.models
[...]
foo = accounts.models.ReporterProfile()
</code>```

Body:
I have two apps: collection and accounts, with both having models defined. I'm importing a model ReporterProfile from accounts to collection. Similarly, I'm importing a model Report from collection to accounts.

The Report model from collection is called in a model class method in accounts like this:

from collection.models import Report

class ReporterProfile(models.Model):
    ....

    def published_articles_number(self):
        num = Report.objects.filter(reporterprofile=self.id).count()
        return num

Similarly, I am importing ReporterProfile and User models from accounts to collection model like this:

from accounts.models import ReporterProfile, User
from <project_name> import settings

class Report(models.Model):
    reporterprofile = models.ForeignKey(ReporterProfile, on_delete=models.CASCADE, verbose_name="Report Author")
    ...

class Comment(models.Model):
    report = models.ForeignKey(Report, on_delete=models.CASCADE, related_name='comments')
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, verbose_name="Comment by")
    ...

When running the server or makemigrations, I get the error:

File "F:\project_name\accounts\models.py", line 8, in <module>
    from collection.models import Report

File "F:\project_name\collection\models.py", line 2, in <module>
    from accounts.models import ReporterProfile, User

ImportError: cannot import name 'ReporterProfile' from partially initialized module 'accounts.models' (most likely due to a circular import) (F:\project_name\accounts\models.py)

I think the error is coming because of a wrong importing pattern. What should I do?

Body:
For ForeignKey:

Instead of using reporterprofile = models.ForeignKey(ReporterProfile, ...), you can use reporterprofile = models.ForeignKey("accounts.ReporterProfile", ...), so you don't have to import the model.

For preventing circulor import error :

Instead of using :

from accounts.models import ReporterProfile
[...]
foo = ReporterProfile()

You can use:

import accounts.models
[...]
foo = accounts.models.ReporterProfile()


问:
Settings IBOutlets to nil in dealloc
In the section titled 'Memory Warnings' here http://developer.apple.com/iphone/library/documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmNibObjects.html, I don't follow why the IBOutlet is set to nil in the dealloc.  If

```<code>self.anOutlet = nil
</code>```

causes a crash as mentioned in the topic, why are they setting the ivar to nil?

In general, why would you set an ivar to nil in the dealloc when you are already calling release?

答:
Sometimes a crash is a good thing, and a quick solution would hide a deeper problem. Calling a released variable might be something you want to know about.

The book iOS Recipes refers to this issue:

Cleanup in -dealloc

  In addition to releasing all relevant instance variables in the -dealloc, our examples set them to nil. This practice is one of the most hotly debated topics among Cocoa programmers, and both sides of the argu- ment hold weight. This book is not meant to participate in the debate at all: we set them to nil, but that doesn’t mean you have to. If you don’t like nil-in-dealloc, feel free to leave it out of your own code.

A quick google search found this thread:

http://www.cocoabuilder.com/archive/cocoa/204055-why-should-we-set-ivars-to-nil-in-dealloc.html

ContentLicense: CC BY-SA 2.5

Title: Settings IBOutlets to nil in dealloc

Body:
In the section titled 'Memory Warnings' here http://developer.apple.com/iphone/library/documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmNibObjects.html, I don't follow why the IBOutlet is set to nil in the dealloc.  If

self.anOutlet = nil

causes a crash as mentioned in the topic, why are they setting the ivar to nil?

In general, why would you set an ivar to nil in the dealloc when you are already calling release?

ContentLicense: CC BY-SA 3.0


问:
Rust: the usage of "self" when bringing paths into scope

mod front_of_house {
    pub mod hosting {
        pub fn add_to_waitlist() {}
    }
}

use self::front_of_house::hosting;

pub fn eat_at_restaurant() {
    hosting::add_to_waitlist();
    hosting::add_to_waitlist();
    hosting::add_to_waitlist();
}
```

The code is from Rust Book. In this case, if using the relative path, why bother to use self? I find that use front_of_house::hosting works well here.

So, any necessary reason to introduce self here?

答: The outcome of use front_of_house::hosting depends on the context. If the crate root contains extern crate front_of_house or front_of_house is a dependency in Cargo.toml, this will refer to hosting in that crate. In your case, however, there is the local module front_of_house, which takes priority over external crates. Conveniently, it's located just before the code that uses it, so it's obvious that it's the actual module being used. In larger files, however, there is a chance that the source of a module is ambiguous, i.e. if there is a dependency named the same as a local module. In that case, the extra self adds clarity to the code, helping you differentiate between dependencies and local modules. If, in that case, you wanted to use the dependency, you'd use ::front_of_house::hosting, which unconditionally refers to the dependency and fails if there isn't one named like that.

Body:
mod front_of_house {
    pub mod hosting {
        pub fn add_to_waitlist() {}
    }
}

use self::front_of_house::hosting;

pub fn eat_at_restaurant() {
    hosting::add_to_waitlist();
    hosting::add_to_waitlist();
    hosting::add_to_waitlist();
}

The code is from Rust Book. In this case, if using the relative path, why bother to use self? I find that use front_of_house::hosting works well here.

So, any necessary reason to introduce self here?


问:
Fetch data for the entire app without depending on component logic
There are X routes in the frontend made with React-router and each of them drives to a component.

No matter which route is visited, I need to use some data from an api.

This data is constant through the application. Using Redux I could dispatch an action FETCH_DATA in each React component and manage the logic of fetching in Redux actions.

However, this looks repetitive to me because I would be writing the same logic through all the React components that need data: look for the the data in the store. If it's there take it. If it's not there, dispatch FETCH_DATA.

What is another approach?

答:
GraphQL offers an elegant solution for this requirement of sharing data across components belonging to different routes.

More information:

https://www.youtube.com/watch?v=p_kqcGW1jkY

Apollo GraphQL (React) Data sharing across components


问:
Making button enabled when javascript return true
I'm trying to do a form with a basic captcha. Currently, because I'm a novice HTML coder, I only did the submit button enabled when the user clicks the verify button (it doesn'T enable itself when it sees return true.) And I'm trying to make it so if it returns return true i want to make the button enabled, and disabled at other times. Here is the link to the code: https://codepen.io/pen/GRpVmve

I would appreciate if anyone helps.

答:
remove button verify button and add to input oninput function

function Check(){
  document.getElementById("button2").disabled = true;
  if(ValidCaptcha()){
    document.getElementById("button2").disabled = false;
  }
}

function Captcha(){
   var alpha = new Array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z');
   var i;
   for (i=0;i<6;i++){
     var a = alpha[Math.floor(Math.random() * alpha.length)];
     var b = alpha[Math.floor(Math.random() * alpha.length)];
     var c = alpha[Math.floor(Math.random() * alpha.length)];
     var d = alpha[Math.floor(Math.random() * alpha.length)];
     var e = alpha[Math.floor(Math.random() * alpha.length)];
     var f = alpha[Math.floor(Math.random() * alpha.length)];
     var g = alpha[Math.floor(Math.random() * alpha.length)];
    }
  var code = a + ' ' + b + ' ' + ' ' + c + ' ' + d + ' ' + e + ' '+ f + ' ' + g;
  document.getElementById("mainCaptcha").value = code;
 Check()
}
function ValidCaptcha(){
    var string1 = removeSpaces(document.getElementById('mainCaptcha').value);
    var string2 = removeSpaces(document.getElementById('txtInput').value);
    if (string1 == string2){
      return true;
    }
    else{
      return false;
    }
}
function removeSpaces(string){
  return string.split(' ').join('');
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form action="https://www.w3schools.com/action_page.php">
  <label for="fname">First name:</label><br>
  <input type="text" id="fname" name="fname" value="John"><br>
  <label for="lname">Last name:</label><br>
  <input type="text" id="lname" name="lname" value="Doe"><br><br>
  <h3>Gender</h3>
    <input type="radio" id="male" name="gender" value="male">

  <label for="male">Male</label><br>
  <input type="radio" id="female" name="gender" value="female">
  <label for="female">Female</label><br>
  <input type="radio" id="other" name="gender" value="other">
  <label for="other">Other</label>

     <body onload="Captcha();">
        <table>
          <tr>
           <h3>
                 Captcha<br />
           </td>
          </tr>
          <tr>
           <td>
             <input type="text" id="mainCaptcha" disabled/>
              <input type="button" id="refresh" value="Refresh" onclick="Captcha();" />
           </td>
          </tr>
          <tr>
           <td>
              <input type="text"oninput="Check()" name="captcha" id="txtInput"/>
          </td>
         </tr>
         <tr>
          <td>

              <input type="submit" id="button2" value="Send" disabled>
          </td>
        </tr>
      </table>
    </body>

</form> </code>```

Body:
remove button verify button and add to input oninput function

function Check(){
  document.getElementById("button2").disabled = true;
  if(ValidCaptcha()){
    document.getElementById("button2").disabled = false;
  }
}

function Captcha(){
   var alpha = new Array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z');
   var i;
   for (i=0;i<6;i++){
     var a = alpha[Math.floor(Math.random() * alpha.length)];
     var b = alpha[Math.floor(Math.random() * alpha.length)];
     var c = alpha[Math.floor(Math.random() * alpha.length)];
     var d = alpha[Math.floor(Math.random() * alpha.length)];
     var e = alpha[Math.floor(Math.random() * alpha.length)];
     var f = alpha[Math.floor(Math.random() * alpha.length)];
     var g = alpha[Math.floor(Math.random() * alpha.length)];
    }
  var code = a + ' ' + b + ' ' + ' ' + c + ' ' + d + ' ' + e + ' '+ f + ' ' + g;
  document.getElementById("mainCaptcha").value = code;
 Check()
}
function ValidCaptcha(){
    var string1 = removeSpaces(document.getElementById('mainCaptcha').value);
    var string2 = removeSpaces(document.getElementById('txtInput').value);
    if (string1 == string2){
      return true;
    }
    else{
      return false;
    }
}
function removeSpaces(string){
  return string.split(' ').join('');
}

<form action="https://www.w3schools.com/action_page.php">
  <label for="fname">First name:</label><br>
  <input type="text" id="fname" name="fname" value="John"><br>
  <label for="lname">Last name:</label><br>
  <input type="text" id="lname" name="lname" value="Doe"><br><br>
  <h3>Gender</h3>
    <input type="radio" id="male" name="gender" value="male">

  <label for="male">Male</label><br>
  <input type="radio" id="female" name="gender" value="female">
  <label for="female">Female</label><br>
  <input type="radio" id="other" name="gender" value="other">
  <label for="other">Other</label>

     <body onload="Captcha();">
        <table>
          <tr>
           <h3>
                 Captcha<br />
           </td>
          </tr>
          <tr>
           <td>
             <input type="text" id="mainCaptcha" disabled/>
              <input type="button" id="refresh" value="Refresh" onclick="Captcha();" />
           </td>
          </tr>
          <tr>
           <td>
              <input type="text"oninput="Check()" name="captcha" id="txtInput"/>
          </td>
         </tr>
         <tr>
          <td>

              <input type="submit" id="button2" value="Send" disabled>
          </td>
        </tr>
      </table>
    </body>

</form>


问:
Errors with declared array/table variable values in SAP HanaDB SQL
I am trying to add a declared variable to replace a hardcoded list of values in a "where in" clause.
Researching how Hana handles array variables it seems like I can do this by declaring an array and then either using a select directly on it or by unnesting it first into a table but I keep getting errors I can't resolve.

When I try it this way:

DO
BEGIN

  DECLARE CODES_ARRAY NVARCHAR(100) ARRAY = ARRAY('01','02','03','04');

  SELECT T0."ItemCode"
  FROM OITM T0
    INNER JOIN OITW T1 ON T0."ItemCode" = T1."ItemCode"
  WHERE "WhsCode" IN (SELECT "code" FROM :CODES_ARRAY); -- line 9 where error occurs

END;

```

<p>I get this error message <code>sql syntax error: incorrect syntax near ")": line 9 col 54 (at pos 239)</code></p>

<p>I can't figure out what the syntax error resolution is. </p>

<p>So then I tried inserting a declared table variable like this:</p>

<pre class="lang-sql prettyprint-override"><code>DO
BEGIN

  DECLARE CODES_ARRAY NVARCHAR(100) ARRAY = ARRAY('01','02','03','04');
  DECLARE CODES_TABLE TABLE = UNNEST(:CODES_ARRAY) AS ("code"); -- line 5 where error occurs

  SELECT T0."ItemCode"
  FROM OITM T0
    INNER JOIN OITW T1 ON T0."ItemCode" = T1."ItemCode"
  WHERE "WhsCode" IN (SELECT "code" FROM CODES_TABLE); -- I know : is missing here but when adding, the same error from previous block shows up

END;
</code>```

and I get this error message: identifier must be declared: 1: line 5 col 38 (at pos 123)

As far as I can tell the array variable is declared as it should be so I don't know how to resolve the error.

I've read the SAP Hana SQL Reference documentation (for array/table variables, unnest function, etc.) over and over and it seems like I've got everything setup correctly but can't figure out these errors. I would like to be able to use both of these approaches at different times if possible (the "array variable to table variable" and the "array variable only" approaches)

I don't know exactly what is going on here, but one thing I notice that the two different error messages referenced in my post (see difference from errors in the first two code blocks) is that each error is occurring either immediately before the use of the variable with the : (in the case of the UNNEST) or immediately following the variable with the : (in the case of using in the SELECT * FROM in the query).

Because of that, I wondered if the issue is "upstream" at the Hana ADO.NET application query preparation and execution call level, but I ran a test and when I double checked the query string just before it is executed, it appears unchanged and the variables with : still look as they should, so at least as far as just before execution through Hana ADO.NET HanaCommand it looks correct - but once executing the query using HanaDataReader or HanaDataAdapter it returns the error messages referred to above. It may be a red herring to chase the problem from the Hana ADO.NET level but don't know what else to do.

Update

To further troubleshoot, I tried executing this code block below using hdbsql.exe -n XXX.XXX.XXX.XXX:30015 -u XXX -p XXX -m -I "c:\temp\test.sql" -c "#" and it works! So, the errors I see only show up when executing the same query through the Hana ADO.NET interface.

DO
BEGIN

  DECLARE CODES_ARRAY NVARCHAR(10) ARRAY = ARRAY('01','02','03','04');
  DECLARE CODES_TABLE TABLE ("code" NVARCHAR(10)) = UNNEST(:CODES_ARRAY) AS ("code");

  SELECT T0."ItemCode"
  FROM OITM T0
    INNER JOIN OITW T1 ON T0."ItemCode" = T1."ItemCode"
  WHERE "WhsCode" IN (SELECT "code" FROM :CODES_TABLE); -- line 10 where error occurs when using Hana ADO.NET

END;
#
```

<p>The above fails when through <code>Hana ADO.NET</code> with the error message: <code>sql syntax error: incorrect syntax near ")": line 10 col 54 (at pos 325)</code> but works when executed through <code>hdbsql</code>.</p>

<p><strong>Update</strong></p>

<p>The C# code that executes the query is fairly straight forward, but for completeness of troubleshooting effort I am including the interesting parts of our <code>HanaHelper</code> class. This code works successfully to execute 100s of queries a day without errors or problems. This is the first time where a variable of any type has been attempted to be declared or used in a query through this code and when the errors started showing up. As far as I can tell, the issue is tied to the use of the <code>:</code> when using the variable in the query.</p>

<pre class="lang-c# prettyprint-override"><code>public class HanaHelper
{
    public HanaConnection objConn = null;

    public HanaHelper(string ConnectionString)
    {
        try
        {
            objConn = new HanaConnection(ConnectionString);
        }
        catch (Exception e)
        {
            Console.WriteLine(@"Exception thrown by HanaConnection: {0}\n{1}", e.Message, e.InnerException);
        }
    }

    public DataSet GetData(string strSQL)
    {
        using (HanaCommand objCmd = new HanaCommand(strSQL, objConn))
        {
            using (HanaDataAdapter objDA = new HanaDataAdapter(objCmd))
            {
                DataSet objDS = new DataSet();
                try
                {
                    objDA.Fill(objDS);
                }
                catch (Exception)
                {
                    throw;
                }
                finally
                {
                  // do something interesting regardless of success or failure
                }
                objConn.Close();
                return objDS;
            }
        }
    }
}
</code>```

Any clue here why the same query works through hdbsql but fails when executing through Hana ADO.NET?

Update

I figured out how to use HanaSQLTrace in the C# code so that I can inspect the prepared query text and viola, the source of error messages becomes apparent, all occurrences of ":VARNAME" are replaced with "?       " (a ? replaces the : and a space for each character in the variable name). I suppose it is trying to pre-substitute occurrences of : with a ? as if there were parameters to be substituted.

How can this behavior be disabled, or worked with, or worked around so that I can use variables in a query in Hana ADO.NET effectively?

答:
Updated based on the OP feedback.

To refer to a variable (in order to access its value(s)) in SQLScript it's
necessary to put a colon : in front of the variable name.

The main issue, however, turns out to be the declaration of the CODES_TABLE table variable.
With HANA 2 SPS 4 the error message is

```<code>`SAP DBTech JDBC: [264]: invalid datatype: unknown type SYSTEM.TABLE: line 5 col 23`
</code>```

This points to the declaration of the TABLE typed variable CODES_TABLE which lacks the definition of what columns should be in the table.

Adding this fixes the issue.

With these changes, your code should work:

```<code>DO
BEGIN

  DECLARE CODES_ARRAY NVARCHAR(100) ARRAY = ARRAY('01','02','03','04');
  DECLARE CODES_TABLE TABLE ("code" NVARCHAR(100)) = UNNEST(:CODES_ARRAY) AS ("code");
  --                        ^^^^^^^^^^^^^^^^^^^^^^
  --                                     |
  ---------------------------------------+

  SELECT
        T0."ItemCode"
  FROM
               OITM T0
    INNER JOIN OITW T1
      ON T0."ItemCode" = T1."ItemCode"
  WHERE
        "WhsCode" IN (SELECT "code" FROM :CODES_TABLE);
  --                                     ^
  --                                     |
  ---------------------------------------+
END;
</code>```

An alternative option to declare and assign the table variable is to not use the DECLARE command.

```<code>DO
BEGIN

  DECLARE CODES_ARRAY NVARCHAR(100) ARRAY = ARRAY('01','02','03','04');

  CODES_TABLE = UNNEST(:CODES_ARRAY) AS ("code");

  SELECT
        T0."ItemCode"
  FROM
               OITM T0
    INNER JOIN OITW T1
      ON T0."ItemCode" = T1."ItemCode"
  WHERE
        "WhsCode" IN (SELECT "code" FROM :CODES_TABLE);

END;
</code>```

Body:
I am trying to add a declared variable to replace a hardcoded list of values in a "where in" clause.
Researching how Hana handles array variables it seems like I can do this by declaring an array and then either using a select directly on it or by unnesting it first into a table but I keep getting errors I can't resolve.

When I try it this way:

DO
BEGIN

  DECLARE CODES_ARRAY NVARCHAR(100) ARRAY = ARRAY('01','02','03','04');

  SELECT T0."ItemCode"
  FROM OITM T0
    INNER JOIN OITW T1 ON T0."ItemCode" = T1."ItemCode"
  WHERE "WhsCode" IN (SELECT "code" FROM :CODES_ARRAY); -- line 9 where error occurs

END;

I get this error message sql syntax error: incorrect syntax near ")": line 9 col 54 (at pos 239)

I can't figure out what the syntax error resolution is.

So then I tried inserting a declared table variable like this:

DO
BEGIN

  DECLARE CODES_ARRAY NVARCHAR(100) ARRAY = ARRAY('01','02','03','04');
  DECLARE CODES_TABLE TABLE = UNNEST(:CODES_ARRAY) AS ("code"); -- line 5 where error occurs

  SELECT T0."ItemCode"
  FROM OITM T0
    INNER JOIN OITW T1 ON T0."ItemCode" = T1."ItemCode"
  WHERE "WhsCode" IN (SELECT "code" FROM CODES_TABLE); -- I know : is missing here but when adding, the same error from previous block shows up

END;

and I get this error message: identifier must be declared: 1: line 5 col 38 (at pos 123)

As far as I can tell the array variable is declared as it should be so I don't know how to resolve the error.

I've read the SAP Hana SQL Reference documentation (for array/table variables, unnest function, etc.) over and over and it seems like I've got everything setup correctly but can't figure out these errors. I would like to be able to use both of these approaches at different times if possible (the "array variable to table variable" and the "array variable only" approaches)

I don't know exactly what is going on here, but one thing I notice that the two different error messages referenced in my post (see difference from errors in the first two code blocks) is that each error is occurring either immediately before the use of the variable with the : (in the case of the UNNEST) or immediately following the variable with the : (in the case of using in the SELECT * FROM in the query).

Because of that, I wondered if the issue is "upstream" at the Hana ADO.NET application query preparation and execution call level, but I ran a test and when I double checked the query string just before it is executed, it appears unchanged and the variables with : still look as they should, so at least as far as just before execution through Hana ADO.NET HanaCommand it looks correct - but once executing the query using HanaDataReader or HanaDataAdapter it returns the error messages referred to above. It may be a red herring to chase the problem from the Hana ADO.NET level but don't know what else to do.

Update

To further troubleshoot, I tried executing this code block below using hdbsql.exe -n XXX.XXX.XXX.XXX:30015 -u XXX -p XXX -m -I "c:\temp\test.sql" -c "#" and it works! So, the errors I see only show up when executing the same query through the Hana ADO.NET interface.

DO
BEGIN

  DECLARE CODES_ARRAY NVARCHAR(10) ARRAY = ARRAY('01','02','03','04');
  DECLARE CODES_TABLE TABLE ("code" NVARCHAR(10)) = UNNEST(:CODES_ARRAY) AS ("code");

  SELECT T0."ItemCode"
  FROM OITM T0
    INNER JOIN OITW T1 ON T0."ItemCode" = T1."ItemCode"
  WHERE "WhsCode" IN (SELECT "code" FROM :CODES_TABLE); -- line 10 where error occurs when using Hana ADO.NET

END;
#

The above fails when through Hana ADO.NET with the error message: sql syntax error: incorrect syntax near ")": line 10 col 54 (at pos 325) but works when executed through hdbsql.

Update

The C# code that executes the query is fairly straight forward, but for completeness of troubleshooting effort I am including the interesting parts of our HanaHelper class. This code works successfully to execute 100s of queries a day without errors or problems. This is the first time where a variable of any type has been attempted to be declared or used in a query through this code and when the errors started showing up. As far as I can tell, the issue is tied to the use of the : when using the variable in the query.

public class HanaHelper
{
    public HanaConnection objConn = null;

    public HanaHelper(string ConnectionString)
    {
        try
        {
            objConn = new HanaConnection(ConnectionString);
        }
        catch (Exception e)
        {
            Console.WriteLine(@"Exception thrown by HanaConnection: {0}\n{1}", e.Message, e.InnerException);
        }
    }

    public DataSet GetData(string strSQL)
    {
        using (HanaCommand objCmd = new HanaCommand(strSQL, objConn))
        {
            using (HanaDataAdapter objDA = new HanaDataAdapter(objCmd))
            {
                DataSet objDS = new DataSet();
                try
                {
                    objDA.Fill(objDS);
                }
                catch (Exception)
                {
                    throw;
                }
                finally
                {
                  // do something interesting regardless of success or failure
                }
                objConn.Close();
                return objDS;
            }
        }
    }
}

Any clue here why the same query works through hdbsql but fails when executing through Hana ADO.NET?

Update

I figured out how to use HanaSQLTrace in the C# code so that I can inspect the prepared query text and viola, the source of error messages becomes apparent, all occurrences of ":VARNAME" are replaced with "?       " (a ? replaces the : and a space for each character in the variable name). I suppose it is trying to pre-substitute occurrences of : with a ? as if there were parameters to be substituted.

How can this behavior be disabled, or worked with, or worked around so that I can use variables in a query in Hana ADO.NET effectively?

Body:
Updated based on the OP feedback.

To refer to a variable (in order to access its value(s)) in SQLScript it's
necessary to put a colon : in front of the variable name.

The main issue, however, turns out to be the declaration of the CODES_TABLE table variable.
With HANA 2 SPS 4 the error message is

`SAP DBTech JDBC: [264]: invalid datatype: unknown type SYSTEM.TABLE: line 5 col 23`

This points to the declaration of the TABLE typed variable CODES_TABLE which lacks the definition of what columns should be in the table.

Adding this fixes the issue.

With these changes, your code should work:

DO
BEGIN

  DECLARE CODES_ARRAY NVARCHAR(100) ARRAY = ARRAY('01','02','03','04');
  DECLARE CODES_TABLE TABLE ("code" NVARCHAR(100)) = UNNEST(:CODES_ARRAY) AS ("code");
  --                        ^^^^^^^^^^^^^^^^^^^^^^
  --                                     |
  ---------------------------------------+

  SELECT
        T0."ItemCode"
  FROM
               OITM T0
    INNER JOIN OITW T1
      ON T0."ItemCode" = T1."ItemCode"
  WHERE
        "WhsCode" IN (SELECT "code" FROM :CODES_TABLE);
  --                                     ^
  --                                     |
  ---------------------------------------+
END;

An alternative option to declare and assign the table variable is to not use the DECLARE command.

DO
BEGIN

  DECLARE CODES_ARRAY NVARCHAR(100) ARRAY = ARRAY('01','02','03','04');

  CODES_TABLE = UNNEST(:CODES_ARRAY) AS ("code");

  SELECT
        T0."ItemCode"
  FROM
               OITM T0
    INNER JOIN OITW T1
      ON T0."ItemCode" = T1."ItemCode"
  WHERE
        "WhsCode" IN (SELECT "code" FROM :CODES_TABLE);

END;


问:
RBAC in multi tenant microservices
I am part of development of multi-tenant cloud SaaS.
Currently we have around 15 micro services.
We are using mongo as backend with db per tenant as tenancy sepration.
We are now trying to design rbac for the complete platform.
Below are the questions I have regarding the same.

Should i have a central authz micro-service for manage my rbac autz ?
   a. With this if authz service fails all micro-services are affected, and platform is prone or unusable.(bad)
   b. Service will store roles/permissions for all the resources across the micro-services.(good)
   c. For every request that comes to api gw post auth will go to authz and before calling micro-service it can be rejected.(good)

Should i have a side car for each micro-service as my autz
  No single point of failure ... if authz fails for some service other service can continue to work.(good)
  Every service will have its on permissions ..(good)
  Auth service can store role and group info for permission it has to reach to individual service for its management (permission CRUD).(bad)
  Authz evaluation happens at individual service level.(not sure)

Any other approach ?

Thanks
Jeet

答:
I would like to choose the below solution

The API Gateway does the basic authentication check (token validity, tenant identification etc, client id validation etc), if any sanity check fails, returns a 401 from here

In the individual Microservice, we will have a middleware that intercepts the requests and checks for the right permission against the resource (entity) that is being operated upon, incase of a lack of permission, let the microservice return a 403 from here.

Title: RBAC in multi tenant microservices


问:
Swift -Frame dimensions for portrait video
If I want to display a 16:9 horizontal video inside a cell I use the dimensions:

```<code>let videoHeight = self.frame.size.width * 9 / 16

contentView.addSubview(thumbnailImageView)
thumbnailImageView.heightAnchor.constraint(equalToConstant: videoHeight).isActive = true
thumbnailImageView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor).isActive = true
thumbnailImageView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor).isActive = true

// In the cv's sizeForItem I set the same height
let width = collectionView.frame.width
let videoHeight: CGFloat = width * 9 / 16
return CGSize(width: width, height: videoHeight)
</code>```

which will give me a horizontal cell:

That work's fine if the video is in a 16:9 but if the user recorded the video in portrait the video thumbnail is in the middle of the view with the black sides.

In a situation like this, when it's a portrait video, I want to adjust the cell so that it supports a portrait video to give me something like what all the social networks are currently using for portrait (I only need 1 cell, this is just a screenshot of a example of a portrait cell):

I know how to set up the cell but I don't know what dimensions to use for a portrait video:

For example I find out if the video is portrait:

```<code>guard let videoTrack = AVAsset(url: videoUrl).tracks(withMediaType: AVMediaType.video).first else { return }
let transformedVideoSize = videoTrack.naturalSize.applying(videoTrack.preferredTransform)
let videoIsPortrait = abs(transformedVideoSize.width) < abs(transformedVideoSize.height)

var videoHeight = self.frame.size.width * 9 / 16 // dimension for horizontal video
if videoIsPortrait {

    videoHeight = // dimension for portrait video ???
    videoWidth = // not sure if this is necessary
}

thumbnailImageView.heightAnchor.constraint(equalToConstant: videoHeight).isActive = true
thumbnailImageView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor).isActive = true
// if a width is necessary I set it otherwise I just use the trailing anchor

// I do the same thing inside sizeForItem to adjust to the portrait height (and width if necessary)
</code>```

What are the dimensions for a portrait video?

答:
Using this blog post that said the iPhone vertical aspect ratio (the dimensions for a portrait video) is 9:16 and this answer I did this for 2 columns:

```<code>func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

    let widthForTwoColumnCells = collectionView.frame.width / 2

    let insideRect = CGRect(x: 0, y: 0, width: widthForTwoColumnCells, height: .infinity)
    let rect = AVMakeRect(aspectRatio: CGSize(width: 9, height: 16), insideRect: insideRect)

    let videoHeight: CGFloat = rect.size.height

    return CGSize(width: widthForTwoColumnCells, height: videoHeight)
}
</code>```

Body:
If I want to display a 16:9 horizontal video inside a cell I use the dimensions:

let videoHeight = self.frame.size.width * 9 / 16

contentView.addSubview(thumbnailImageView)
thumbnailImageView.heightAnchor.constraint(equalToConstant: videoHeight).isActive = true
thumbnailImageView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor).isActive = true
thumbnailImageView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor).isActive = true

// In the cv's sizeForItem I set the same height
let width = collectionView.frame.width
let videoHeight: CGFloat = width * 9 / 16
return CGSize(width: width, height: videoHeight)

which will give me a horizontal cell:

That work's fine if the video is in a 16:9 but if the user recorded the video in portrait the video thumbnail is in the middle of the view with the black sides.

In a situation like this, when it's a portrait video, I want to adjust the cell so that it supports a portrait video to give me something like what all the social networks are currently using for portrait (I only need 1 cell, this is just a screenshot of a example of a portrait cell):

I know how to set up the cell but I don't know what dimensions to use for a portrait video:

For example I find out if the video is portrait:

guard let videoTrack = AVAsset(url: videoUrl).tracks(withMediaType: AVMediaType.video).first else { return }
let transformedVideoSize = videoTrack.naturalSize.applying(videoTrack.preferredTransform)
let videoIsPortrait = abs(transformedVideoSize.width) < abs(transformedVideoSize.height)

var videoHeight = self.frame.size.width * 9 / 16 // dimension for horizontal video
if videoIsPortrait {

    videoHeight = // dimension for portrait video ???
    videoWidth = // not sure if this is necessary
}

thumbnailImageView.heightAnchor.constraint(equalToConstant: videoHeight).isActive = true
thumbnailImageView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor).isActive = true
// if a width is necessary I set it otherwise I just use the trailing anchor

// I do the same thing inside sizeForItem to adjust to the portrait height (and width if necessary)

What are the dimensions for a portrait video?

Body:
Using this blog post that said the iPhone vertical aspect ratio (the dimensions for a portrait video) is 9:16 and this answer I did this for 2 columns:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

    let widthForTwoColumnCells = collectionView.frame.width / 2

    let insideRect = CGRect(x: 0, y: 0, width: widthForTwoColumnCells, height: .infinity)
    let rect = AVMakeRect(aspectRatio: CGSize(width: 9, height: 16), insideRect: insideRect)

    let videoHeight: CGFloat = rect.size.height

    return CGSize(width: widthForTwoColumnCells, height: videoHeight)
}


问:
Getting the CORS policy: No 'Access-Control-Allow-Origin' error
I am trying to integrate a third party API using JavaScript and its working fine on local but it is showing the error on live i.e.

```<code>Access to XMLHttpRequest at 'https://newsapi.org/v2/top-headlines?country=in&category=technology' from origin 'https://www.example.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
</code>```

Here is my JavaScript,

```<code>var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        var myObj, i, x = "";
        myObj = JSON.parse(this.response);

        for (i=0;i<1;i++ in myObj.articles) {

            x += "<a href="+ myObj.articles[i].url +" target='blank'>";
            x += "<div style='background: linear-gradient(rgba(0,130,170,0),rgba(6,23,0,1)), url( "+ myObj.articles[i].urlToImage +" );height: 430px;margin-top: 20px;'>";
            x += "</div>";
            x += "</a>";

        }

        document.getElementById("technology").innerHTML = x;

    }
};

xmlhttp.open("GET", "https://newsapi.org/v2/top-headlines?country=in&category=technology", true);
xmlhttp.send();
</code>```

HTML

```<code><div style="background-color: gray;height: 430px;margin-top: 20px;">
   p id="technology"></p>
</div>
</code>```

I don't understand why this is happening.

Please help me out,
Thanks in advance.

答:
As mentioned by @chris-g you are not using api-key. You might try with API key and perhaps CORS issue would be gone.
If you are still getting CORS, try simple jquery $ajax with jsonp or try a simple proxy server to forward the request and response.

Body:
I am trying to integrate a third party API using JavaScript and its working fine on local but it is showing the error on live i.e.

Access to XMLHttpRequest at 'https://newsapi.org/v2/top-headlines?country=in&category=technology' from origin 'https://www.example.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Here is my JavaScript,

var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        var myObj, i, x = "";
        myObj = JSON.parse(this.response);

        for (i=0;i<1;i++ in myObj.articles) {

            x += "";
            x += "
";
            x += "
";
            x += "";

        }

        document.getElementById("technology").innerHTML = x;

    }
};

xmlhttp.open("GET", "https://newsapi.org/v2/top-headlines?country=in&category=technology", true);
xmlhttp.send();

HTML

   p id="technology">

I don't understand why this is happening.

Please help me out,
Thanks in advance.


问:
Get Specific JSON Object by ID from array and return the JSON object (Javascript/JQuery)
I am trying to pull a specific JSON object from an array of objects using JavaScript. Here is my JSON:

```<code>"Awards": [
   {
     "Award1": {
        "title": "Award1 Title",
        "recipient": "John Doe",
        "description": "Blah Blah Blah"
     }
   },
   {
     "Award2": {
        "title": "Award2 Title",
        "recipient": "Tom White",
        "description": "Blah Blah Blah"
     }
   },
   {
      "Award3": {
         "title": "Award3 Title",
         "recipient": "Will Biggs",
         "description": "Blah Blah Blah"
      }
   }
]
</code>```

What I want to be able to do is create a function that takes in the data and an id, finds the object in the array and returns the object as a whole. For example if I search for Award1, I want it to return:

```<code>var obj = {
 "title": "Award1 Title",
 "recipient": "John Doe",
 "description": "Blah Blah Blah"
}
</code>```

So then I could access the data like so:

```<code>obj.recipient // Which would return John Doe
</code>```

Ideas?

答:
This should do the trick:

```<code>var obj=Awards['Award1'];
</code>```

But keep in mind that this will only be a referenced copy, i. e. changes to obj will also happen to the original Awards object.

There is not really a need to create a function for it, but of course, you can do that too:

```<code>function getObj(parent,key){
  return parent[key];
}

var obj=getObj (Awards,'Award1');
</code>```

Body:
I am trying to pull a specific JSON object from an array of objects using JavaScript. Here is my JSON:

"Awards": [
   {
     "Award1": {
        "title": "Award1 Title",
        "recipient": "John Doe",
        "description": "Blah Blah Blah"
     }
   },
   {
     "Award2": {
        "title": "Award2 Title",
        "recipient": "Tom White",
        "description": "Blah Blah Blah"
     }
   },
   {
      "Award3": {
         "title": "Award3 Title",
         "recipient": "Will Biggs",
         "description": "Blah Blah Blah"
      }
   }
]

What I want to be able to do is create a function that takes in the data and an id, finds the object in the array and returns the object as a whole. For example if I search for Award1, I want it to return:

var obj = {
 "title": "Award1 Title",
 "recipient": "John Doe",
 "description": "Blah Blah Blah"
}

So then I could access the data like so:

obj.recipient // Which would return John Doe

Ideas?

Body:
This should do the trick:

var obj=Awards['Award1'];

But keep in mind that this will only be a referenced copy, i. e. changes to obj will also happen to the original Awards object.

There is not really a need to create a function for it, but of course, you can do that too:

function getObj(parent,key){
  return parent[key];
}

var obj=getObj (Awards,'Award1');


问:
Wordpress Woocommerce Show attributes on shop page
I want to add some attributes to the shop page of wordpress.
This code i found on Stackoverflow, is shows all attribute labes but on all the same attribute names.

```<code>add_action('woocommerce_after_shop_loop_item_title','add_attribute');
function add_attribute() {
global $product;

$product_attributes = array( 'pa_country','pa_class','pa_faction','pa_gender' );
$attr_output = array();

foreach( $product_attributes as $taxonomy ){
    if( taxonomy_exists($taxonomy) ){
        $label_name = get_taxonomy( $taxonomy )->labels->singular_name;
        $value = $product->get_attribute('pa_country','pa_class','pa_faction','pa_gender');

        if( ! empty($value) ){

            $attr_output[] = '<span class="'.$taxonomy.'">'.$label_name.': '.$value.'</span>';
        }
    }}

echo '<div class="product-attributes">'.implode( '<br>', $attr_output ).'</div>';
</code>```

}

current state

I just need a bit help to get it to show all the right attributes.

答:
I solved the problem. its not pretty but it works.</p>

```<code>add_action( 'woocommerce_after_shop_loop_item_title', 'display_size_attribute', 5 );
function display_size_attribute() {
global $product;
if ( $product->is_type('simple') ) {
    $taxonomy = 'pa_country';
    echo '<span class="attribute-s">Country: ' . $product->get_attribute($taxonomy) . '</span>','<br>';
}
 if ( $product->is_type('simple') ) {
    $taxonomy = 'pa_class';
    echo '<span class="attribute-s">Class: ' . $product->get_attribute($taxonomy) . '</span>','<br>';
}
 if ( $product->is_type('simple') ) {
    $taxonomy = 'pa_faction';
    echo '<span class="attribute-s">Faction: ' . $product->get_attribute($taxonomy) . '</span>','<br>';
}
 if ( $product->is_type('simple') ) {
    $taxonomy = 'pa_gender';
    echo '<span class="attribute-s">Gender: ' . $product->get_attribute($taxonomy) . '</span>','<br>';
}}
</code>```

Body:
I want to add some attributes to the shop page of wordpress.
This code i found on Stackoverflow, is shows all attribute labes but on all the same attribute names.

add_action('woocommerce_after_shop_loop_item_title','add_attribute');
function add_attribute() {
global $product;

$product_attributes = array( 'pa_country','pa_class','pa_faction','pa_gender' );
$attr_output = array();

foreach( $product_attributes as $taxonomy ){
    if( taxonomy_exists($taxonomy) ){
        $label_name = get_taxonomy( $taxonomy )->labels->singular_name;
        $value = $product->get_attribute('pa_country','pa_class','pa_faction','pa_gender');

        if( ! empty($value) ){

            $attr_output[] = ''.$label_name.': '.$value.'';
        }
    }}

echo '
'.implode( '
', $attr_output ).'
';

}

current state

I just need a bit help to get it to show all the right attributes.

Body:
I solved the problem. its not pretty but it works.

add_action( 'woocommerce_after_shop_loop_item_title', 'display_size_attribute', 5 );
function display_size_attribute() {
global $product;
if ( $product->is_type('simple') ) {
    $taxonomy = 'pa_country';
    echo '<span class="attribute-s">Country: ' . $product->get_attribute($taxonomy) . '</span>','<br>';
}
 if ( $product->is_type('simple') ) {
    $taxonomy = 'pa_class';
    echo '<span class="attribute-s">Class: ' . $product->get_attribute($taxonomy) . '</span>','<br>';
}
 if ( $product->is_type('simple') ) {
    $taxonomy = 'pa_faction';
    echo '<span class="attribute-s">Faction: ' . $product->get_attribute($taxonomy) . '</span>','<br>';
}
 if ( $product->is_type('simple') ) {
    $taxonomy = 'pa_gender';
    echo '<span class="attribute-s">Gender: ' . $product->get_attribute($taxonomy) . '</span>','<br>';
}}


问:
Calculating Intrinsic Estimation Error and Extrinsic Error in Camera Calibration using a sequence of images using OpenCv
Well, given a sequence of 2d image points for N images and a single set of 3d object points, calibration can be done for a single camera using

```<code>double calibrateCamera(InputArrayOfArrays objectPoints, InputArrayOfArrays
imagePoints, Size imageSize, InputOutputArray cameraMatrix,
InputOutputArray distCoeffs, OutputArrayOfArrays rvecs,
OutputArrayOfArrays tvecs, int flags=0,
TermCriteria criteria=TermCriteria( TermCriteria::COUNT+TermCriteria::EPS, 30, DBL_EPSILON) )
</code>```

Well, this function returns 3x3 Camera Matrix(Intrinsic parameters like focal length, principal points) and various extrinsic parameters like distortion coefficients and rotation vector,etc.

If i wish to estimate Errors for all intrinsic and extrinsic parameters obtained using the above function, what should be the procedure? Basicalluy, what is the way to obtain Calibration Errors in opencv. Any help would be appreciated.

答: Using the newly obtained calibration parameter, project the 3d object point to the image plane and calculate the distance of each projected point with the detected 2d points</p>

Body:
Well, given a sequence of 2d image points for N images and a single set of 3d object points, calibration can be done for a single camera using

double calibrateCamera(InputArrayOfArrays objectPoints, InputArrayOfArrays
imagePoints, Size imageSize, InputOutputArray cameraMatrix,
InputOutputArray distCoeffs, OutputArrayOfArrays rvecs,
OutputArrayOfArrays tvecs, int flags=0,
TermCriteria criteria=TermCriteria( TermCriteria::COUNT+TermCriteria::EPS, 30, DBL_EPSILON) )

Well, this function returns 3x3 Camera Matrix(Intrinsic parameters like focal length, principal points) and various extrinsic parameters like distortion coefficients and rotation vector,etc.

If i wish to estimate Errors for all intrinsic and extrinsic parameters obtained using the above function, what should be the procedure? Basicalluy, what is the way to obtain Calibration Errors in opencv. Any help would be appreciated.


问:
state variable scope no access react timeInterval
I am trying to access to intervalId "useState" variable inside of a timeInterval function. But the scope is not working properly. intervalId is always null inside ot the timeInterval function, that means that it does not about delay of value assignation.

```<code>    export function useLocalCommands(length, id) {
    const [intervalId, setIntervalId] = useState(null)
    const [currentIndex, setCurrentIndex] = useState(10)
    const [timeInterval, setTimeInterval] = useState(Constants.READING.READING_TIME_INTERVAL)

    let pauseReading = () => {
        console.log("pause:" + intervalId)
        clearInterval(intervalId)
    }

    let startReading = () => {
        console.log("play")
        pauseReading()
        if (currentIndex < length) {
            setIntervalId(setInterval(() => {
                setCurrentIndex((index) => {
                    if (index < length) {
                        if (id && index % 40 === 0) {
                            Meteor.call('myBooks.updateIndex', id, index, (err, res) => {
                                // show a toast if err
                            })
                        }
                        return index + 1
                    } else {
                        console.log("pauseReading: " + intervalId)
                        pauseReading();
                    }
                })
            }, timeInterval))

        }
    }
}
</code>```

Thanks you,
Best.

答:
IntervalId is being used from closure which is why when the setInterval runs, the values being takes at the time of declaration. However setIntervalId triggeres a state update and even though the value of state is updated, your timerId within setInterval function continues to point to the old state that it used from closure.

Instead of using state, you can make use of useRef to store the timerId. Since refs are mutated, they aren't affected by closure

```<code>export function useLocalCommands(length, id) {
    const intervalId = useRef(null)
    const [currentIndex, setCurrentIndex] = useState(10)
    const [timeInterval, setTimeInterval] = useState(Constants.READING.READING_TIME_INTERVAL)

    let pauseReading = () => {
        console.log("pause:" + intervalId.current)
        clearInterval(intervalId.current)
    }

    let startReading = () => {
        console.log("play")
        pauseReading()
        if (currentIndex < length) {
            intervalId.current = setInterval(() => {
                setCurrentIndex((index) => {
                    if (index < length) {
                        if (id && index % 40 === 0) {
                            Meteor.call('myBooks.updateIndex', id, index, (err, res) => {
                                // show a toast if err
                            })
                        }
                        return index + 1
                    } else {
                        console.log("pauseReading: " + intervalId.current)
                        pauseReading();
                    }
                })
            }, timeInterval);

        }
    }
}
</code>```

Body:
I am trying to access to intervalId "useState" variable inside of a timeInterval function. But the scope is not working properly. intervalId is always null inside ot the timeInterval function, that means that it does not about delay of value assignation.

    export function useLocalCommands(length, id) {
    const [intervalId, setIntervalId] = useState(null)
    const [currentIndex, setCurrentIndex] = useState(10)
    const [timeInterval, setTimeInterval] = useState(Constants.READING.READING_TIME_INTERVAL)

    let pauseReading = () => {
        console.log("pause:" + intervalId)
        clearInterval(intervalId)
    }

    let startReading = () => {
        console.log("play")
        pauseReading()
        if (currentIndex < length) {
            setIntervalId(setInterval(() => {
                setCurrentIndex((index) => {
                    if (index < length) {
                        if (id && index % 40 === 0) {
                            Meteor.call('myBooks.updateIndex', id, index, (err, res) => {
                                // show a toast if err
                            })
                        }
                        return index + 1
                    } else {
                        console.log("pauseReading: " + intervalId)
                        pauseReading();
                    }
                })
            }, timeInterval))

        }
    }
}

Thanks you,
Best.

Body:
IntervalId is being used from closure which is why when the setInterval runs, the values being takes at the time of declaration. However setIntervalId triggeres a state update and even though the value of state is updated, your timerId within setInterval function continues to point to the old state that it used from closure.

Instead of using state, you can make use of useRef to store the timerId. Since refs are mutated, they aren't affected by closure

export function useLocalCommands(length, id) {
    const intervalId = useRef(null)
    const [currentIndex, setCurrentIndex] = useState(10)
    const [timeInterval, setTimeInterval] = useState(Constants.READING.READING_TIME_INTERVAL)

    let pauseReading = () => {
        console.log("pause:" + intervalId.current)
        clearInterval(intervalId.current)
    }

    let startReading = () => {
        console.log("play")
        pauseReading()
        if (currentIndex < length) {
            intervalId.current = setInterval(() => {
                setCurrentIndex((index) => {
                    if (index < length) {
                        if (id && index % 40 === 0) {
                            Meteor.call('myBooks.updateIndex', id, index, (err, res) => {
                                // show a toast if err
                            })
                        }
                        return index + 1
                    } else {
                        console.log("pauseReading: " + intervalId.current)
                        pauseReading();
                    }
                })
            }, timeInterval);

        }
    }
}


问:
Mobx observe property of object in observe array
I have 2 class:

class Account {
  games: Game[];
}

class Game {
  id: number;
  active: boolean;
}
```

<p>And observable array of accounts.</p>

<p>I need to change property <code>active</code> in game using checkbox. But when I change <code>active</code> my react component will not update.</p>

<pre class="lang-js prettyprint-override"><code>interface GameListProps {
  games: Game[];
}

@observer
class GameList extends Component<GameListProps> {
  render() {
    return (
      <div>
        {Array.map((game) => (
          <div>
            <input
              type="checkbox"
              checked={game.active}
              onChange={(event) => {
                game.active = event.target.checked;
              }}
            />
          </div>
        ))}
      </div>
    );
  }
}
</code>```

How can I change active with updating react component?

Can I create array of checed games but use active for checked?

@observer
class GameList extends Component<GameListProps> {
  @ovservable checkedGames: number[];

  handleCheck(gameId: number, checked: boolean) {
    this.props.games.find((game) => game.id === gameId).active = cheched;
    if (checked) {
      this.checkedGames.push(gameId);
    } else {
      let findIndex = this.checkedGames.indexOf(gameId);
      if (findIndex !== -1) {
        this.checkedGames.splice(this.checkedGames.indexOf(gameId), 1);
      }
    }
  }

  render() {
    return (

        {Array.map((game) => (

            <input
              type="checkbox"
              checked={game.active}
              onChange={(event) => {
                this.handleCheck(game.id, event.target.checked);
              }}
            />

        ))}

    );
  }
}
```

I think that it is not good because we change props. But we need game property active for init state of checkbox.

答:
You should mark active property on the Game class as observable.

class Game {
  id: number;
  @observable active: boolean;
  // --^
}
```

Body:
I have 2 class:

class Account {
  games: Game[];
}

class Game {
  id: number;
  active: boolean;
}

And observable array of accounts.

I need to change property active in game using checkbox. But when I change active my react component will not update.

interface GameListProps {
  games: Game[];
}

@observer
class GameList extends Component<GameListProps> {
  render() {
    return (

        {Array.map((game) => (

            <input
              type="checkbox"
              checked={game.active}
              onChange={(event) => {
                game.active = event.target.checked;
              }}
            />

        ))}

    );
  }
}

How can I change active with updating react component?

Can I create array of checed games but use active for checked?

@observer
class GameList extends Component<GameListProps> {
  @ovservable checkedGames: number[];

  handleCheck(gameId: number, checked: boolean) {
    this.props.games.find((game) => game.id === gameId).active = cheched;
    if (checked) {
      this.checkedGames.push(gameId);
    } else {
      let findIndex = this.checkedGames.indexOf(gameId);
      if (findIndex !== -1) {
        this.checkedGames.splice(this.checkedGames.indexOf(gameId), 1);
      }
    }
  }

  render() {
    return (

        {Array.map((game) => (

            <input
              type="checkbox"
              checked={game.active}
              onChange={(event) => {
                this.handleCheck(game.id, event.target.checked);
              }}
            />

        ))}

    );
  }
}

I think that it is not good because we change props. But we need game property active for init state of checkbox.


问:
Calling stored procedure with return value
I am trying to call a stored procedure from my C# windows application. The stored procedure is running on a local instance of SQL Server 2008. I am able to call the stored procedure but I am not able to retrieve the value back from the stored procedure. This stored procedure is supposed to return the next number in the sequence. I have done research online and all the sites I've seen have pointed to this solution working.

Stored procedure code:

```<code>ALTER procedure [dbo].[usp_GetNewSeqVal]
      @SeqName nvarchar(255)
as
begin
      declare @NewSeqVal int
      set NOCOUNT ON
      update AllSequences
      set @NewSeqVal = CurrVal = CurrVal+Incr
      where SeqName = @SeqName

      if @@rowcount = 0 begin
print 'Sequence does not exist'
            return
      end

      return @NewSeqVal
end
</code>```

Code calling the stored procedure:

```<code>SqlConnection conn = new SqlConnection(getConnectionString());
conn.Open();

SqlCommand cmd = new SqlCommand(parameterStatement.getQuery(), conn);
cmd.CommandType = CommandType.StoredProcedure;

SqlParameter param = new SqlParameter();

param = cmd.Parameters.Add("@SeqName", SqlDbType.NVarChar);
param.Direction = ParameterDirection.Input;
param.Value = "SeqName";

SqlDataReader reader = cmd.ExecuteReader();
</code>```

I have also tried using a DataSet to retrieve the return value with the same result. What am I missing to get
the return value from my stored procedure? If more information is needed, please let me know.

答: You can try using an output parameter. http://msdn.microsoft.com/en-us/library/ms378108.aspx</p>

Body:
I am trying to call a stored procedure from my C# windows application. The stored procedure is running on a local instance of SQL Server 2008. I am able to call the stored procedure but I am not able to retrieve the value back from the stored procedure. This stored procedure is supposed to return the next number in the sequence. I have done research online and all the sites I've seen have pointed to this solution working.

Stored procedure code:

ALTER procedure [dbo].[usp_GetNewSeqVal]
      @SeqName nvarchar(255)
as
begin
      declare @NewSeqVal int
      set NOCOUNT ON
      update AllSequences
      set @NewSeqVal = CurrVal = CurrVal+Incr
      where SeqName = @SeqName

      if @@rowcount = 0 begin
print 'Sequence does not exist'
            return
      end

      return @NewSeqVal
end

Code calling the stored procedure:

SqlConnection conn = new SqlConnection(getConnectionString());
conn.Open();

SqlCommand cmd = new SqlCommand(parameterStatement.getQuery(), conn);
cmd.CommandType = CommandType.StoredProcedure;

SqlParameter param = new SqlParameter();

param = cmd.Parameters.Add("@SeqName", SqlDbType.NVarChar);
param.Direction = ParameterDirection.Input;
param.Value = "SeqName";

SqlDataReader reader = cmd.ExecuteReader();

I have also tried using a DataSet to retrieve the return value with the same result. What am I missing to get
the return value from my stored procedure? If more information is needed, please let me know.


问:
How can I use the files in the project files?
I make an object detection application with OpenCV in Android studio. I use yolo for object detection. I get the necessary yolo files from the phone's memory.

```<code>String tinyCfg =  Environment.getExternalStorageDirectory() + "/dnns/yolov3-tiny.cfg";
String tinyWeights = Environment.getExternalStorageDirectory() + "/dnns/yolov3-tiny.weights";
tinyYolo = Dnn.readNetFromDarknet(tinyCfg, tinyWeights);
</code>```

I want to transfer these files to application files and use them from there. I am using this code for this.

```<code>String tinyCfg = "dnns/yolov3-tiny.cfg";
String tinyWeights = "dnns/yolov3-tiny.weights";
tinyYolo = Dnn.readNetFromDarknet(tinyCfg, tinyWeights);
</code>```

enter image description here

But I get this error

```<code>E/cv::error(): OpenCV(3.4.5) Error: Parsing error (Failed to parse NetParameter file: dnns/yolov3-tiny.cfg) in cv::dnn::experimental_dnn_34_v11::Net cv::dnn::experimental_dnn_34_v11::readNetFromDarknet(const cv::String&, const cv::String&), file /build/3_4_pack-android/opencv/modules/dnn/src/darknet/darknet_importer.cpp, line 207
E/org.opencv.dnn: dnn::readNetFromDarknet_10() caught cv::Exception: OpenCV(3.4.5) /build/3_4_pack-android/opencv/modules/dnn/src/darknet/darknet_importer.cpp:207: error: (-212:Parsing error) Failed to parse NetParameter file: dnns/yolov3-tiny.cfg in function 'cv::dnn::experimental_dnn_34_v11::Net cv::dnn::experimental_dnn_34_v11::readNetFromDarknet(const cv::String&, const cv::String&)'
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.vision, PID: 26157
    CvException [org.opencv.core.CvException: cv::Exception: OpenCV(3.4.5) /build/3_4_pack-android/opencv/modules/dnn/src/darknet/darknet_importer.cpp:207: error: (-212:Parsing error) Failed to parse NetParameter file: dnns/yolov3-tiny.cfg in function 'cv::dnn::experimental_dnn_34_v11::Net cv::dnn::experimental_dnn_34_v11::readNetFromDarknet(const cv::String&, const cv::String&)']
</code>```

答:
If you want to put files directly in your app package you should put them in the assets or the raw resource folder (here is a question for comparison).
Then you can access them by AssetManager or Resources.openRawResource() or using an appropriate Uri.

I don't know whether or not the readNetFromDarknet can accept InputStreams.

If true, the you can use AssetManager.open("dnns/yolov3-tiny.cfg") or Resources.openRawResource(your_resource_id) to get the stream.

If not, if it accepts Uri as input you can use file:///android_asset/dnns/yolov3-tiny.cfg or
android.resource://[package]/[res type]/[res name] (based on this) to locate the files.

If non of those, you can copy them to your app files directory and then give the path to the function.

If you don't know how to put files in assets folder check this.

Body:
I make an object detection application with OpenCV in Android studio. I use yolo for object detection. I get the necessary yolo files from the phone's memory.

String tinyCfg =  Environment.getExternalStorageDirectory() + "/dnns/yolov3-tiny.cfg";
String tinyWeights = Environment.getExternalStorageDirectory() + "/dnns/yolov3-tiny.weights";
tinyYolo = Dnn.readNetFromDarknet(tinyCfg, tinyWeights);

I want to transfer these files to application files and use them from there. I am using this code for this.

String tinyCfg = "dnns/yolov3-tiny.cfg";
String tinyWeights = "dnns/yolov3-tiny.weights";
tinyYolo = Dnn.readNetFromDarknet(tinyCfg, tinyWeights);

enter image description here

But I get this error

E/cv::error(): OpenCV(3.4.5) Error: Parsing error (Failed to parse NetParameter file: dnns/yolov3-tiny.cfg) in cv::dnn::experimental_dnn_34_v11::Net cv::dnn::experimental_dnn_34_v11::readNetFromDarknet(const cv::String&, const cv::String&), file /build/3_4_pack-android/opencv/modules/dnn/src/darknet/darknet_importer.cpp, line 207
E/org.opencv.dnn: dnn::readNetFromDarknet_10() caught cv::Exception: OpenCV(3.4.5) /build/3_4_pack-android/opencv/modules/dnn/src/darknet/darknet_importer.cpp:207: error: (-212:Parsing error) Failed to parse NetParameter file: dnns/yolov3-tiny.cfg in function 'cv::dnn::experimental_dnn_34_v11::Net cv::dnn::experimental_dnn_34_v11::readNetFromDarknet(const cv::String&, const cv::String&)'
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.vision, PID: 26157
    CvException [org.opencv.core.CvException: cv::Exception: OpenCV(3.4.5) /build/3_4_pack-android/opencv/modules/dnn/src/darknet/darknet_importer.cpp:207: error: (-212:Parsing error) Failed to parse NetParameter file: dnns/yolov3-tiny.cfg in function 'cv::dnn::experimental_dnn_34_v11::Net cv::dnn::experimental_dnn_34_v11::readNetFromDarknet(const cv::String&, const cv::String&)']


问:
Git authentication fails after enabling 2FA
I just enabled 2FA (I can't think of any other changes I made) and git asked for my username and password. I provided both, but they were "wrong". I tried many of the solutions here: Git push requires username and password but that didn't work. In particular, when switching from https to ssh, the ssh key gives

Permission denied (publickey).
fatal: Could not read from remote repository.

```<code>$ git push
warning: push.default is unset; its implicit value is changing in
Git 2.0 from 'matching' to 'simple'. To squelch this message
and maintain the current behavior after the default changes, use:

  git config --global push.default matching

To squelch this message and adopt the new behavior now, use:

  git config --global push.default simple

See 'git help config' and search for 'push.default' for further information.
(the 'simple' mode was introduced in Git 1.7.11. Use the similar mode
'current' instead of 'simple' if you sometimes use older versions of Git)

Username for 'https://github.com': **********
Password for 'https://mlbileschi@github.com':
remote: Invalid username or password.
fatal: Authentication failed for 'https://github.com/mlbileschi/scala.git/'
</code>```

Any tips?

答:
I was facing this problem on existing repo when I enabled 2FA(two factor authentication) for one of my private repos.
I was able to solve it following below steps on my ubuntu 19.0 terminal:-

Add your ssh key to github so that you dont need to use your password again,as now you have enabled 2FA.Visit github page to know how to do it easily.

Once key is added, go to your terminal, and update the origin url

git remote set-url origin git@github.com:<USERNAME>/<BRANCH-NAME>

Thats it.Hope it helps

Body:
I just enabled 2FA (I can't think of any other changes I made) and git asked for my username and password. I provided both, but they were "wrong". I tried many of the solutions here: Git push requires username and password but that didn't work. In particular, when switching from https to ssh, the ssh key gives

Permission denied (publickey).
fatal: Could not read from remote repository.

$ git push
warning: push.default is unset; its implicit value is changing in
Git 2.0 from 'matching' to 'simple'. To squelch this message
and maintain the current behavior after the default changes, use:

  git config --global push.default matching

To squelch this message and adopt the new behavior now, use:

  git config --global push.default simple

See 'git help config' and search for 'push.default' for further information.
(the 'simple' mode was introduced in Git 1.7.11. Use the similar mode
'current' instead of 'simple' if you sometimes use older versions of Git)

Username for 'https://github.com': **********
Password for 'https://mlbileschi@github.com':
remote: Invalid username or password.
fatal: Authentication failed for 'https://github.com/mlbileschi/scala.git/'

Any tips?


问:
Can an android app copy contacts with read contact permissions?
So there's an app that asks permission to read contacts. It's needs this access to check phone numbers against it's own member list. No problem with that.

This works by an option "add from contacts" where you pick a contact and the app checks whether that contact is a member by the phone number and reports accordingly in a pop up. Is or isn't a member.

Someone used an android proxy and captured the app traffic and discovered the app was posting the entire contacts list with ALL fields even email and postal addresses to it's servers.

My question is does allowing the app to read contacts by extension allow it to copy contacts?

答: Yes, absolutely, how an app works is that there's a database of contacts on the phone, when you give it the permission to read contacts, basically you give it access to the database, and it can without anything to stop it, do whatever it wants with it.</p>


答:
Finds the first object that contains the property key=Award1 and returns it.

const findKey = (list, key)=>(list.find(obj=>obj[key])||{})[key]

data = {
"Awards": [
   {
     "Award1": {
        "title": "Award1 Title",
        "recipient": "John Doe",
        "description": "Blah Blah Blah"
     }
   },
   {
     "Award2": {
        "title": "Award2 Title",
        "recipient": "Tom White",
        "description": "Blah Blah Blah"
     }
   },
   {
      "Award3": {
         "title": "Award3 Title",
         "recipient": "Will Biggs",
         "description": "Blah Blah Blah"
      }
   }
]
}

console.log(data.Awards.find(obj=>obj["Award1"]))

let key = "Award1"
console.log(data.Awards.find(obj=>obj[key])[key].title)

console.log(
findKey(data.Awards,'Award1')
)

console.log(
findKey(data.Awards,'Award2')
)

console.log(
findKey(data.Awards,'Award3')
)```

Title: Get Specific JSON Object by ID from array and return the JSON object (Javascript/JQuery)


问:
from collections import defaultdict
why is it when I do not set default value of defaultdict to be zero (int), my below program does not give me results:

```<code>>>> doc
'A wonderful serenity has taken possession of my entire soul, like these sweet mornings of spring which I enjoy with my whole heart. I am alone, and feel the charm of existence in this spot, which was created for the bliss of souls like mine. I am so happy'
>>> some = defaultdict()
>>> for i in doc.split():
...  some[i] = some[i]+1
...
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
KeyError: 'A'
>>> some
defaultdict(None, {})
>>> i
'A'
</code>```

yet it works with a default value

```<code>>>> some = defaultdict(int)
>>> for i in doc.split():
...  some[i] = some[i]+1
...
>>> some
defaultdict(<class 'int'>, {'A': 1, 'wonderful': 1, 'serenity': 1, 'has': 1, 'taken': 1, 'possession': 1, 'of': 4, 'my': 2, 'entire': 1, 'soul,': 1, 'like': 2, 'these': 1, 'sweet': 1, 'mornings': 1, 'spring': 1, 'which': 2, 'I': 3, 'enjoy': 1, 'with': 1, 'whole': 1, 'heart.': 1, 'am': 2, 'alone,': 1, 'and': 1, 'feel': 1, 'the': 2, 'charm': 1, 'existence': 1, 'in': 1, 'this': 1, 'spot,': 1, 'was': 1, 'created': 1, 'for': 1, 'bliss': 1, 'souls': 1, 'mine.': 1, 'so': 1, 'happy': 1})
>>>
</code>```

Could you tell why does it work like thus?

答:
As the documentation says:

The first argument provides the initial value for the default_factory
  attribute; it defaults to None. All remaining arguments are treated
  the same as if they were passed to the dict constructor, including
  keyword arguments.

Therefore, if you just write defaultdict without passing any value to the constructor, the default value is set to None
See the output:

```<code>some = defaultdict()
print(some)    # defaultdict(None, {})
</code>```

And when the value is set to None, you can not execute: some[i] = some[i]+1.

Thus, you have to set the default value to int explicitly: some = defaultdict(int)

Title: from collections import defaultdict

Body:
why is it when I do not set default value of defaultdict to be zero (int), my below program does not give me results:

>>> doc
'A wonderful serenity has taken possession of my entire soul, like these sweet mornings of spring which I enjoy with my whole heart. I am alone, and feel the charm of existence in this spot, which was created for the bliss of souls like mine. I am so happy'
>>> some = defaultdict()
>>> for i in doc.split():
...  some[i] = some[i]+1
...
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
KeyError: 'A'
>>> some
defaultdict(None, {})
>>> i
'A'

yet it works with a default value

>>> some = defaultdict(int)
>>> for i in doc.split():
...  some[i] = some[i]+1
...
>>> some
defaultdict(<class 'int'>, {'A': 1, 'wonderful': 1, 'serenity': 1, 'has': 1, 'taken': 1, 'possession': 1, 'of': 4, 'my': 2, 'entire': 1, 'soul,': 1, 'like': 2, 'these': 1, 'sweet': 1, 'mornings': 1, 'spring': 1, 'which': 2, 'I': 3, 'enjoy': 1, 'with': 1, 'whole': 1, 'heart.': 1, 'am': 2, 'alone,': 1, 'and': 1, 'feel': 1, 'the': 2, 'charm': 1, 'existence': 1, 'in': 1, 'this': 1, 'spot,': 1, 'was': 1, 'created': 1, 'for': 1, 'bliss': 1, 'souls': 1, 'mine.': 1, 'so': 1, 'happy': 1})
>>>

Could you tell why does it work like thus?

Body:
As the documentation says:

The first argument provides the initial value for the default_factory
  attribute; it defaults to None. All remaining arguments are treated
  the same as if they were passed to the dict constructor, including
  keyword arguments.

Therefore, if you just write defaultdict without passing any value to the constructor, the default value is set to None
See the output:

some = defaultdict()
print(some)    # defaultdict(None, {})

And when the value is set to None, you can not execute: some[i] = some[i]+1.

Thus, you have to set the default value to int explicitly: some = defaultdict(int)