问:
Native Tongue as Default Language For an Application
When downloading both Firefox and Chrome, I've noticed that the default version I got was in my native tongue of Hebrew. I personally don't like my applications in Hebrew, since I'm used to the English UI conventions embedded in me since long ago by:

The lack of choice: Most programs don't offer interfaces in multiple languages and when they do, those languages are usually English and the developer's native tongue.

Programming languages which are almost completely bound to the English language.

My question then is this:

If you translate your applications, would you limit the UI to the user's native tongue or give them the choice by enabling more than one language pack by default?

Which language would your application default to (which is interesting mostly if you only install one language pack with your application)?

And also generally I'd like to know how much value do you put into translating your applications on a whole.

答:
I usually try to ship products with all available sets of localized resources.  Upon a user's first launch of the product, the UI is presented in the localization most closely matching the OS on their machine. Once within the app, the user has the option of switching the UI to one of the other available localizations.

I think it is very important to provide localizations that match one's target markets.  Most "normal" people (not software developers!) prefer by far to have a UI in their native language.

OwnerDisplayName: Omer van Kloeten

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Paul Lalonde


来源: stackexchange

问:
How can I programmatically obtain an image's REAL URL/Path?
To clarify the title question, I have code such as:

```<code><img src='gallery/main.php?g2_view=core.DownloadItem&g2_itemId=8161&g2_serialNumber=2&g2_GALLERYSID=5b24df90ee45f0e01795a3c01a1d634b'>
</code>```

with the file actually residing in the file system under my webroot. Is there any way in PHP to retrieve the images real path being served such as:

```<code><img src='images/gallery/album1/file1.jpg'>
</code>```

Eg someFunction(longURL) ==> images/gallery/album1/file1.jpg

Thank you,

答:
I'm quite sure, Gallery2 (which you are apparently using) has an internal method for this - at least it does this resolving at some place.
You'd have to find that piece of code and could either use it directly (if it's e.g. a static method) or abstract it from there.

You may want to ask on the Gallery2 forums - it may even have been answered there already.

Using Google Codesearch, I've found that main.php appears to have the code to do this already:

```<code>$path = GalleryDataCache::getCachePath(
    array('type' => 'fast-download', 'itemId' => $itemId));
</code>```

$path appears to be a file, which, when included provides maybe the vars you'll need.

OwnerDisplayName: barfoon

Body:
To clarify the title question, I have code such as:

with the file actually residing in the file system under my webroot. Is there any way in PHP to retrieve the images real path being served such as:

Eg someFunction(longURL) ==> images/gallery/album1/file1.jpg

Thank you,

LastEditorDisplayName: Martin Meredith

Body:
I'm quite sure, Gallery2 (which you are apparently using) has an internal method for this - at least it does this resolving at some place.
You'd have to find that piece of code and could either use it directly (if it's e.g. a static method) or abstract it from there.

You may want to ask on the Gallery2 forums - it may even have been answered there already.

Using Google Codesearch, I've found that main.php appears to have the code to do this already:

$path = GalleryDataCache::getCachePath(
    array('type' => 'fast-download', 'itemId' => $itemId));

$path appears to be a file, which, when included provides maybe the vars you'll need.

OwnerDisplayName: blueyed


问:
Dynamics in .NET 4.0: am I doing it right?
Yesterday I wrote my first lines of code using the new dynamic type in .NET 4.0. The scenario where I found this useful is as follows:

I have a class holding several lists of values. This can be List<string>, List<bool>, List<int> or really any kind of list. The way these are used, is that I add a value to one or more of these lists. Then I "synchronize" them, so that they all end up the same length (those too short are filled with a default value). And then I continue to add more values, sync again etc. The goal is that the item at any index in one of the lists are related to an item at the same index in another list. (Yes, this could probably be better solved by wrapping all this in another class, but that's not the point in this case.)

I have this construct in a couple of classes, so I wanted to make this synchronizing of the lists as generic as possible. But since the inner type of the lists might vary, this wasn't as straight forward as I first had thought. But, enter the hero of the day: dynamics :)

I wrote the following helper class that can take a collection of lists (of any type) together with a default value for each list:

```<code>using System;
using System.Collections.Generic;
using System.Linq;

namespace Foo.utils
{
    public class ListCollectionHelper
    {
        /// <summary>
        /// Takes a collection of lists and synchronizes them so that all of the lists are the same length (matching
        /// the length of the longest list present in the parameter).
        ///
        /// It is assumed that the dynamic type in the enumerable is of the type Tuple<ICollection<T>, T>, i.e. a
        /// list of tuples where Item1 is the list itself, and Item2 is the default value (to fill the list with). In
        /// each tuple, the type T must be the same for the list and the default value, but between the tuples the type
        /// might vary.
        /// </summary>
        /// <param name="listCollection">A collection of tuples with a List<T> and a default value T</param>
        /// <returns>The length of the lists after the sync (length of the longest list before the sync)</returns>
        public static int SyncListLength(IEnumerable<dynamic> listCollection)
        {
            int maxNumberOfItems = LengthOfLongestList(listCollection);
            PadListsWithDefaultValue(listCollection, maxNumberOfItems);
            return maxNumberOfItems;
        }

        private static int LengthOfLongestList(IEnumerable<dynamic> listCollection)
        {
            return listCollection.Aggregate(0, (current, tuple) => Math.Max(current, tuple.Item1.Count));
        }

        private static void PadListsWithDefaultValue(IEnumerable<dynamic> listCollection, int maxNumberOfItems)
        {
            foreach (dynamic tuple in listCollection)
            {
                FillList(tuple.Item1, tuple.Item2, maxNumberOfItems);
            }
        }

        private static void FillList<T>(ICollection<T> list, T fillValue, int maxNumberOfItems)
        {
            int itemsToAdd = maxNumberOfItems - list.Count;

            for (int i = 0; i < itemsToAdd; i++)
            {
                list.Add(fillValue);
            }
        }
    }
}
</code>```

And below is a short set of unit tests I used to verify that I ended up with the desired behaviour:

```<code>using System;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Foo.utils;

namespace Foo.UnitTests
{
    [TestClass]
    public class DynamicListSync
    {
        private readonly List<string> stringList = new List<string>();
        private readonly List<bool> boolList = new List<bool>();
        private readonly List<string> stringListWithCustomDefault = new List<string>();
        private readonly List<int> intList = new List<int>();

        private readonly List<dynamic> listCollection = new List<dynamic>();

        private const string FOO = "bar";

        [TestInitialize]
        public void InitTest()
        {
            listCollection.Add(Tuple.Create(stringList, default(String)));
            listCollection.Add(Tuple.Create(boolList, default(Boolean)));
            listCollection.Add(Tuple.Create(stringListWithCustomDefault, FOO));
            listCollection.Add(Tuple.Create(intList, default(int)));
        }

        [TestMethod]
        public void SyncEmptyLists()
        {
            Assert.AreEqual(0, ListCollectionHelper.SyncListLength(listCollection));
        }

        [TestMethod]
        public void SyncWithOneListHavingOneItem()
        {
            stringList.Add("one");
            Assert.AreEqual(1, ListCollectionHelper.SyncListLength(listCollection));

            Assert.AreEqual("one", stringList[0]);
            Assert.AreEqual(default(Boolean), boolList[0]);
            Assert.AreEqual(FOO, stringListWithCustomDefault[0]);
            Assert.AreEqual(default(int), intList[0]);
        }

        [TestMethod]
        public void SyncWithAllListsHavingSomeItems()
        {
            stringList.Add("one");
            stringList.Add("two");
            stringList.Add("three");
            boolList.Add(false);
            boolList.Add(true);
            stringListWithCustomDefault.Add("one");

            Assert.AreEqual(3, ListCollectionHelper.SyncListLength(listCollection));

            Assert.AreEqual("one", stringList[0]);
            Assert.AreEqual("two", stringList[1]);
            Assert.AreEqual("three", stringList[2]);

            Assert.AreEqual(false, boolList[0]);
            Assert.AreEqual(true, boolList[1]);
            Assert.AreEqual(default(Boolean), boolList[2]);

            Assert.AreEqual("one", stringListWithCustomDefault[0]);
            Assert.AreEqual(FOO, stringListWithCustomDefault[1]);
            Assert.AreEqual(FOO, stringListWithCustomDefault[2]);

            Assert.AreEqual(default(int), intList[0]);
            Assert.AreEqual(default(int), intList[1]);
            Assert.AreEqual(default(int), intList[2]);
        }
    }
}
</code>```

So, since this is my first shot at dynamics (both in C# and anywhere else really...), I just wanted to ask if I'm doing this right. Obviously the code works as intended, but is this the right way of doing it? Are there any obvious optimizations or pitfalls I'm missing etc?

答:
I don't think this is a solution for dynamic. Dynamic is useful when you need to work with a bunch of different types conditionally. If this is a string, do something, if it's an int, do something else, if its a Puppy class instance, call bark(). dynamic frees you from having to litter code like this with tons of type casting or ugly generics. Uses for dynamic and other advanced language features are meant for code generators, interpreters etc...

It's a cool feature, but unless your talking to a dynamic language or COM interop, it's only meant for when you have a nasty advanced problem.

ContentLicense: CC BY-SA 3.0

Body:
Yesterday I wrote my first lines of code using the new dynamic type in .NET 4.0. The scenario where I found this useful is as follows:

I have a class holding several lists of values. This can be List<string>, List<bool>, List<int> or really any kind of list. The way these are used, is that I add a value to one or more of these lists. Then I "synchronize" them, so that they all end up the same length (those too short are filled with a default value). And then I continue to add more values, sync again etc. The goal is that the item at any index in one of the lists are related to an item at the same index in another list. (Yes, this could probably be better solved by wrapping all this in another class, but that's not the point in this case.)

I have this construct in a couple of classes, so I wanted to make this synchronizing of the lists as generic as possible. But since the inner type of the lists might vary, this wasn't as straight forward as I first had thought. But, enter the hero of the day: dynamics :)

I wrote the following helper class that can take a collection of lists (of any type) together with a default value for each list:

using System;
using System.Collections.Generic;
using System.Linq;

namespace Foo.utils
{
    public class ListCollectionHelper
    {
        ///
        /// Takes a collection of lists and synchronizes them so that all of the lists are the same length (matching
        /// the length of the longest list present in the parameter).
        ///
        /// It is assumed that the dynamic type in the enumerable is of the type Tuple<ICollection<T>, T>, i.e. a
        /// list of tuples where Item1 is the list itself, and Item2 is the default value (to fill the list with). In
        /// each tuple, the type T must be the same for the list and the default value, but between the tuples the type
        /// might vary.
        ///
        /// <param name="listCollection">A collection of tuples with a List<T> and a default value T</param>
        /// <returns>The length of the lists after the sync (length of the longest list before the sync)</returns>
        public static int SyncListLength(IEnumerable<dynamic> listCollection)
        {
            int maxNumberOfItems = LengthOfLongestList(listCollection);
            PadListsWithDefaultValue(listCollection, maxNumberOfItems);
            return maxNumberOfItems;
        }

        private static int LengthOfLongestList(IEnumerable<dynamic> listCollection)
        {
            return listCollection.Aggregate(0, (current, tuple) => Math.Max(current, tuple.Item1.Count));
        }

        private static void PadListsWithDefaultValue(IEnumerable<dynamic> listCollection, int maxNumberOfItems)
        {
            foreach (dynamic tuple in listCollection)
            {
                FillList(tuple.Item1, tuple.Item2, maxNumberOfItems);
            }
        }

        private static void FillList<T>(ICollection<T> list, T fillValue, int maxNumberOfItems)
        {
            int itemsToAdd = maxNumberOfItems - list.Count;

            for (int i = 0; i < itemsToAdd; i++)
            {
                list.Add(fillValue);
            }
        }
    }
}

And below is a short set of unit tests I used to verify that I ended up with the desired behaviour:

using System;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Foo.utils;

namespace Foo.UnitTests
{
    [TestClass]
    public class DynamicListSync
    {
        private readonly List<string> stringList = new List<string>();
        private readonly List<bool> boolList = new List<bool>();
        private readonly List<string> stringListWithCustomDefault = new List<string>();
        private readonly List<int> intList = new List<int>();

        private readonly List<dynamic> listCollection = new List<dynamic>();

        private const string FOO = "bar";

        [TestInitialize]
        public void InitTest()
        {
            listCollection.Add(Tuple.Create(stringList, default(String)));
            listCollection.Add(Tuple.Create(boolList, default(Boolean)));
            listCollection.Add(Tuple.Create(stringListWithCustomDefault, FOO));
            listCollection.Add(Tuple.Create(intList, default(int)));
        }

        [TestMethod]
        public void SyncEmptyLists()
        {
            Assert.AreEqual(0, ListCollectionHelper.SyncListLength(listCollection));
        }

        [TestMethod]
        public void SyncWithOneListHavingOneItem()
        {
            stringList.Add("one");
            Assert.AreEqual(1, ListCollectionHelper.SyncListLength(listCollection));

            Assert.AreEqual("one", stringList[0]);
            Assert.AreEqual(default(Boolean), boolList[0]);
            Assert.AreEqual(FOO, stringListWithCustomDefault[0]);
            Assert.AreEqual(default(int), intList[0]);
        }

        [TestMethod]
        public void SyncWithAllListsHavingSomeItems()
        {
            stringList.Add("one");
            stringList.Add("two");
            stringList.Add("three");
            boolList.Add(false);
            boolList.Add(true);
            stringListWithCustomDefault.Add("one");

            Assert.AreEqual(3, ListCollectionHelper.SyncListLength(listCollection));

            Assert.AreEqual("one", stringList[0]);
            Assert.AreEqual("two", stringList[1]);
            Assert.AreEqual("three", stringList[2]);

            Assert.AreEqual(false, boolList[0]);
            Assert.AreEqual(true, boolList[1]);
            Assert.AreEqual(default(Boolean), boolList[2]);

            Assert.AreEqual("one", stringListWithCustomDefault[0]);
            Assert.AreEqual(FOO, stringListWithCustomDefault[1]);
            Assert.AreEqual(FOO, stringListWithCustomDefault[2]);

            Assert.AreEqual(default(int), intList[0]);
            Assert.AreEqual(default(int), intList[1]);
            Assert.AreEqual(default(int), intList[2]);
        }
    }
}

So, since this is my first shot at dynamics (both in C# and anywhere else really...), I just wanted to ask if I'm doing this right. Obviously the code works as intended, but is this the right way of doing it? Are there any obvious optimizations or pitfalls I'm missing etc?


问:
dpinst fails to install driver silently
I use Inno Setup installer to install my Win32 application, it is installed mainly on Windows 10. There is a driver for some USB dongle (basically it is USB serial port) to be installed together with my app. The driver consists of files and directories:

```<code>amd64 (folder)
x86 (folder)
dfu.cat
dfu.inf
usbserial.cat
usbserial.inf
</code>```

I added dpinst32.exe and dpinst64.exe to the driver's folder and I call dpinst32 or dpinst64 (based on Windows version) from my installer.

However, on some PCs I end with drivers not installed.

What is the correct way to install drivers by my installer?

EDIT: This is log from dpinst64.exe /Q /c

```<code>INFO:   Option set: dumping log info to console.
INFO:   Current working directory: 'F:\windrv'
INFO:   Running on path 'F:\windrv'
INFO:   No valid 'dpinst.xml' file provided.
INFO:   Install option set: Running in quiet mode. Suppressing Wizard and OS popups.
INFO:   Found driver package: 'F:\windrv\dfu.inf'.
INFO:   Found driver package: 'F:\windrv\usbserial.inf'.
INFO:   Preinstalling 'f:\windrv\dfu.inf' ...
INFO:   ENTER:  DriverPackagePreinstallW
INFO:   RETURN: DriverPackagePreinstallW  (0xE0000242)
INFO:   Preinstalling 'f:\windrv\usbserial.inf' ...
INFO:   ENTER:  DriverPackagePreinstallW
INFO:   RETURN: DriverPackagePreinstallW  (0xE0000242)
INFO:   Returning with code 0x80020000
</code>```

答:
The /S Option of Dpinst completely hides all interaction with the operating System. The Problem you are having is that your operating System does not trust the manufacturer yet and does not complete the Installation. If you run Dpinst with the Parameter /SW for example you will see this window.

That will be the reason why the Installation works on some Computers and on some other not.

One solution is to extract the certificates for your Drivers, call certmgr.msc from the console and check under "Trusted Publishers", you should find the manufacturer and with a Right click be able to export the certificate as a yourCert.cer file. You can then as Admin call certutil.exe -addstore "TrustedPublisher" yourCert.cer from the console before you call Dpinst /S on your target system.

As you already gave the operating System the certificate the window should not Pop up anymore and you can run dpinst completely silent.

ContentLicense: CC BY-SA 4.0

Title: dpinst fails to install driver silently

Body:
I use Inno Setup installer to install my Win32 application, it is installed mainly on Windows 10. There is a driver for some USB dongle (basically it is USB serial port) to be installed together with my app. The driver consists of files and directories:

amd64 (folder)
x86 (folder)
dfu.cat
dfu.inf
usbserial.cat
usbserial.inf

I added dpinst32.exe and dpinst64.exe to the driver's folder and I call dpinst32 or dpinst64 (based on Windows version) from my installer.

However, on some PCs I end with drivers not installed.

What is the correct way to install drivers by my installer?

EDIT: This is log from dpinst64.exe /Q /c

INFO:   Option set: dumping log info to console.
INFO:   Current working directory: 'F:\windrv'
INFO:   Running on path 'F:\windrv'
INFO:   No valid 'dpinst.xml' file provided.
INFO:   Install option set: Running in quiet mode. Suppressing Wizard and OS popups.
INFO:   Found driver package: 'F:\windrv\dfu.inf'.
INFO:   Found driver package: 'F:\windrv\usbserial.inf'.
INFO:   Preinstalling 'f:\windrv\dfu.inf' ...
INFO:   ENTER:  DriverPackagePreinstallW
INFO:   RETURN: DriverPackagePreinstallW  (0xE0000242)
INFO:   Preinstalling 'f:\windrv\usbserial.inf' ...
INFO:   ENTER:  DriverPackagePreinstallW
INFO:   RETURN: DriverPackagePreinstallW  (0xE0000242)
INFO:   Returning with code 0x80020000


问:
How to Cross Database Queries in Azure SQL with Same Table name and structure on both database
I need Ur help regarding Join query between two different Azure SQL database with same table name and same structure. Actually I have two different database with same table name and whole fields with different data.

I would like to Transfer the data from One database to another on Azure Sql or Join the table (both the table have the same name and structure).
For this I am using the "Elastic Database Query"

https://ppolyzos.com/2016/07/30/cross-database-queries-in-azure-sql-databases/

I am facing the error message while creating External Table “CREATE EXTERNAL TABLE [dbo].[Users]”

Error Message :-
"There is already an object named 'Users' in the database."

Sample Database 1st

[Test].[dbo].[Users]

```<code>CREATE TABLE [Users] (
  [UserGuid] uniqueidentifier NOT NULL
, [FirstName] nvarchar(90)  NOT NULL
, [LastName] nvarchar(90)  NOT NULL
, [UserID] nvarchar(50)  NOT NULL
, [PasswordSalt] nvarchar(90)  NOT NULL
, [Password] nvarchar(90)  NOT NULL
, [PasswordChanged] datetime NULL
, [UserName] nvarchar(50)  NOT NULL
);
</code>```

GO

Database 2nd
[TestAnother].[dbo].[Users]

```<code>CREATE TABLE [Users] (
  [UserGuid] uniqueidentifier NOT NULL
, [FirstName] nvarchar(90)  NOT NULL
, [LastName] nvarchar(90)  NOT NULL
, [UserID] nvarchar(50)  NOT NULL
, [PasswordSalt] nvarchar(90)  NOT NULL
, [Password] nvarchar(90)  NOT NULL
, [PasswordChanged] datetime NULL
, [UserName] nvarchar(50)  NOT NULL
);
GO
</code>```

I have written the Elastic Database Query as below :

```<code>Use TestAnother
Go

CREATE MASTER KEY ENCRYPTION BY PASSWORD = 'ABCmn!A4F43';

CREATE DATABASE SCOPED CREDENTIAL MyDbCredential
WITH IDENTITY = 'TestID',
SECRET = 'ABC9mn!A4F43';

CREATE EXTERNAL DATA SOURCE Connect2Test
WITH (
TYPE=RDBMS,
LOCATION='XXXX.database.windows.net',
DATABASE_NAME='Test',
CREDENTIAL= MyDbCredential,);

CREATE EXTERNAL TABLE [dbo].[Users] (
  [UserGuid] uniqueidentifier NOT NULL
, [FirstName] nvarchar(90)  NOT NULL
, [LastName] nvarchar(90)  NOT NULL
, [UserID] nvarchar(50)  NOT NULL
, [PasswordSalt] nvarchar(90)  NOT NULL
, [Password] nvarchar(90)  NOT NULL
, [PasswordChanged] datetime NULL
, [UserName] nvarchar(50)  NOT NULL
)
WITH (
        DATA_SOURCE = Connect2Test);
GO
</code>```

If I remove  or rename the Users table on "TestAnother" database then its work fine. But I wanna use the same Table name and structure.

How can I migrate the data from one table from One database to another table on other database and both the database table name and structure are same on Azure Sql environment.

答:
You need to create the external table with different name, and define its schema and real name in the create, bellow</p>

```<code>CREATE EXTERNAL TABLE [dbo].[ExternalUsers] (
  [UserGuid] uniqueidentifier NOT NULL
, [FirstName] nvarchar(90)  NOT NULL
, [LastName] nvarchar(90)  NOT NULL
, [UserID] nvarchar(50)  NOT NULL
, [PasswordSalt] nvarchar(90)  NOT NULL
, [Password] nvarchar(90)  NOT NULL
, [PasswordChanged] datetime NULL
, [UserName] nvarchar(50)  NOT NULL
)
WITH (
        DATA_SOURCE = Connect2Test,
SCHEMA_NAME = 'dbo',
 OBJECT_NAME = 'Users');
</code>```

Body:
I need Ur help regarding Join query between two different Azure SQL database with same table name and same structure. Actually I have two different database with same table name and whole fields with different data.

I would like to Transfer the data from One database to another on Azure Sql or Join the table (both the table have the same name and structure).
For this I am using the "Elastic Database Query"

https://ppolyzos.com/2016/07/30/cross-database-queries-in-azure-sql-databases/

I am facing the error message while creating External Table “CREATE EXTERNAL TABLE [dbo].[Users]”

Error Message :-
"There is already an object named 'Users' in the database."

Sample Database 1st

[Test].[dbo].[Users]

CREATE TABLE [Users] (
  [UserGuid] uniqueidentifier NOT NULL
, [FirstName] nvarchar(90)  NOT NULL
, [LastName] nvarchar(90)  NOT NULL
, [UserID] nvarchar(50)  NOT NULL
, [PasswordSalt] nvarchar(90)  NOT NULL
, [Password] nvarchar(90)  NOT NULL
, [PasswordChanged] datetime NULL
, [UserName] nvarchar(50)  NOT NULL
);

GO

Database 2nd
[TestAnother].[dbo].[Users]

CREATE TABLE [Users] (
  [UserGuid] uniqueidentifier NOT NULL
, [FirstName] nvarchar(90)  NOT NULL
, [LastName] nvarchar(90)  NOT NULL
, [UserID] nvarchar(50)  NOT NULL
, [PasswordSalt] nvarchar(90)  NOT NULL
, [Password] nvarchar(90)  NOT NULL
, [PasswordChanged] datetime NULL
, [UserName] nvarchar(50)  NOT NULL
);
GO

I have written the Elastic Database Query as below :

Use TestAnother
Go

CREATE MASTER KEY ENCRYPTION BY PASSWORD = 'ABCmn!A4F43';

CREATE DATABASE SCOPED CREDENTIAL MyDbCredential
WITH IDENTITY = 'TestID',
SECRET = 'ABC9mn!A4F43';

CREATE EXTERNAL DATA SOURCE Connect2Test
WITH (
TYPE=RDBMS,
LOCATION='XXXX.database.windows.net',
DATABASE_NAME='Test',
CREDENTIAL= MyDbCredential,);

CREATE EXTERNAL TABLE [dbo].[Users] (
  [UserGuid] uniqueidentifier NOT NULL
, [FirstName] nvarchar(90)  NOT NULL
, [LastName] nvarchar(90)  NOT NULL
, [UserID] nvarchar(50)  NOT NULL
, [PasswordSalt] nvarchar(90)  NOT NULL
, [Password] nvarchar(90)  NOT NULL
, [PasswordChanged] datetime NULL
, [UserName] nvarchar(50)  NOT NULL
)
WITH (
        DATA_SOURCE = Connect2Test);
GO

If I remove  or rename the Users table on "TestAnother" database then its work fine. But I wanna use the same Table name and structure.

How can I migrate the data from one table from One database to another table on other database and both the database table name and structure are same on Azure Sql environment.

Body:
You need to create the external table with different name, and define its schema and real name in the create, bellow

CREATE EXTERNAL TABLE [dbo].[ExternalUsers] (
  [UserGuid] uniqueidentifier NOT NULL
, [FirstName] nvarchar(90)  NOT NULL
, [LastName] nvarchar(90)  NOT NULL
, [UserID] nvarchar(50)  NOT NULL
, [PasswordSalt] nvarchar(90)  NOT NULL
, [Password] nvarchar(90)  NOT NULL
, [PasswordChanged] datetime NULL
, [UserName] nvarchar(50)  NOT NULL
)
WITH (
        DATA_SOURCE = Connect2Test,
SCHEMA_NAME = 'dbo',
 OBJECT_NAME = 'Users');


问:
How to access localhost from a Genymotion android emulator?
I can not figure out how to access localhost from a Genymotion android emulator. By the way, Im using MAMP.</p>

答:
In my case 10.0.3.2 didn't work. I changed to virtual box host-only network : 192.168.128.2 it works.
You have to try other virtualbox adapters IP if it doesn't work with 192.168.56.1.
My environment is behind a corporate proxy and I was running an embedded undertow server.
Hope it helps.</p>


问:
Unable to create superuser in cvat
I am able to build and run cvat tool. But when I trying to create a superuser then it is giving me below error.

ImportError: No module named 'gitdb.utils.compat'

I am running below command for creating a superuser.

docker exec -it cvat bash -ic 'python3 ~/manage.py createsuperuser'

Does anyone have any idea or suggestion for the above problem?

答:
This problem is most probably due to a newer gitdb2 python package.
If cvat is already built as a docker container, for testing, you must log into the container as root, uninstall it and install an older gitdb.

docker exec -it -u root cvat bash

pip3 uninstall gitdb2

pip3 install gitdb

Then, running python script must work. If that is the case, then a persistent solution is to rebuild the containers.

You need to edit Dockerfile as below:

# Install git application dependencies

...

fi

RUN pip3 uninstall -y gitdb2

RUN pip3 install --no-cache-dir gitdb

Run "docker-compose build".

Hope this helps.

Title: Unable to create superuser in cvat


问:
Dictionary<StudentType, List<Student>> to IDictionary<StudentType, IList<Student>>?
Please consider the following code:

```<code>class Student
{
}

enum StudentType
{
}

static void foo(IDictionary<StudentType, IList<Student>> students)
{
}

static void Main(string[] args)
{
    Dictionary<StudentType, List<Student>> studentDict =
                     new Dictionary<StudentType, List<Student>>();

    foo(studentDict);

    ...
}
</code>```

There is the error:

error CS1503: Argument '1': cannot
  convert from
  'System.Collections.Generic.Dictionary>'
  to
  'System.Collections.Generic.IDictionary>'

Is there any way to call foo function?

答:
You will have build a new dictionary with the right types, copying the data from the old one into the new one.

Or, you could change the original dictionary to be of the right type to begin with.

Either way, no, you can't cast the dictionary.

The reason for this limitation is as follows:

The dictionary contains values of type Student

You could have many types that implement IStudent

The method you're giving the cast'ed dictionary to could potentially try to stuff another IStudent into the dictionary, even if it isn't Student

Body:
Please consider the following code:

class Student
{
}

enum StudentType
{
}

static void foo(IDictionary<StudentType, IList<Student>> students)
{
}

static void Main(string[] args)
{
    Dictionary<StudentType, List<Student>> studentDict =
                     new Dictionary<StudentType, List<Student>>();

    foo(studentDict);

    ...
}

There is the error:

error CS1503: Argument '1': cannot
  convert from
  'System.Collections.Generic.Dictionary>'
  to
  'System.Collections.Generic.IDictionary>'

Is there any way to call foo function?


问:
"No such module" error when archiving
My Swift 4 app rebuilds and runs successfully on all simulators except for Generic iOS Device. If I try to archive it or do a rebuild on Generic iOS Device, I get a No such module error relating to one of my pod frameworks.

I tried adding the framework to Linked Frameworks and Libraries, and that removed the error, but then it fails on the next pod framework, and so on. I have tried all sorts of paths in Framework Search Paths with no luck.

Currently, the value is set to:

I even tried deleting the workspace, the pod lock file, and the pods folder, and then I did a pod install to rebuild everything. Again, it rebuilds clean on any simulator except the generic one. On the generic one, I get No such module on all import statements for pod frameworks.

Any suggestions appreciated, as this problem has me completely stalled, since I can't get a release out.

答: In my case, the module which couldn't be found was a dynamic Obj-C framework with a minimum deployment target higher than my application project's minimum deployment target. Bumping my minimum version fixed it, but you could drop the version on the framework instead.</p>

Title: "No such module" error when archiving


问:
Converting linq to non linq
Hi i've been woeking net 2 on visual studio 2008 .net 2 and seems my linq code won't work in here. I made a few search on internet but i dont see from linq to non linq.
Here's the code ive trying to convert.

var listWithoutCol = fmas.Select(x => new { x.NcrbNo, x.LotInfo, x.FailureMode, x.JobOwner, x.Status, x.Originator, x.DateCreated }).ToList();

The variable listWithoutCol will be used in exporting to excel.

Hope you underatand what i mean.

答:
Would suggest you to update to a newer version that supports linq.
But you can just create a new class:

```<code>class Job {
    public int NcrbNo; // use proper types.
    public int LotInfo;
    public int FailureMode;
    public int JobOwner;
    public int Status;
    public int Originator;
    public DateTime DateCreated;
}
</code>```

Then just use a foreach to iterate.

```<code>List<Job> listWithoutCol = new List<Job>();
foreach (FmasType element in fmas) { // Replace FmasType with the type it is.
    Job job = new Job();
    job.NcrbNo = element.NcrbNo;
    job.LotInfo = element.Lotinfo;
    job.FailureMode = element.FailureMode;
    job.JobOwner = element.JobOwner;
    //..etc..

    listWithoutCol.add(element);
}
</code>```

Title: Converting linq to non linq

Body:
Would suggest you to update to a newer version that supports linq.
But you can just create a new class:

class Job {
    public int NcrbNo; // use proper types.
    public int LotInfo;
    public int FailureMode;
    public int JobOwner;
    public int Status;
    public int Originator;
    public DateTime DateCreated;
}

Then just use a foreach to iterate.

List<Job> listWithoutCol = new List<Job>();
foreach (FmasType element in fmas) { // Replace FmasType with the type it is.
    Job job = new Job();
    job.NcrbNo = element.NcrbNo;
    job.LotInfo = element.Lotinfo;
    job.FailureMode = element.FailureMode;
    job.JobOwner = element.JobOwner;
    //..etc..

    listWithoutCol.add(element);
}


问:
iOS 13.2 MKTileOverlay occasionally won't render
I'm having an issue where in iOS 13.2 (probably also from iOS 13), loading offline map tile using MKTileOverlay occasionally won't be able to render, leaving the tile blank, there seems to be no issue with MKTileOverlay's subclass at all as it worked well in iOS 12 and below. I have 2 MKTileOverlay class (1 add grid and 1 load map tile file, default MKTileOverlay), both won't be able to load on that blank tile with default MKTileOverlayRenderer, other overlays seems to appear fine.

The issue seems to be resolved itself if I go to home screen and go back to the app, causing the tiles to reload. Is this a bug from iOS MapKit itself? Does anyone have temporary solution for this? Thank you.

Code for adding overlay:

```<code>let overlay = MKTileOverlay(urlTemplate: urlTemplate)
overlay.canReplaceMapContent = true
overlay.maximumZ = 19
mapView.insertOverlay(overlay, at: 0, level: .aboveLabels)
</code>```

Renderer:

```<code>func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
    if overlay is MKTileOverlay {
        let renderer = MKTileOverlayRenderer(tileOverlay: overlay as! MKTileOverlay)
        return renderer
    }

    return MKOverlayRenderer()
}
</code>```

答:
It is clearly a MapKit issue/bug.

I've also open a feedback ticket since the 9th of December 2020.

The root of this issue is not very sure.

MapKit and specially MKTileOverlay always had/have some issues with "heavy" tiles like PNG 24bit. When the MKTileOverlay use PNG (heavy tiles), the tiles sometimes are flashing and the map is continuously reloading especially with wide screens (iPad pro etc..)

So, since the JPEG tiles are often lighter than PNG, JPEG can be a workaround.

BUT, this new iOS 13.2+ issue is not the same! Random tiles are not rendered. If you remove and readd the MKTileOverlay or call the reloadData method of MKTileOverlayRenderer, the missing tiles will be rendered and it will be other random tiles that which be missing.

The real solution of the issue is to open a feedback ticket: https://feedbackassistant.apple.com

Edit: I've just tried to replace my 8bit PNG by 85% JPEG on the very simple MKTileOverlay project sample i've sent to Apple in my ticket. Same issue... no improvement.

Edit 2: Loading the NSData into an UIImage then using UIImageRepresentationJPEG seems to do the trick... Ugly...

```<code>- (void)loadTileAtPath:(MKTileOverlayPath)path result:(void (^)(NSData * _Nullable, NSError * _Nullable))result
{
    NSString *tilePath = [self PATHForTilePath:path];
    NSData *data = nil;

    if (![[NSFileManager defaultManager] fileExistsAtPath:tilePath])
    {
        NSLog(@"Z%ld/%ld/%ld does not exist!", path.z, path.x, path.y);
    }
    else
    {
        NSLog(@"Z%ld/%ld/%ld exist", path.z, path.x, path.y);

        UIImage *image = [UIImage imageWithContentsOfFile:tilePath];
        data = UIImageJPEGRepresentation(image, 0.8);
        // Instead of: data = [NSData dataWithContentsOfFile:tilePath];

        if (data == nil)
        {
            NSLog(@"Error!!! Unable to read an existing file!");
        }
    }

    dispatch_async(dispatch_get_main_queue(), ^{
        result(data, nil);
    });
}
</code>```

Body:
I'm having an issue where in iOS 13.2 (probably also from iOS 13), loading offline map tile using MKTileOverlay occasionally won't be able to render, leaving the tile blank, there seems to be no issue with MKTileOverlay's subclass at all as it worked well in iOS 12 and below. I have 2 MKTileOverlay class (1 add grid and 1 load map tile file, default MKTileOverlay), both won't be able to load on that blank tile with default MKTileOverlayRenderer, other overlays seems to appear fine.

The issue seems to be resolved itself if I go to home screen and go back to the app, causing the tiles to reload. Is this a bug from iOS MapKit itself? Does anyone have temporary solution for this? Thank you.

Code for adding overlay:

let overlay = MKTileOverlay(urlTemplate: urlTemplate)
overlay.canReplaceMapContent = true
overlay.maximumZ = 19
mapView.insertOverlay(overlay, at: 0, level: .aboveLabels)

Renderer:

func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
    if overlay is MKTileOverlay {
        let renderer = MKTileOverlayRenderer(tileOverlay: overlay as! MKTileOverlay)
        return renderer
    }

    return MKOverlayRenderer()
}

Body:
It is clearly a MapKit issue/bug.

I've also open a feedback ticket since the 9th of December 2020.

The root of this issue is not very sure.

MapKit and specially MKTileOverlay always had/have some issues with "heavy" tiles like PNG 24bit. When the MKTileOverlay use PNG (heavy tiles), the tiles sometimes are flashing and the map is continuously reloading especially with wide screens (iPad pro etc..)

So, since the JPEG tiles are often lighter than PNG, JPEG can be a workaround.

BUT, this new iOS 13.2+ issue is not the same! Random tiles are not rendered. If you remove and readd the MKTileOverlay or call the reloadData method of MKTileOverlayRenderer, the missing tiles will be rendered and it will be other random tiles that which be missing.

The real solution of the issue is to open a feedback ticket: https://feedbackassistant.apple.com

Edit: I've just tried to replace my 8bit PNG by 85% JPEG on the very simple MKTileOverlay project sample i've sent to Apple in my ticket. Same issue... no improvement.

Edit 2: Loading the NSData into an UIImage then using UIImageRepresentationJPEG seems to do the trick... Ugly...

- (void)loadTileAtPath:(MKTileOverlayPath)path result:(void (^)(NSData * _Nullable, NSError * _Nullable))result
{
    NSString *tilePath = [self PATHForTilePath:path];
    NSData *data = nil;

    if (![[NSFileManager defaultManager] fileExistsAtPath:tilePath])
    {
        NSLog(@"Z%ld/%ld/%ld does not exist!", path.z, path.x, path.y);
    }
    else
    {
        NSLog(@"Z%ld/%ld/%ld exist", path.z, path.x, path.y);

        UIImage *image = [UIImage imageWithContentsOfFile:tilePath];
        data = UIImageJPEGRepresentation(image, 0.8);
        // Instead of: data = [NSData dataWithContentsOfFile:tilePath];

        if (data == nil)
        {
            NSLog(@"Error!!! Unable to read an existing file!");
        }
    }

    dispatch_async(dispatch_get_main_queue(), ^{
        result(data, nil);
    });
}


问:
How do I extract a certain amount of lines after a pattern in perl?
Lets say I have a text file:

```<code>Line 1
Line 2
Target Name1
Line 3
Line 4
Line 5
Line 6
Target Name2
Line 7
Line 8
Line 9
Line 10
</code>```

I want to be able to search for a target pattern (there could be multiple in the text file like in example above) and then print out a certain amount of lines that is following it. Lets say 3 lines. So then the output I would want is

```<code>Target Name1
Line 3
Line 4
Line 5

Target Name2
Line 7
Line 8
Line 9
</code>```

So far all I have is code to find the target and print it out:

```<code>use strict;
use warning;
open (my $INFILE, $input_file);
my $outfile = "output.txt";
open (my $OUTFILE, '>', $outfile);

my $name;

while (my $line = <$INFILE>) {
  if ($line =~ m#TARGET\s+(\S+)#){
    $name = $1;
    print $OUTFILE "Target $name\n";
  }
}
</code>```

I am not sure how to print out the next 3 lines following Target. Note: Assume that the targets are always farther apart than 3 lines from each other. I think I would need a counter right?

答:
Yet another answer:

```<code>perl -ne 'print if /^Target\b/ and $l=$. or $. <= 3+$l&&$l' sample.txt
</code>```

This exploits that the special Perl variable $. has the current line number of the input.

If you're using Gnu/Linux or a similarly reasonable OS, then the grep command with a trailing context of 3 lines after matches is also an alternative. If you can bear to have -- separation lines between the matches:

```<code>grep -A3 Target sample.txt
grep -A3 '^Target ' sample.txt
grep -A3 -P '^Target\b' sample.txt
</code>```

Body:
Lets say I have a text file:

Line 1
Line 2
Target Name1
Line 3
Line 4
Line 5
Line 6
Target Name2
Line 7
Line 8
Line 9
Line 10

I want to be able to search for a target pattern (there could be multiple in the text file like in example above) and then print out a certain amount of lines that is following it. Lets say 3 lines. So then the output I would want is

Target Name1
Line 3
Line 4
Line 5

Target Name2
Line 7
Line 8
Line 9

So far all I have is code to find the target and print it out:

use strict;
use warning;
open (my $INFILE, $input_file);
my $outfile = "output.txt";
open (my $OUTFILE, '>', $outfile);

my $name;

while (my $line = <$INFILE>) {
  if ($line =~ m#TARGET\s+(\S+)#){
    $name = $1;
    print $OUTFILE "Target $name\n";
  }
}

I am not sure how to print out the next 3 lines following Target. Note: Assume that the targets are always farther apart than 3 lines from each other. I think I would need a counter right?

Body:
Yet another answer:

perl -ne 'print if /^Target\b/ and $l=$. or $. <= 3+$l&&$l' sample.txt

This exploits that the special Perl variable $. has the current line number of the input.

If you're using Gnu/Linux or a similarly reasonable OS, then the grep command with a trailing context of 3 lines after matches is also an alternative. If you can bear to have -- separation lines between the matches:

grep -A3 Target sample.txt
grep -A3 '^Target ' sample.txt
grep -A3 -P '^Target\b' sample.txt


问:
pd.read_csv is reading less rows than the expected
I'm using pandas to read a csv file, beforehand I already know the file has 13,000 rows, and pandas reads just 9,500 without raising any errors... but here is the thing, when I use 'to_csv()' method, and open the file with excel, it has 13,000 rows, so I don't understand what's happening here...</p>

```<code>raw_data = pd.read_csv(file
                   ,delimiter='|'
                   ,sep='|'
                   ,low_memory= False
                  )
</code>```

答:
I used this post to fix my problem an it worked

Not reading all rows while importing csv into pandas dataframe

If somebody can explain why is this happen, and why I need use the parameter "quoting" I'll be grateful.

Body:
I'm using pandas to read a csv file, beforehand I already know the file has 13,000 rows, and pandas reads just 9,500 without raising any errors... but here is the thing, when I use 'to_csv()' method, and open the file with excel, it has 13,000 rows, so I don't understand what's happening here...

raw_data = pd.read_csv(file
                   ,delimiter='|'
                   ,sep='|'
                   ,low_memory= False
                  )


问:
Azure DevOps and Azure Function Deployment: where are my app settings
I'm trying to upload a Dotnet core Azure Function to an app service hosted on Windows and I'm struggling to prove that it works or ensure the settings are correct.

I also have the aspiration that the deployment should be fully automated without having to go via the Azure Portal and tweak settings etc.

Build process: currently it looks like this...

The c# function compiles and all unit tests pass locally and on the Azure DevOps build agents

Build completes and generates the zip file

I wrap the zip file within a versioned Nuget package

Nuget package is hosted in Azure DevOps Artifacts repo

So all looks good at this point.

Release Process

I restore and unpack the nuget package on the Azure DevOps build agent.

I confirm the zip file exists with a Powershell task - all good.

I then use the Azure DevOps Release pipeline task; "Azure Functions"

https://github.com/Microsoft/azure-pipelines-tasks/blob/master/Tasks/AzureFunctionAppV1/README.md

I think I've configured this task correctly

Package or Folder: "The path I validated in step 2 above"

Deployment Method: Zip Deploy (I've alternated between this and Package deployment in different releases)

App Settings (see screenshot below)

name value pairs like -Name "value" -Name2 "value2" etc

I've also included -WEBSITE_RUN_FROM_PACKAGE "1" in the list of app settings (I've tried releases with and without this setting present)

The Results

The release passes, it says in the logs that its uploaded the package and the app settings.

However, when I go to the Azure Portal:

I don't see my app settings that I thought I'd uploaded in the release.

It retains dummy app settings that I added via the Azure Portal directly

Questions

Should I create an empty Azure Function within the AppServive using the Azure Portal before I start the Release with this task?

The very first time I ran the release it failed because it said it couldn't find the slot I'd specified. I was under the impression that the Azure Function pipeline task would create everything but it appears that it expects there to be an empty function with slots predefined and maybe app settings predefined. Any thoughts please?

Do I have to create app settings in the Portal before the release? In other words does the Pipeline task only allow updates to existing Portal created app settings.

Is there a better Pipeline task to use - that can create an new Azure Function if it doesn't exist already?

As is often the case with help documentation, the info I've seen follows a happy path, or sometimes too much with lots of ifs, buts and maybe advice.

Any guidance would be truly appreciated as I feel I'm going round in circles here and it should be simple.

Thankyou.

答:
After you've done a build in your Azure Devops pipeline you will create a package to make a release from. You have to make sure that the contents in that package matches to correct folder structure. The contents of your app should have the following structure according to Requirements for continuous deployment.

```<code>FunctionApp
 | - host.json
 | - MyFirstFunction
 | | - function.json
 | | - ...
 | - MySecondFunction
 | | - function.json
 | | - ...
 | - SharedCode
 | - bin
</code>```

After the build you can check the contents of the generated package by going to the summary for that particular build and clicking on the published artifact. There you can download the contents and make sure that it has the following structure and content:

```<code> | - host.json
 | - MyFirstFunction
 | | - function.json
 | | - ...
 | - MySecondFunction
 | | - function.json
 | | - ...
 | - SharedCode (might not be there)
 | - bin
</code>```

Once deployed you can browser your deployed files through Kudu by using the CMD or Powershell Debug Console. If you have chosen to run from package you can see the package used at /data/SitePackages/. The packagename.txt points to the latest package used. The contents of the package are extracted to /site/wwwroot/. There you should see at least a host.json, a bin folder, and the folders containing your functions. Nothing else. The function app content should not be deployed to a sub folder of /site/wwwroot/, like for example /site/wwwroot/FunctionApp/.

If the content and folder structure in wwwroot isn't correct, you might still see a successful deployment, you Function App shows up but there are no functions showing up.

Body:
After you've done a build in your Azure Devops pipeline you will create a package to make a release from. You have to make sure that the contents in that package matches to correct folder structure. The contents of your app should have the following structure according to Requirements for continuous deployment.

FunctionApp
 | - host.json
 | - MyFirstFunction
 | | - function.json
 | | - ...
 | - MySecondFunction
 | | - function.json
 | | - ...
 | - SharedCode
 | - bin

After the build you can check the contents of the generated package by going to the summary for that particular build and clicking on the published artifact. There you can download the contents and make sure that it has the following structure and content:

 | - host.json
 | - MyFirstFunction
 | | - function.json
 | | - ...
 | - MySecondFunction
 | | - function.json
 | | - ...
 | - SharedCode (might not be there)
 | - bin

Once deployed you can browser your deployed files through Kudu by using the CMD or Powershell Debug Console. If you have chosen to run from package you can see the package used at /data/SitePackages/. The packagename.txt points to the latest package used. The contents of the package are extracted to /site/wwwroot/. There you should see at least a host.json, a bin folder, and the folders containing your functions. Nothing else. The function app content should not be deployed to a sub folder of /site/wwwroot/, like for example /site/wwwroot/FunctionApp/.

If the content and folder structure in wwwroot isn't correct, you might still see a successful deployment, you Function App shows up but there are no functions showing up.


问:
Can't create python virtualenv FileNotFoundError wheels.lock
I am working in a system for which virtualenv is not installed system wide. I do not have root access to install it system wide.

After installing virtualenv for me as user with pip3 install --user virtualenv, creating a virtual environment with
python3 -m virtualenv testenv fails with:

```<code>FileNotFoundError: [Errno 2] No such file or directory: '/path/to/python/share/virtualenv/seed-v1/3.6/wheels.lock'
</code>```

The folder  /path/to/python/share/virtualenv/ does not exist.

How can I use virtualenv even so it is not installed system wide?

答:
The Problem seems to be that virtualenv tries to write to the seed-v1 folder for which I don't have permissions.

After setting the recently introduced VIRTUALENV_OVERRIDE_APP_DATA to a folder with write permission I can use virtualenv  like expected.

Body:
I am working in a system for which virtualenv is not installed system wide. I do not have root access to install it system wide.

After installing virtualenv for me as user with pip3 install --user virtualenv, creating a virtual environment with
python3 -m virtualenv testenv fails with:

FileNotFoundError: [Errno 2] No such file or directory: '/path/to/python/share/virtualenv/seed-v1/3.6/wheels.lock'

The folder  /path/to/python/share/virtualenv/ does not exist.

How can I use virtualenv even so it is not installed system wide?


问:
Svelte v3 programmatically create a component with props and event listeners
Is it possible to create a component and programmatically attach event listeners to it?

I know that this is easily possible for props using <svelte:component/> by spreading with { ...props }. I wonder if something similar can be achieved to attach event listeners.

E.g., in the following example I would like to programmatically attach on:message to A and on:count to B:

```<code><!-- App.svelte -->
<script>
    import A from './A.svelte';
    import B from './B.svelte';

    let message = 'Hi there ';
    let count = 0;

    const components = [{
        component: A,
        props: { message },
        listeners: { message: (m) => { console.log(`They say "${m}"`); } }
    }, {
        component: B,
        props: { count },
        listeners: { click: () => { count++; } }
    }];
</script>

{#each components as component}
    <div><svelte:component this={component.component} { ...component.props }/></div>
{/each}

<div>
    <p>They say "{message}"!</p>
    <p>They clicked {count} times!</p>
</div>

<!-- A.svelte -->
<script>
    import { createEventDispatcher } from 'svelte';
    const dispatch = createEventDispatcher();
    export let message = '';
    function changeHandler(e) { dispatch('message', message); }
</script>

<input on:change={changeHandler} on:value={message} value={message} />

<!-- B.svelte -->
<script>
    import { createEventDispatcher } from 'svelte';
    const dispatch = createEventDispatcher();
    export let count = 0;
    function clickHandler() { dispatch('count', count); }
</script>

<button on:click={clickHandler}>Click me</button>
</code>```

Here's a live demo: https://svelte.dev/repl/af1bd30ab75b43f19b72a306340b7282?version=3.18.2

I.e., I am hoping there's a way to expand the components array to

```<code><A message={message} on:message={e => { message = e.detail; }}/>
<B count={count} on:count={e => { count = e.detail; }}/>
</code>```

答:
You can't dynamically attach listeners, no - don't forget Svelte is a compiled language, it does all the heavy lifting at compile time, so things need to be known in advance.

What I've done for dynamic listeners is to fire a single known event, and then have the event detail contain differential logic, such as event names, etc. As in the following:

```<code>// SomeComponent.svelte
<script>
  import { createEventDispatcher } from 'svelte'

  const dispatch = createEventDispatcher()

  dispatch('component-event', { name: 'alert', value: 'oh noes' })
  dispatch('component-event', { name: 'log', value: 'some message' })
</script>
</code>```

```<code>// App.svelte
<svelte:component this={someComponent} on:component-event={e => handleEvent(e)} />

<script>
  function handleEvent ({ detail }) {
    const { name, value } = detail
    if (name === 'alert') { alert(value) }
    if (name === 'log') { console.log(value) }
  }
</script>
</code>```

Body:
Is it possible to create a component and programmatically attach event listeners to it?

I know that this is easily possible for props using <svelte:component/> by spreading with { ...props }. I wonder if something similar can be achieved to attach event listeners.

E.g., in the following example I would like to programmatically attach on:message to A and on:count to B:

{#each components as component}

<svelte:component this={component.component} { ...component.props }/>

{/each}

They say "{message}"!

They clicked {count} times!

<input on:change={changeHandler} on:value={message} value={message} />

<button on:click={clickHandler}>Click me</button>

Here's a live demo: https://svelte.dev/repl/af1bd30ab75b43f19b72a306340b7282?version=3.18.2

I.e., I am hoping there's a way to expand the components array to

 { message = e.detail; }}/>
 { count = e.detail; }}/>

Body:
You can't dynamically attach listeners, no - don't forget Svelte is a compiled language, it does all the heavy lifting at compile time, so things need to be known in advance.

What I've done for dynamic listeners is to fire a single known event, and then have the event detail contain differential logic, such as event names, etc. As in the following:

// SomeComponent.svelte
<script>
  import { createEventDispatcher } from 'svelte'

  const dispatch = createEventDispatcher()

  dispatch('component-event', { name: 'alert', value: 'oh noes' })
  dispatch('component-event', { name: 'log', value: 'some message' })
</script>

// App.svelte
<svelte:component this={someComponent} on:component-event={e => handleEvent(e)} />

<script>
  function handleEvent ({ detail }) {
    const { name, value } = detail
    if (name === 'alert') { alert(value) }
    if (name === 'log') { console.log(value) }
  }
</script>


问:
Angular *NgIf With Semantic UI
Am Facing One issue with Semantic UI Dropdown with Angular *NgIf. When am Putting Semantic Dropdown Inside any NgIf condition. Semantic is not working. when i removed that Ngif Its working Fine. Any Solution for this.

WIth *NgIf,
Now Semantic Dropdown will not work. It will show Normal Dropdown.

```<code><div *ngIf= "IsVisible">
<select class="ui selection dropdown"
   <option value="" selected="selected">Bedroom</option>
   <option *ngFor="let bedroom of bedrooms">
      {{bedroom.bhk_numbers}}
   </option>
</select>
</div>

</code>```

If I removed *NgIf. It will Work Perfectly Semantic UI. Like this,

```<code><div>
<select class="ui selection dropdown"
   <option value="" selected="selected">Bedroom</option>
   <option *ngFor="let bedroom of bedrooms">
      {{bedroom.bhk_numbers}}
   </option>
</select>
</div>

</code>```

答:
You can use [hidden] attribute to solve this issue. *ngIf will remove the subsequent inner lines of code from the dom. But on using [hidden], it will stay inside the dom, but wont be visible to user.

Please replace

*ngIf= "IsVisible" with  [hidden]="!IsVisible"

Title: Angular *NgIf With Semantic UI

Body:
Am Facing One issue with Semantic UI Dropdown with Angular *NgIf. When am Putting Semantic Dropdown Inside any NgIf condition. Semantic is not working. when i removed that Ngif Its working Fine. Any Solution for this.

WIth *NgIf,
Now Semantic Dropdown will not work. It will show Normal Dropdown.

<select class="ui selection dropdown"
   <option value="" selected="selected">Bedroom</option>
   <option *ngFor="let bedroom of bedrooms">
      {{bedroom.bhk_numbers}}
   </option>
</select>

If I removed *NgIf. It will Work Perfectly Semantic UI. Like this,

<select class="ui selection dropdown"
   <option value="" selected="selected">Bedroom</option>
   <option *ngFor="let bedroom of bedrooms">
      {{bedroom.bhk_numbers}}
   </option>
</select>


问:
How to extract floats from vector columns in PySpark?
My Spark DataFrame has data in the following format:

The printSchema() shows that each column is of the type vector.

I tried to get the values out of [ and ] using the code below (for 1 columns col1):

```<code>from pyspark.sql.functions import udf
from pyspark.sql.types import FloatType

firstelement=udf(lambda v:float(v[0]),FloatType())
df.select(firstelement('col1')).show()
</code>```

However, how can I apply it to all columns of df?

答:
1. Extract first element of a single vector column:

To get the first element of a vector column, you can use the answer from this SO: discussion Access element of a vector in a Spark DataFrame (Logistic Regression probability vector)

Here's a reproducible example:

```<code>>>> from pyspark.sql import functions as f
>>> from pyspark.sql.types import FloatType
>>> df = spark.createDataFrame([{"col1": [0.2], "col2": [0.25]},
                                {"col1": [0.45], "col2":[0.85]}])
>>> df.show()
+------+------+
|  col1|  col2|
+------+------+
| [0.2]|[0.25]|
|[0.45]|[0.85]|
+------+------+

>>> firstelement=f.udf(lambda v:float(v[0]),FloatType())
>>> df.withColumn("col1", firstelement("col1")).show()
+----+------+
|col1|  col2|
+----+------+
| 0.2|[0.25]|
|0.45|[0.85]|
+----+------+
</code>```

2. Extract first element of multiple vector columns:

To generalize the above solution to multiple columns, apply a for loop. Here's an example:

```<code>>>> from pyspark.sql import functions as f
>>> from pyspark.sql.types import FloatType

>>> df = spark.createDataFrame([{"col1": [0.2], "col2": [0.25]},
                                {"col1": [0.45], "col2":[0.85]}])
>>> df.show()
+------+------+
|  col1|  col2|
+------+------+
| [0.2]|[0.25]|
|[0.45]|[0.85]|
+------+------+

>>> firstelement=f.udf(lambda v:float(v[0]),FloatType())
>>> df = df.select([firstelement(c).alias(c) for c in df.columns])
>>> df.show()
+----+----+
|col1|col2|
+----+----+
| 0.2|0.25|
|0.45|0.85|
+----+----+
</code>```

Body:
My Spark DataFrame has data in the following format:

The printSchema() shows that each column is of the type vector.

I tried to get the values out of [ and ] using the code below (for 1 columns col1):

from pyspark.sql.functions import udf
from pyspark.sql.types import FloatType

firstelement=udf(lambda v:float(v[0]),FloatType())
df.select(firstelement('col1')).show()

However, how can I apply it to all columns of df?

Body:
1. Extract first element of a single vector column:

To get the first element of a vector column, you can use the answer from this SO: discussion Access element of a vector in a Spark DataFrame (Logistic Regression probability vector)

Here's a reproducible example:

>>> from pyspark.sql import functions as f
>>> from pyspark.sql.types import FloatType
>>> df = spark.createDataFrame([{"col1": [0.2], "col2": [0.25]},
                                {"col1": [0.45], "col2":[0.85]}])
>>> df.show()
+------+------+
|  col1|  col2|
+------+------+
| [0.2]|[0.25]|
|[0.45]|[0.85]|
+------+------+

>>> firstelement=f.udf(lambda v:float(v[0]),FloatType())
>>> df.withColumn("col1", firstelement("col1")).show()
+----+------+
|col1|  col2|
+----+------+
| 0.2|[0.25]|
|0.45|[0.85]|
+----+------+

2. Extract first element of multiple vector columns:

To generalize the above solution to multiple columns, apply a for loop. Here's an example:

>>> from pyspark.sql import functions as f
>>> from pyspark.sql.types import FloatType

>>> df = spark.createDataFrame([{"col1": [0.2], "col2": [0.25]},
                                {"col1": [0.45], "col2":[0.85]}])
>>> df.show()
+------+------+
|  col1|  col2|
+------+------+
| [0.2]|[0.25]|
|[0.45]|[0.85]|
+------+------+

>>> firstelement=f.udf(lambda v:float(v[0]),FloatType())
>>> df = df.select([firstelement(c).alias(c) for c in df.columns])
>>> df.show()
+----+----+
|col1|col2|
+----+----+
| 0.2|0.25|
|0.45|0.85|
+----+----+


问:
How can I create a function that takes a parameter of unknown type in C?
Say I have the following code:

```<code>struct test* t1;
t1 = get_t(1);
</code>```

... where get_t is:

```<code>struct test* get_t(int);
</code>```

How can I refactor the above code and put it in a function? Something like the following:

```<code>void r1(?* t, ?* (fn*)(int)) {
    t = fn(1);
}

/* ... */

struct test* t1;
r1(t1, &get_t);
</code>```

答:
If you have gcc, you can use this more typesafe version:

```<code>#define r1(varp,func) ({ \
    typeof(**varp)* (*_func_)(int); \
    typeof(**varp)* _varp_ = (varp); \
    _func_ = (func); \
    r1_((void**)(_varp_),(void*(*)(int))_func_); \
    })

void r1_(void** varp,void*(*func)(int))
    {
    *varp = func(1);
    }
</code>```

Call as:

```<code>struct test* get_t(int);
struct test* t1;
r1(&t,get_t);
</code>```

(You dont need to use & on functions, they decay to pointers automatically, like arrays). This checks that t is a pointer, and that get_t is a function returning that type of pointer. _varp_ is technically unneeded, but keeps the argument evaluation in the right order.

Edit:

If you don't have gcc, you can still do this, but you have to provide the type explicitly:

```<code>#define r1(T,varp,func) do { \
    T*(*_func_)(int); \
    T* _varp_ = (varp); \
    _func_ = (func); \
    r1_((void**)(_varp_),(void*(*)(int))_func_); \
    } while(0)

void r1_(void** varp,void*(*func)(int))
    {
    *varp = func(1);
    }
</code>```

Call as:

```<code>struct test* get_t(int);
struct test* t1;
r1(struct test*,&t,get_t);
</code>```

not quite as safe, and more redundant, but still fairly good.

Body:
Say I have the following code:

struct test* t1;
t1 = get_t(1);

... where get_t is:

struct test* get_t(int);

How can I refactor the above code and put it in a function? Something like the following:

void r1(?* t, ?* (fn*)(int)) {
    t = fn(1);
}

/* ... */

struct test* t1;
r1(t1, &get_t);

Body:
If you have gcc, you can use this more typesafe version:

#define r1(varp,func) ({ \
    typeof(**varp)* (*_func_)(int); \
    typeof(**varp)* _varp_ = (varp); \
    _func_ = (func); \
    r1_((void**)(_varp_),(void*(*)(int))_func_); \
    })

void r1_(void** varp,void*(*func)(int))
    {
    *varp = func(1);
    }

Call as:

struct test* get_t(int);
struct test* t1;
r1(&t,get_t);

(You dont need to use & on functions, they decay to pointers automatically, like arrays). This checks that t is a pointer, and that get_t is a function returning that type of pointer. _varp_ is technically unneeded, but keeps the argument evaluation in the right order.

Edit:

If you don't have gcc, you can still do this, but you have to provide the type explicitly:

#define r1(T,varp,func) do { \
    T*(*_func_)(int); \
    T* _varp_ = (varp); \
    _func_ = (func); \
    r1_((void**)(_varp_),(void*(*)(int))_func_); \
    } while(0)

void r1_(void** varp,void*(*func)(int))
    {
    *varp = func(1);
    }

Call as:

struct test* get_t(int);
struct test* t1;
r1(struct test*,&t,get_t);

not quite as safe, and more redundant, but still fairly good.


问:
DialogFlow name in context, prevent resetting conversation flow every time a new name is spoken
I have a conversation tree set up in DialogFlow, starts with a welcome intent and has a few follow-up intents, goes three levels deep.
The conversation begins with the user saying hi or similar, to which the bot replies with a greeting and prompts for the user's name, the user then provides the name, the bot follows up with 'Hi [name], nice to meet you' and asks a question. Then depending on the answer (custom follow-up intents) the conversation goes on.

The name is remembered and used in the follow-up intents, but at any point in the conversation flow if the user says a different name for some reason (or something that is recognized as a name), the bot resets to the 'awaiting_name' intent and says 'Hi [new name], nice to meet you'.

How can I prevent this from happening?

答:
This is due the the LifeSpanCount that you are setting to each intent. Reduce it to 1 or 2 as required so to make it inactive after 2 counts.
Also, you can add follow-up intents to handle the "no-match" situation, defining whether to repeat the intent or do something else when a user speaks something out of context.</p>


问:
How to return LocalDateTime from REST controller endpoint?
I'm writing a REST controller in Spring- java, and one of my endpoints should return a LocalDateTime variable.

```<code>@GetMapping(path = "/lastDateTimeOfReset")
LocalDateTime fetchLastDateTimeOfReset() {
   return mongoManagerService.fetchLastDateTimeOfReset();
}
</code>```

This is the client request:

```<code>ResponseEntity<LocalDateTime> lastDateEntity = restTemplate.getForEntity(url, LocalDateTime.class);
</code>```

I get the following excepation on my client side:

```<code>org.springframework.web.client.RestClientException:
Error while extracting response for type [class java.time.LocalDateTime] and content type [application/json;charset=UTF-8];
nested exception is org.springframework.http.converter.HttpMessageNotReadableException:
JSON parse error: Expected array or string.;
nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Expected array or string.
at [Source: (PushbackInputStream); line: 1, column: 1]
</code>```

I checked the return value on debug mode and it is a valid LocalDateTime.
Why is this exception thrown and how to overcome it?

答:
You need to check return type of mongoManagerService.fetchLastDateTimeOfReset();

Or Test your application with below sample code

Service

```<code>@GetMapping(path = "/lastDateTimeOfReset")
    LocalDateTime fetchLastDateTimeOfReset() {
       return LocalDateTime.now();
    }
</code>```

Client

```<code>RestTemplate rs = new RestTemplate();
ResponseEntity<LocalDateTime> lastDateEntity = rs.getForEntity(new URI("http://localhost:8089/lastDateTimeOfReset"), LocalDateTime.class);
System.out.println(lastDateEntity);
</code>```

Output

<200,2020-02-19T15:00:51.603220,[Content-Type:"application/json;charset=UTF-8", Transfer-Encoding:"chunked", Date:"Wed, 19 Feb 2020 09:30:51 GMT"]>

Body:
I'm writing a REST controller in Spring- java, and one of my endpoints should return a LocalDateTime variable.

@GetMapping(path = "/lastDateTimeOfReset")
LocalDateTime fetchLastDateTimeOfReset() {
   return mongoManagerService.fetchLastDateTimeOfReset();
}

This is the client request:

ResponseEntity<LocalDateTime> lastDateEntity = restTemplate.getForEntity(url, LocalDateTime.class);

I get the following excepation on my client side:

org.springframework.web.client.RestClientException:
Error while extracting response for type [class java.time.LocalDateTime] and content type [application/json;charset=UTF-8];
nested exception is org.springframework.http.converter.HttpMessageNotReadableException:
JSON parse error: Expected array or string.;
nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Expected array or string.
at [Source: (PushbackInputStream); line: 1, column: 1]

I checked the return value on debug mode and it is a valid LocalDateTime.
Why is this exception thrown and how to overcome it?

Body:
You need to check return type of mongoManagerService.fetchLastDateTimeOfReset();

Or Test your application with below sample code

Service

@GetMapping(path = "/lastDateTimeOfReset")
    LocalDateTime fetchLastDateTimeOfReset() {
       return LocalDateTime.now();
    }

Client

RestTemplate rs = new RestTemplate();
ResponseEntity<LocalDateTime> lastDateEntity = rs.getForEntity(new URI("http://localhost:8089/lastDateTimeOfReset"), LocalDateTime.class);
System.out.println(lastDateEntity);

Output

<200,2020-02-19T15:00:51.603220,[Content-Type:"application/json;charset=UTF-8", Transfer-Encoding:"chunked", Date:"Wed, 19 Feb 2020 09:30:51 GMT"]>


问:
Angular Reactive Forms: How to Populate A Multi-Selection Checkbox form?
How can I populate check boxes of a form group while in "Edit Mode"?

I am working on a project where I am making and editing workouts, then storing them to a database (using firebase at this current time). The workout creation worked flawlessly with the Angular template driven approach, but I am trying to add the functionality where I can edit an existing workout. Because of this, I have made the form reactive where depending on if I am in editMode (this mode is determined from the route params) or not, the information is either populated, or it isn't.

This works great for the basic string population, such as title and imagepath. Here, I am in editMode (coming from the route params) and things are populated accordingly:

However, I also have checkboxes to be filled on this same form. I am using Material Theme for the checkboxes. Here's an example from a workoutphase selection:

```<code><mat-form-field
  hideRequiredMarker
  appearance="fill"
  class="phase">
  <mat-label>Phase</mat-label>
  <mat-select multiple id="phase" name="phase" formControlName="phases">
    <mat-option value="Base 1">Base 1</mat-option>
    <mat-option value="Base 2">Base 2</mat-option>
    <mat-option value="Base 3">Base 3</mat-option>
    <mat-option value="Build 1">Build 1</mat-option>
    <mat-option value="Build 2">Build 2</mat-option>
    <mat-option value="Recovery">Recovery</mat-option>
    <mat-option value="Peak">Peak</mat-option>
    <mat-option value="Race">Race</mat-option>
    <mat-option value="Testing">Testing</mat-option>
  </mat-select>
</mat-form-field>
</code>```

and how it appears when creating a workout (the problem is when trying to populate while in editMode):

This appears with a list dropdown that later returns an array of selected items to be added to the workouts.

With the reactive approach, I am trying to be able to populate the checkboxes as filled while being in editMode (or when the information is being pulled in). Is there a way to populate checkboxes? Or would I simply need to "re-check" which boxes I want while in edit mode?

So far I have tried using a new FormArray([]); that takes this array and populates everything as it should be. This gives me loads of errors related to the formGroup.

This form is in the WorkoutEditComponent found in app/features/workouts-page/workout-edit
You can get to the edit form by clicking on any workout on the home view workouts page, then clicking edit button at the top.

Here is the stackblitz to this code.
 You can see that if you go to the side menu and select workouts, create workout, then there is a checkbox option and the dropdown works. But when you go through the workouts/edit, then the checkboxes are unable to populate. I have simplified and backtracked a bit on this stackblitz for the sake of simplicity of the problem. Any method used with the FormArray([]) seemed to make the problem worse.

Here is some more information:

I am initializing the form through my ngOnInit after checking whether or not I am in edit mode:

```<code>ngOnInit()
 this.route.params.subscribe((params: Params) => {
    this.id = +params["id"];
    this.editMode = params["id"] != null;
    this.initForm();
  });
}
</code>```

and the initForm():

```<code>private initForm() {
  let workoutImgPath = "";
  let workoutTitle = "";
  if (this.editMode) {
    const workout = this.workoutService.getWorkout(this.id);
    workoutTitle = workout.title;
    workoutImgPath = workout.imagePath;
    console.log(workout);
  }

 this.workoutForm = new FormGroup({
    title: new FormControl(workoutTitle, Validators.required),
    imgPath: new FormControl(workoutImgPath, Validators.required)
  });
}
</code>```

Above is the currently working solution where only the image path and title are being added to the form whilst in edit mode.

Can these checkboxes also be populated from an array of items while editing an existing workout?

答:
I updated your stackblitz example, and hopefully managed to do what you are trying to do, it was quite simple actually.

https://stackblitz.com/edit/github-qzxhec-lnaozw

Body:
How can I populate check boxes of a form group while in "Edit Mode"?

I am working on a project where I am making and editing workouts, then storing them to a database (using firebase at this current time). The workout creation worked flawlessly with the Angular template driven approach, but I am trying to add the functionality where I can edit an existing workout. Because of this, I have made the form reactive where depending on if I am in editMode (this mode is determined from the route params) or not, the information is either populated, or it isn't.

This works great for the basic string population, such as title and imagepath. Here, I am in editMode (coming from the route params) and things are populated accordingly:

However, I also have checkboxes to be filled on this same form. I am using Material Theme for the checkboxes. Here's an example from a workoutphase selection:

<mat-form-field
  hideRequiredMarker
  appearance="fill"
  class="phase">
  <mat-label>Phase</mat-label>
  <mat-select multiple id="phase" name="phase" formControlName="phases">
    <mat-option value="Base 1">Base 1</mat-option>
    <mat-option value="Base 2">Base 2</mat-option>
    <mat-option value="Base 3">Base 3</mat-option>
    <mat-option value="Build 1">Build 1</mat-option>
    <mat-option value="Build 2">Build 2</mat-option>
    <mat-option value="Recovery">Recovery</mat-option>
    <mat-option value="Peak">Peak</mat-option>
    <mat-option value="Race">Race</mat-option>
    <mat-option value="Testing">Testing</mat-option>
  </mat-select>
</mat-form-field>

and how it appears when creating a workout (the problem is when trying to populate while in editMode):

This appears with a list dropdown that later returns an array of selected items to be added to the workouts.

With the reactive approach, I am trying to be able to populate the checkboxes as filled while being in editMode (or when the information is being pulled in). Is there a way to populate checkboxes? Or would I simply need to "re-check" which boxes I want while in edit mode?

So far I have tried using a new FormArray([]); that takes this array and populates everything as it should be. This gives me loads of errors related to the formGroup.

This form is in the WorkoutEditComponent found in app/features/workouts-page/workout-edit
You can get to the edit form by clicking on any workout on the home view workouts page, then clicking edit button at the top.

Here is the stackblitz to this code.
 You can see that if you go to the side menu and select workouts, create workout, then there is a checkbox option and the dropdown works. But when you go through the workouts/edit, then the checkboxes are unable to populate. I have simplified and backtracked a bit on this stackblitz for the sake of simplicity of the problem. Any method used with the FormArray([]) seemed to make the problem worse.

Here is some more information:

I am initializing the form through my ngOnInit after checking whether or not I am in edit mode:

ngOnInit()
 this.route.params.subscribe((params: Params) => {
    this.id = +params["id"];
    this.editMode = params["id"] != null;
    this.initForm();
  });
}

and the initForm():

private initForm() {
  let workoutImgPath = "";
  let workoutTitle = "";
  if (this.editMode) {
    const workout = this.workoutService.getWorkout(this.id);
    workoutTitle = workout.title;
    workoutImgPath = workout.imagePath;
    console.log(workout);
  }

 this.workoutForm = new FormGroup({
    title: new FormControl(workoutTitle, Validators.required),
    imgPath: new FormControl(workoutImgPath, Validators.required)
  });
}

Above is the currently working solution where only the image path and title are being added to the form whilst in edit mode.

Can these checkboxes also be populated from an array of items while editing an existing workout?


问:
How To Use A Directive In A Custom Input With ControlValueAccessor Angular
I've been create a simple custom input component in my angular app use ControlValueAccessor. So, when I want to create a form input element, I don't have to call <input />, only call <my-input>.

I have a problem, when I use <input />, I can use myDirective. For example:

<input type="text" class="form-control" formControlName="name" myDirective />
```

<p>But, when I use <code>my-input</code>, then I can't use <code>myDirective</code>. For example:</p>

<pre class="lang-html prettyprint-override"><code><my-input formControlName="name" myDirective></my-input>
</code>```

myDirective dosn't work in my-input

This is my-input component use ControlValueAccessor code:

import { Component, forwardRef } from '@angular/core';
import { NG_VALUE_ACCESSOR, ControlValueAccessor } from '@angular/forms';

@Component({
  selector: 'my-input',
  templateUrl: './my-input.component.html',
  styleUrls: ['./my-input.component.scss'],
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(()  => MyInputComponent ),
      multi: true
    }
  ]
})

export class MyInputComponent implements ControlValueAccessor {

  onChange: () => void;
  onTouched: () => void;

  value: string;

  writeValue(value: string): void {
    this.value = value ? value : '';
  }

  registerOnChange(fn: any): void {
    this.onChange = fn;
  }

  registerOnTouched(fn: any): void {
    this.onTouched = fn;
  }
}
```

<p><strong>Updated:</strong> <code>myDirective</code> code:</p>

<pre class="lang-js prettyprint-override"><code>import { Directive, HostListener } from '@angular/core';
import { FormControlName } from '@angular/forms';

@Directive({
    selector: '[myDirective]'
})

export class MyDirective{
    constructor(private formControlName: FormControlName) { }

    @HostListener('input', ['$event'])
    onInputChange() {
        this.formControlName.control.setValue(this.formControlName.value.replace(/[^0-9]/g, ''));
    }
}
</code>```

Is there a way for myDirective to be used in themy-input component?

Thanks in advance.

答:
You can't directly but you can do some Hack with directives queries

According to the Angular Directives documentation:

Decorator that marks a class as an Angular directive. You can define your own directives to attach custom behaviour to elements in the DOM.

a decorator is a behaviour attached to an element to the DOM, so it will affect the element wich use the directive.

BUT (and is a big BUT for a reason - check notes), you can hack this behaviour using directive queries.

BUT remember you must define specific directives which will work only with specific queries and cannot be used for any DOM element.

The solution

The solution is based on the following:

I want to define a directive which works on an element children, and not on the element itself.

You can use @ContentChildren and QueryList to check if you have some children with a specific directive.

For example, I have a background directive applied to input parent and a CustomFormControlDirective to query the children:

import {
  Directive,
  ElementRef,
  Input,
  ContentChildren,
  ViewChildren,
  QueryList
} from "@angular/core";

@Directive({
  selector: "[customformcontrol]"
})
export class CustomFormControlDirective {
  constructor(public elementRef: ElementRef) {}
}

@Directive({
  selector: "[backgroundColor]",
  queries: {
    contentChildren: new ContentChildren(CustomFormControlDirective),
    viewChildren: new ViewChildren(CustomFormControlDirective)
  }
})
export class BackgroundColorDirective {
  @Input()
  set backgroundColor(color: string) {
    this.elementRef.nativeElement.style.backgroundColor = color;
  }

  @ContentChildren(CustomFormControlDirective, { descendants: true })
  contentChildren: QueryList<CustomFormControlDirective>;
  viewChildren: QueryList<CustomFormControlDirective>;

  constructor(private elementRef: ElementRef) {}

  ngAfterContentInit() {
    // contentChildren is set
    console.log("%o", this.contentChildren);
  }
}
[...]

  <input customformcontrol />

```

<p>Of course this directive will apply the bg color to the parent div:</p>

<p><img src="https://i.stack.imgur.com/d7Fjh.png" alt="Div with red bg]"></p>

<p>So how can we set this property to the children?</p>

<p>We have the children inside our <strong>contentChildren</strong> variable:</p>

<p><img src="https://i.stack.imgur.com/FF0TT.png" alt="Console log"></p>

<p>So we need to apply the desired background to our children element, we can loop trough the query results and try to apply the style:</p>

<pre class="lang-js prettyprint-override"><code>  [...]
  _backgroundColor = null;
  @Input()
  set backgroundColor(color: string) {
    /// save the bg color instead of apply style
    this._backgroundColor = color;
  }
  ngAfterContentInit() {
    if (this.contentChildren.length) {
      /// then loop through childrens to apply style
      this.contentChildren.forEach(customFormControl => {
        customFormControl.elementRef.nativeElement.style.backgroundColor = this._backgroundColor;
      });
    }
  }
  [...]
</code>```

And it will apply the style to childrens:

also if there are more than 1 children:

Notes

this is an example, don't take this implementation as-is, you might define your own method or use a better one, but try to understand the QueryList selectors and ContentChildren.

using a custom directive to fetch childrens might not be necessary, you might use ReactiveForm directives directly (AbstractControlDirective / FormControlDirective) but I don't think they will let you access the DOM as it is private.

these directives will work only with children, so you might choose a better naming convention (e.g. ApplyToControlBackgroundDirective)

Body:
I've been create a simple custom input component in my angular app use ControlValueAccessor. So, when I want to create a form input element, I don't have to call <input />, only call <my-input>.

I have a problem, when I use <input />, I can use myDirective. For example:

<input type="text" class="form-control" formControlName="name" myDirective />

But, when I use my-input, then I can't use myDirective. For example:

<my-input formControlName="name" myDirective></my-input>

myDirective dosn't work in my-input

This is my-input component use ControlValueAccessor code:

import { Component, forwardRef } from '@angular/core';
import { NG_VALUE_ACCESSOR, ControlValueAccessor } from '@angular/forms';

@Component({
  selector: 'my-input',
  templateUrl: './my-input.component.html',
  styleUrls: ['./my-input.component.scss'],
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(()  => MyInputComponent ),
      multi: true
    }
  ]
})

export class MyInputComponent implements ControlValueAccessor {

  onChange: () => void;
  onTouched: () => void;

  value: string;

  writeValue(value: string): void {
    this.value = value ? value : '';
  }

  registerOnChange(fn: any): void {
    this.onChange = fn;
  }

  registerOnTouched(fn: any): void {
    this.onTouched = fn;
  }
}

Updated: myDirective code:

import { Directive, HostListener } from '@angular/core';
import { FormControlName } from '@angular/forms';

@Directive({
    selector: '[myDirective]'
})

export class MyDirective{
    constructor(private formControlName: FormControlName) { }

    @HostListener('input', ['$event'])
    onInputChange() {
        this.formControlName.control.setValue(this.formControlName.value.replace(/[^0-9]/g, ''));
    }
}

Is there a way for myDirective to be used in themy-input component?

Thanks in advance.

Body:
You can't directly but you can do some Hack with directives queries

According to the Angular Directives documentation:

Decorator that marks a class as an Angular directive. You can define your own directives to attach custom behaviour to elements in the DOM.

a decorator is a behaviour attached to an element to the DOM, so it will affect the element wich use the directive.

BUT (and is a big BUT for a reason - check notes), you can hack this behaviour using directive queries.

BUT remember you must define specific directives which will work only with specific queries and cannot be used for any DOM element.

The solution

The solution is based on the following:

I want to define a directive which works on an element children, and not on the element itself.

You can use @ContentChildren and QueryList to check if you have some children with a specific directive.

For example, I have a background directive applied to input parent and a CustomFormControlDirective to query the children:

import {
  Directive,
  ElementRef,
  Input,
  ContentChildren,
  ViewChildren,
  QueryList
} from "@angular/core";

@Directive({
  selector: "[customformcontrol]"
})
export class CustomFormControlDirective {
  constructor(public elementRef: ElementRef) {}
}

@Directive({
  selector: "[backgroundColor]",
  queries: {
    contentChildren: new ContentChildren(CustomFormControlDirective),
    viewChildren: new ViewChildren(CustomFormControlDirective)
  }
})
export class BackgroundColorDirective {
  @Input()
  set backgroundColor(color: string) {
    this.elementRef.nativeElement.style.backgroundColor = color;
  }

  @ContentChildren(CustomFormControlDirective, { descendants: true })
  contentChildren: QueryList<CustomFormControlDirective>;
  viewChildren: QueryList<CustomFormControlDirective>;

  constructor(private elementRef: ElementRef) {}

  ngAfterContentInit() {
    // contentChildren is set
    console.log("%o", this.contentChildren);
  }
}
[...]
<div backgroundColor="red">
  <input customformcontrol />
</div>

Of course this directive will apply the bg color to the parent div:

So how can we set this property to the children?

We have the children inside our contentChildren variable:

So we need to apply the desired background to our children element, we can loop trough the query results and try to apply the style:

  [...]
  _backgroundColor = null;
  @Input()
  set backgroundColor(color: string) {
    /// save the bg color instead of apply style
    this._backgroundColor = color;
  }
  ngAfterContentInit() {
    if (this.contentChildren.length) {
      /// then loop through childrens to apply style
      this.contentChildren.forEach(customFormControl => {
        customFormControl.elementRef.nativeElement.style.backgroundColor = this._backgroundColor;
      });
    }
  }
  [...]

And it will apply the style to childrens:

also if there are more than 1 children:

Notes

this is an example, don't take this implementation as-is, you might define your own method or use a better one, but try to understand the QueryList selectors and ContentChildren.

using a custom directive to fetch childrens might not be necessary, you might use ReactiveForm directives directly (AbstractControlDirective / FormControlDirective) but I don't think they will let you access the DOM as it is private.

these directives will work only with children, so you might choose a better naming convention (e.g. ApplyToControlBackgroundDirective)


Title: Coverting a python list into string with comma separated in efficient way

Body:
I have a list of acc nos:

list1 = ['1234','3456','2345','5543','1344','5679','6433','3243','0089']

Output I need is a string:

print(output): '1234','3456','2345','5543','1344','5679','6433','3243','0089'

Body:
>>> list1 = ['1234','3456','2345','5543','1344','5679','6433','3243','0089']
>>> print(','.join(["'{0}'".format(s) for s in list1]))
'1234','3456','2345','5543','1344','5679','6433','3243','0089'


问:
Does Angular memoize inline *ngIf condition statements?
Does Angular memoize inline *ngIf condition statements? If I have for example:

```<code><form [formGroup]="form" *ngIf="inputModels.length < 200">
</code>```

is "inputModels.length < 200" recalculated every time change detection runs, or it's stored until inputModel changes?

答: As the variable inputModel change condition also check at that time.*NgIf detects changes.Hence changes are made to inputModel variable condition gets check</p>

Body:
Does Angular memoize inline *ngIf condition statements? If I have for example:

<form [formGroup]="form" *ngIf="inputModels.length < 200">

is "inputModels.length < 200" recalculated every time change detection runs, or it's stored until inputModel changes?


问:
Spark create dataset using encoder where row is array type
I am unable to figure out, the correct implementation for encoder to create Dataset from below RDD?

e.g.

```<code>JavaRDD<Integer[]>rdd= sparkContext.parallelize(
                Arrays.asList(new Integer[][]{new Integer[]{1,2},
                new Integer[]{3,4}
                ,new Integer[]{6,7}}));
</code>```

Below implementation fails-

```<code>DataSet<Integer> ds = sqlContext.createDataset(rdd.rdd(),Encoders.bean(Integer[].class));
</code>```

Exception in thread "main" java.lang.AssertionError: assertion failed
    at scala.Predef$.assert(Predef.scala:165)   at
  org.apache.spark.sql.catalyst.encoders.ExpressionEncoder$.javaBean(ExpressionEncoder.scala:90)
    at org.apache.spark.sql.Encoders$.bean(Encoders.scala:142)  at
  org.apache.spark.sql.Encoders.bean(Encoders.scala)

How to create encode for array type? Thanks!

答:
Please try converting it first to DataFrame and then to Dataset</p>

```<code>Dataset<Integer[]> dataFrame = sqlContext.createDataFrame(rdd, Integer[].class);
Dataset<Integer[]> ds = dataFrame.as(Encoders.bean(Integer[].class));
</code>```

Body:
I am unable to figure out, the correct implementation for encoder to create Dataset from below RDD?

e.g.

JavaRDD<Integer[]>rdd= sparkContext.parallelize(
                Arrays.asList(new Integer[][]{new Integer[]{1,2},
                new Integer[]{3,4}
                ,new Integer[]{6,7}}));

Below implementation fails-

DataSet<Integer> ds = sqlContext.createDataset(rdd.rdd(),Encoders.bean(Integer[].class));

Exception in thread "main" java.lang.AssertionError: assertion failed
    at scala.Predef$.assert(Predef.scala:165)   at
  org.apache.spark.sql.catalyst.encoders.ExpressionEncoder$.javaBean(ExpressionEncoder.scala:90)
    at org.apache.spark.sql.Encoders$.bean(Encoders.scala:142)  at
  org.apache.spark.sql.Encoders.bean(Encoders.scala)

How to create encode for array type? Thanks!

Body:
Please try converting it first to DataFrame and then to Dataset

Dataset<Integer[]> dataFrame = sqlContext.createDataFrame(rdd, Integer[].class);
Dataset<Integer[]> ds = dataFrame.as(Encoders.bean(Integer[].class));


问:
How to use the result of a JSR223 Pre-Processor script once for thread?
I have 100 threads for 100 iterations. I want to use the result of a script as body of a HTTP POST request, it will has to be different for each thread.
FOR EXAMPLE: 100 thread - 100 iterations, I want 100 different requests.</p>

答:
JSR223 PreProcessor has sampler shortcut, if JSR223 Pre-Processor is applied to the HTTP Request sampler the sampler is mapped to HTTPSamplerProxy

Therefore you can add the generated value to the body of the HTTP Request sampler as:

```<code>sampler.addNonEncodedArgument('', body, '')
sampler.setPostBodyRaw(true)
</code>```

if you declare body as:

```<code>def body = org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric(20)
</code>```

you will see that each threads sends a random string of 20 alphanumeric characters for each virtual user on each iteration.

See Top 8 JMeter Java Classes You Should Be Using with Groovy article for more information on JMeter API shorthands available for JSR223 Test Elements.

Body:
JSR223 PreProcessor has sampler shortcut, if JSR223 Pre-Processor is applied to the HTTP Request sampler the sampler is mapped to HTTPSamplerProxy

Therefore you can add the generated value to the body of the HTTP Request sampler as:

sampler.addNonEncodedArgument('', body, '')
sampler.setPostBodyRaw(true)

if you declare body as:

def body = org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric(20)

you will see that each threads sends a random string of 20 alphanumeric characters for each virtual user on each iteration.

See Top 8 JMeter Java Classes You Should Be Using with Groovy article for more information on JMeter API shorthands available for JSR223 Test Elements.