问:
Is there a function to cut a multiple the same values on combobox in c#
PIC
I try to show all the values that are not repeated.

This is for software that will display a meteorological report

```<code>        private void frm_main_Load(object sender, EventArgs e)
    {
        string path = @"C:\Meteo";

        if (Directory.Exists(path))
        {
            listBox1.Items.Clear();
            string[] files = Directory.GetFiles(path);

            string[] dirs = Directory.GetDirectories(path);

            foreach (string file in files)
            {
                var formattedName = Path.GetFileName(file).Split('_').First();

                //Показва и годината и месеца
                //var formattedName = string.Join("_", Path.GetFileName(file).Split('_').Skip(1).Take(2));

                comboBox2.Items.Add(Path.GetFileName(formattedName));

                listBox1.Items.Add(Path.GetFileName(file));
                //comboBox2.Items.Add(Path.GetFileName(formattedName));

            }

            foreach (string dir in dirs)
            {
                listBox1.Items.Add(Path.GetFileName(path));
            }
        }

        else

        {
            MessageBox.Show("Директорията Meteo не е октирта в системен диск 'C:\'");
            Application.ExitThread();
        }
    }
</code>```

I expect only non-repeatable values to appear.
Picture: values of combobox

答:
You can simply not add the value if the combobox already contains the value.

Example:

```<code>string[] someValues = { "one", "two", "two", "three", "four", "four", "four", "five", "six", "seven", "eight", "nine", "ten", "ten" };

foreach(string val in someValues)
{
    // Only add the value to combobox if the combobox doesn't already contain it
    if (!comboBox1.Items.Contains(val))
    {
        comboBox1.Items.Add(val);
    }
}
</code>```

Body:
PIC
I try to show all the values that are not repeated.

This is for software that will display a meteorological report

        private void frm_main_Load(object sender, EventArgs e)
    {
        string path = @"C:\Meteo";

        if (Directory.Exists(path))
        {
            listBox1.Items.Clear();
            string[] files = Directory.GetFiles(path);

            string[] dirs = Directory.GetDirectories(path);

            foreach (string file in files)
            {
                var formattedName = Path.GetFileName(file).Split('_').First();

                //Показва и годината и месеца
                //var formattedName = string.Join("_", Path.GetFileName(file).Split('_').Skip(1).Take(2));

                comboBox2.Items.Add(Path.GetFileName(formattedName));

                listBox1.Items.Add(Path.GetFileName(file));
                //comboBox2.Items.Add(Path.GetFileName(formattedName));

            }

            foreach (string dir in dirs)
            {
                listBox1.Items.Add(Path.GetFileName(path));
            }
        }

        else

        {
            MessageBox.Show("Директорията Meteo не е октирта в системен диск 'C:\'");
            Application.ExitThread();
        }
    }

I expect only non-repeatable values to appear.
Picture: values of combobox

Body:
You can simply not add the value if the combobox already contains the value.

Example:

string[] someValues = { "one", "two", "two", "three", "four", "four", "four", "five", "six", "seven", "eight", "nine", "ten", "ten" };

foreach(string val in someValues)
{
    // Only add the value to combobox if the combobox doesn't already contain it
    if (!comboBox1.Items.Contains(val))
    {
        comboBox1.Items.Add(val);
    }
}


来源: stackexchange

问:
How to check whether Java plugins are installed or not in a browser using Code .?
How to check whether Java plugins are installed or not in a browser using java or javascript or JSP Code .?</p>

答:
Use deployJava.js  to check the java installation.

```<code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE> New Document </TITLE>
<META NAME="Generator" CONTENT="EditPlus">
<META NAME="Author" CONTENT="">
<META NAME="Keywords" CONTENT="">
<META NAME="Description" CONTENT="">
</HEAD>
<SCRIPT LANGUAGE="JavaScript" src="deployJava.js">
</SCRIPT>
<script type="text/javascript">
function call()
{
    if (deployJava.versionCheck("1.6.0+") || deployJava.versionCheck("1.4") || deployJava.versionCheck("1.5.0*"))
    {
        alert("Java is Enabled");
    } else
    {
        alert("Java is Not Enabled");
    }
}
</script>
<BODY onload="call();">
</BODY>
</HTML>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Use deployJava.js  to check the java installation.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE> New Document </TITLE>
<META NAME="Generator" CONTENT="EditPlus">
<META NAME="Author" CONTENT="">
<META NAME="Keywords" CONTENT="">
<META NAME="Description" CONTENT="">
</HEAD>
<SCRIPT LANGUAGE="JavaScript" src="deployJava.js">
</SCRIPT>
<script type="text/javascript">
function call()
{
    if (deployJava.versionCheck("1.6.0+") || deployJava.versionCheck("1.4") || deployJava.versionCheck("1.5.0*"))
    {
        alert("Java is Enabled");
    } else
    {
        alert("Java is Not Enabled");
    }
}
</script>
<BODY onload="call();">
</BODY>
</HTML>


问:
ISO8601 Format are different in MongoDB and iOS
I want to post a Date with IOS8601 format from iOS to NodeJS(mongoDB), and get from NodeJS to iOS.

But the dateformat are different from both platform.

iOS side: 2019-05-26T17:10:10Z
mongoDB side: 2019-05-26T17:10:10.000Z

which means the date example post to mongoDB, then the date get back with the extra .000.

For iOS:

```<code>extension Date {
  var ISO8601String: String? {
      let formatter = ISO8601DateFormatter()
      return formatter.string(from: self)
  }
}
</code>```

The ISO8601String output is: YYYY-MM-ddTHH:mm:ssZ

For mongoDB

Schema:

```<code>var FooSchema = Schema({

    date: {
      type: Date,
      required: true
    }
})
</code>```

Usage:

```<code>let date = new Date(req.body.date) // I also used req.body.date directlly
new Foo(date: date)
</code>```

On iOS side get the ISO8601 date was added .000.
which is yyyy-MM-dd'T'HH:mm:ss.SSS'Z'

Here is the doc reference:

Do I have to convert at least from one side?

答:
In iOS you can generate a formatter that includes milliseconds in iOS 11 and later with:

```<code>let formatter = ISO8601DateFormatter()
formatter.formatOptions.insert(.withFractionalSeconds)
</code>```

If you need to do this with iOS versions before that, you have to use DateFormatter:

```<code>let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSX"
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.timeZone = TimeZone(secondsFromGMT: 0)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to post a Date with IOS8601 format from iOS to NodeJS(mongoDB), and get from NodeJS to iOS.

But the dateformat are different from both platform.

iOS side: 2019-05-26T17:10:10Z
mongoDB side: 2019-05-26T17:10:10.000Z

which means the date example post to mongoDB, then the date get back with the extra .000.

For iOS:

extension Date {
  var ISO8601String: String? {
      let formatter = ISO8601DateFormatter()
      return formatter.string(from: self)
  }
}

The ISO8601String output is: YYYY-MM-ddTHH:mm:ssZ

For mongoDB

Schema:

var FooSchema = Schema({

    date: {
      type: Date,
      required: true
    }
})

Usage:

let date = new Date(req.body.date) // I also used req.body.date directlly
new Foo(date: date)

On iOS side get the ISO8601 date was added .000.
which is yyyy-MM-dd'T'HH:mm:ss.SSS'Z'

Here is the doc reference:

Do I have to convert at least from one side?

Body:
In iOS you can generate a formatter that includes milliseconds in iOS 11 and later with:

let formatter = ISO8601DateFormatter()
formatter.formatOptions.insert(.withFractionalSeconds)

If you need to do this with iOS versions before that, you have to use DateFormatter:

let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSX"
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.timeZone = TimeZone(secondsFromGMT: 0)


问:
how to do a SQL Join that returns the rows that are not present in my table 2
I want to run a query between my two tables and returns the results to me the lines that are not present in my table 2</p>

答:
```<code>select * from table1
         left join table2
         on table1.id=table2.id
         where table2.id is null
</code>```


问:
Can I bind AppBarButtons into CommandBar.PrimaryCommands
I want to bind an AppBarButtons into a CommandBar.

I tried looking through the CommandBar documentation and found out that part is PrimaryCommands but I try to bind it but it read-only and I can't write anything to it.

Here is what I wanted to do.

<CommandBar PrimaryCommands={x:Bind AdditionCommands}/>
```

<p>So, later on, I could just:</p>

<pre class="lang-xml prettyprint-override"><code><customUI:PauseMenu>
    <customUI:PauseMenu.AdditionCommands>
        <AppBarButton Label="Some"/>
        <AppBarButton Label="Commands"/>
        <AppBarButton Label="Heres"/>
    </customUI:PauseMenu.AdditionCommands>
</customUI:PauseMenu>
</code>```

答:
Can I bind AppBarButtons into CommandBar.PrimaryCommands

CommandBar does not support bind PrimaryCommands like the above. The only implementation way of PrimaryCommands is create list AppBarButton under that  node. Please refer this document.

```<code><CommandBar.PrimaryCommands>
    <AppBarButton Label="Some"/>
    <AppBarButton Label="Commands"/>
    <AppBarButton Label="Heres"/>
</CommandBar.PrimaryCommands>
</code>```

Body:
I want to bind an AppBarButtons into a CommandBar.

I tried looking through the CommandBar documentation and found out that part is PrimaryCommands but I try to bind it but it read-only and I can't write anything to it.

Here is what I wanted to do.

<CommandBar PrimaryCommands={x:Bind AdditionCommands}/>

So, later on, I could just:

<customUI:PauseMenu>
    <customUI:PauseMenu.AdditionCommands>
        <AppBarButton Label="Some"/>
        <AppBarButton Label="Commands"/>
        <AppBarButton Label="Heres"/>
    </customUI:PauseMenu.AdditionCommands>
</customUI:PauseMenu>

Body:
Can I bind AppBarButtons into CommandBar.PrimaryCommands

CommandBar does not support bind PrimaryCommands like the above. The only implementation way of PrimaryCommands is create list AppBarButton under that  node. Please refer this document.

<CommandBar.PrimaryCommands>
    <AppBarButton Label="Some"/>
    <AppBarButton Label="Commands"/>
    <AppBarButton Label="Heres"/>
</CommandBar.PrimaryCommands>


问:
How to fix "Bot object has no attribute logs_from"
I've been trying to make a bot using discord.py, I want to make a command that deletes x number of messages. However, logs_from is not recognized as an attribute for the bot object.

I searched online and everyone seemed to have no problem using logs_from.

import discord
from discord.ext import commands
from discord.ext.commands import Bot

Client = discord.Client()
bot = commands.Bot(command_prefix=">")

@bot.command(pass_context=True,)
async def purge(ctx, number):
    number = int(number)
    if number > 99 or number < 1:
        await ctx.send("I can only delete messages within a range of 1 - 99")
    else:
        author = ctx.message.author
        authorID = author.id
        mgs = []
        number = int(number)
        channel = ctx.message.channel
        async for x in bot.logs_from((channel), limit = int(number+1)):
            mgs.append(x)
        await delete_messages(mgs)
        await ctx.send('Messages deleted!', delete_after=4)```
</code>```

答:
As part of the stateful model changes, Client.logs_from has been replaced with Messageable.history.

If you're trying to adapt old materials into the newer versions of discord.py, you should read the migration guide.


问:
Hosting multiple product APIs in single ASP.NET Core WebAPI Service
I am designing an ASP.NET Core based Web API, which needs to support multiple variants of my product, let's say based on a license or the variety which it was installed.

Instead of going for multiple services for each type of product, I thought of a single service which houses/hosts multiple Endpoints or URLs. I will make this configurable in the appsettings.json at the time of installation.

I am aware of the UseUrls on creating the WebHost, but can I bind the specific URL in a set of URLs to specific Controllers?

Code:

```<code>WebHost.CreateDefaultBuilder(args)
.UseUrls("http://localhost:5000;http://localhost:5001;https://localhost:5002")
</code>```

Expect

```<code>https://localhost:5000/ --> Product1Controller
https://localhost:5001/ --> Product2Controller
https://localhost:5002/ --> Product2Controller
</code>```

I am new to the ASP.NET Core, please help me if this is achievable or not.
Thanks in advance.

答:
A workaround is to add custom Constraint on api controller which is enabled with specific port.

1.Create  a PortActionConstraint class:

```<code>[AttributeUsage(AttributeTargets.Class)]
public class PortActionConstraint : ActionMethodSelectorAttribute
{
    public PortActionConstraint(int port)
    {
        Port = port;
    }

    public int Port { get; }

    public override bool IsValidForRequest(RouteContext routeContext, ActionDescriptor action)
    {
        //external port
        var externalPort = routeContext.HttpContext.Request.Host.Port;
        //local port
        var localPort = routeContext.HttpContext.Connection.LocalPort;
        //write here your custom logic. for example
        return Port == localPort;
    }
}
</code>```

2.Add attribute with correspond port number on all controller like

```<code>[PortActionConstraint(5000)]
[Route("api/[controller]")]
[ApiController]
public class Product1Controller : ControllerBase
</code>```

Body:
I am designing an ASP.NET Core based Web API, which needs to support multiple variants of my product, let's say based on a license or the variety which it was installed.

Instead of going for multiple services for each type of product, I thought of a single service which houses/hosts multiple Endpoints or URLs. I will make this configurable in the appsettings.json at the time of installation.

I am aware of the UseUrls on creating the WebHost, but can I bind the specific URL in a set of URLs to specific Controllers?

Code:

WebHost.CreateDefaultBuilder(args)
.UseUrls("http://localhost:5000;http://localhost:5001;https://localhost:5002")

Expect

https://localhost:5000/ --> Product1Controller
https://localhost:5001/ --> Product2Controller
https://localhost:5002/ --> Product2Controller

I am new to the ASP.NET Core, please help me if this is achievable or not.
Thanks in advance.

Body:
A workaround is to add custom Constraint on api controller which is enabled with specific port.

1.Create  a PortActionConstraint class:

[AttributeUsage(AttributeTargets.Class)]
public class PortActionConstraint : ActionMethodSelectorAttribute
{
    public PortActionConstraint(int port)
    {
        Port = port;
    }

    public int Port { get; }

    public override bool IsValidForRequest(RouteContext routeContext, ActionDescriptor action)
    {
        //external port
        var externalPort = routeContext.HttpContext.Request.Host.Port;
        //local port
        var localPort = routeContext.HttpContext.Connection.LocalPort;
        //write here your custom logic. for example
        return Port == localPort;
    }
}

2.Add attribute with correspond port number on all controller like

[PortActionConstraint(5000)]
[Route("api/[controller]")]
[ApiController]
public class Product1Controller : ControllerBase


问:
WPF Check box: Check changed handling
In WPF data binding, I can bind the IsChecked property to some data, e.g. user setting, but I need to handle "CheckChanged" event, I know I can seperately handle Checked, Unchecked event, but is there any way to get notified when this value is changed?

```<code><CheckBox Content="Case Sensitive" IsChecked="{Binding bSearchCaseSensitive,
          Source={x:Static Properties:Settings.Default}}" />
</code>```

Note: I don't care if it is checked or unchecked. I just want to be notified when it is changed.

答:
A simple and proper way I've found to Handle Checked/Unchecked events using MVVM pattern is the Following, with Caliburn.Micro :

```<code> <CheckBox IsChecked="{Binding IsCheckedBooleanProperty}" Content="{DynamicResource DisplayContent}" cal:Message.Attach="[Event Checked] = [Action CheckBoxClicked()]; [Event Unchecked] = [Action CheckBoxClicked()]" />
</code>```

And implement a Method CheckBoxClicked() in the ViewModel, to do stuff you want.

Title: WPF Check box: Check changed handling

Body:
In WPF data binding, I can bind the IsChecked property to some data, e.g. user setting, but I need to handle "CheckChanged" event, I know I can seperately handle Checked, Unchecked event, but is there any way to get notified when this value is changed?

<CheckBox Content="Case Sensitive" IsChecked="{Binding bSearchCaseSensitive,
          Source={x:Static Properties:Settings.Default}}" />

Note: I don't care if it is checked or unchecked. I just want to be notified when it is changed.

Body:
A simple and proper way I've found to Handle Checked/Unchecked events using MVVM pattern is the Following, with Caliburn.Micro :

 <CheckBox IsChecked="{Binding IsCheckedBooleanProperty}" Content="{DynamicResource DisplayContent}" cal:Message.Attach="[Event Checked] = [Action CheckBoxClicked()]; [Event Unchecked] = [Action CheckBoxClicked()]" />

And implement a Method CheckBoxClicked() in the ViewModel, to do stuff you want.


问:
How to manually generate network parameters in Corda
I have manually created and distributed the required certificates for Corda nodes. Now for the nodes to start, among other things, they need to have a network parameter. The problem is that if I use the Corda network bootstrapper tool to generate the network parameter, the file will be signed by another issuer ("C=UK, L=London, OU=corda, O=R3, CN=Corda Node Root CA") which is different from the issuer of my certificates. My question is how can I manually create a network parameter so I can specify the correct issuer to avoid conflicts during node startup?

答:
So I have figured a way to create network parameters:</p>

```<code>private fun getSignedNetworkParameters(): NetworkParameters {

        //load the notary from a Keystore. This avoids having to start a flow from a node in order to retrieve NotaryInfo
        val notary = loadKeyStore("\\path-to-keystore\\keystore.jks", "keystore-password")

        val certificateAndKeyPair : CertificateAndKeyPair = notary.getCertificateAndKeyPair("entry-alias", "entry-password")
        val notaryParty = Party(certificateAndKeyPair.certificate)
        val notaryInfo = listOf(NotaryInfo(notaryParty, false))

        //map contract ID to the SHA-256 hash of its CorDapp contracts&states JAR file
        val whitelistedContractImplementations = mapOf(
                TestContract.TEST_CONTRACT_ID to listOf(getCheckSum(contractFile))
        )

        return NetworkParameters(minimumPlatformVersion = 3, notaries = notaryInfo,
                maxMessageSize = n, maxTransactionSize = n, modifiedTime = Instant.now(),
                epoch = 1, whitelistedContractImplementations = whitelistedContractImplementations)
    }
</code>```

Body:
So I have figured a way to create network parameters:

private fun getSignedNetworkParameters(): NetworkParameters {

        //load the notary from a Keystore. This avoids having to start a flow from a node in order to retrieve NotaryInfo
        val notary = loadKeyStore("\\path-to-keystore\\keystore.jks", "keystore-password")

        val certificateAndKeyPair : CertificateAndKeyPair = notary.getCertificateAndKeyPair("entry-alias", "entry-password")
        val notaryParty = Party(certificateAndKeyPair.certificate)
        val notaryInfo = listOf(NotaryInfo(notaryParty, false))

        //map contract ID to the SHA-256 hash of its CorDapp contracts&states JAR file
        val whitelistedContractImplementations = mapOf(
                TestContract.TEST_CONTRACT_ID to listOf(getCheckSum(contractFile))
        )

        return NetworkParameters(minimumPlatformVersion = 3, notaries = notaryInfo,
                maxMessageSize = n, maxTransactionSize = n, modifiedTime = Instant.now(),
                epoch = 1, whitelistedContractImplementations = whitelistedContractImplementations)
    }


问:
how to display multiple permissions at once in xamarin.forms?
I want to show runtime permission popup for camera and location when the app starts or after splash screen.

I am using the NuGet package:https://github.com/jamesmontemagno/PermissionsPlugin

I have tried the below code on button click event.

```<code>private async void Button_Clicked(object sender, EventArgs e)
    {
        await GetPermissions();
    }

public static async Task<bool> GetPermissions()
    {
        bool permissionsGranted = true;

        var permissionsStartList = new List<Permission>()
        {
            Permission.Location,
            Permission.LocationAlways,
            Permission.LocationWhenInUse,
            Permission.Storage,
            Permission.Camera
        };

        var permissionsNeededList = new List<Permission>();
        try
        {
            foreach (var permission in permissionsStartList)
            {
                var status = await CrossPermissions.Current.CheckPermissionStatusAsync(permission);
                if (status != PermissionStatus.Granted)
                {
                    permissionsNeededList.Add(permission);
                }
            }
        }
        catch (Exception ex)
        {
        }

        var results = await CrossPermissions.Current.RequestPermissionsAsync(permissionsNeededList.ToArray());

        try
        {
            foreach (var permission in permissionsNeededList)
            {
                var status = PermissionStatus.Unknown;
                //Best practice to always check that the key exists
                if (results.ContainsKey(permission))
                    status = results[permission];
                if (status == PermissionStatus.Granted || status == PermissionStatus.Unknown)
                {
                    permissionsGranted = true;
                }
                else
                {
                    permissionsGranted = false;
                    break;
                }
            }
        }
        catch (Exception ex)
        {
        }
        return permissionsGranted;
    }
</code>```

Please give your suggestions or better approach for it.

答:
I want to show runtime permission popup for camera and location when
  the app starts or after splash screen.

If you want to permission popup for camera and location when the app starts or after splash screen.

You can call the GetPermissions method in OnAppearing() of your MainPage:

```<code>public partial class MainPage : ContentPage
{
    public MainPage()
    {
        InitializeComponent();
    }

    protected override async void OnAppearing()
    {
        base.OnAppearing();

        bool a = await GetPermissions();
    }

    public static async Task<bool> GetPermissions()
    {
        ....
    }
}
</code>```

Note:

As mentioned here, When you install PermissionsPlugin it will also install a file called "MainApplication.cs" into your Android app and that needs to be there.

And make sure you have selected the READ_EXTERNAL_STORAGE, WRITE_EXTERNAL_STORAGE, ACCESS_COARSE_LOCATION and ACCESS_FINE_LOCATION  permissions by right clicking xxxx.Android project--> Properties -->  Android Mainfest --> Required permissions.

I have uploaded a sample and you can check. Let me know if it works.

Body:
I want to show runtime permission popup for camera and location when the app starts or after splash screen.

I am using the NuGet package:https://github.com/jamesmontemagno/PermissionsPlugin

I have tried the below code on button click event.

private async void Button_Clicked(object sender, EventArgs e)
    {
        await GetPermissions();
    }

public static async Task<bool> GetPermissions()
    {
        bool permissionsGranted = true;

        var permissionsStartList = new List<Permission>()
        {
            Permission.Location,
            Permission.LocationAlways,
            Permission.LocationWhenInUse,
            Permission.Storage,
            Permission.Camera
        };

        var permissionsNeededList = new List<Permission>();
        try
        {
            foreach (var permission in permissionsStartList)
            {
                var status = await CrossPermissions.Current.CheckPermissionStatusAsync(permission);
                if (status != PermissionStatus.Granted)
                {
                    permissionsNeededList.Add(permission);
                }
            }
        }
        catch (Exception ex)
        {
        }

        var results = await CrossPermissions.Current.RequestPermissionsAsync(permissionsNeededList.ToArray());

        try
        {
            foreach (var permission in permissionsNeededList)
            {
                var status = PermissionStatus.Unknown;
                //Best practice to always check that the key exists
                if (results.ContainsKey(permission))
                    status = results[permission];
                if (status == PermissionStatus.Granted || status == PermissionStatus.Unknown)
                {
                    permissionsGranted = true;
                }
                else
                {
                    permissionsGranted = false;
                    break;
                }
            }
        }
        catch (Exception ex)
        {
        }
        return permissionsGranted;
    }

Please give your suggestions or better approach for it.

Body:
I want to show runtime permission popup for camera and location when
  the app starts or after splash screen.

If you want to permission popup for camera and location when the app starts or after splash screen.

You can call the GetPermissions method in OnAppearing() of your MainPage:

public partial class MainPage : ContentPage
{
    public MainPage()
    {
        InitializeComponent();
    }

    protected override async void OnAppearing()
    {
        base.OnAppearing();

        bool a = await GetPermissions();
    }

    public static async Task<bool> GetPermissions()
    {
        ....
    }
}

Note:

As mentioned here, When you install PermissionsPlugin it will also install a file called "MainApplication.cs" into your Android app and that needs to be there.

And make sure you have selected the READ_EXTERNAL_STORAGE, WRITE_EXTERNAL_STORAGE, ACCESS_COARSE_LOCATION and ACCESS_FINE_LOCATION  permissions by right clicking xxxx.Android project--> Properties -->  Android Mainfest --> Required permissions.

I have uploaded a sample and you can check. Let me know if it works.


问:
Removing proxy part of grails domain object?
I want to get at an actual instance of a domain object. That is, I need to serialize the object, and I'm trying to use the domain object on two sides of an httpinvoker chain. Is there a way to get a fully-loaded domain object that doesn't have any grails wiring, so that I can serialize it?

答:
We do GrailsHibernateUtil.unwrapIfProxy(obj). It won't get rid of Grails injected methods and such - only of Hibernate/GORM proxy, but it should be sufficient.

edit:

Sorry for asking, but did you declare your domain class as implements Serializable?

It might be something you add/inject into your class, like in Grails non-bug 6379.

This piece of code (got it here) worked for me in grails console on a small domain class:

.

```<code>import org.codehaus.groovy.grails.orm.hibernate.cfg.GrailsHibernateUtil
import com.somegroup.domain.*

def loc = SomeDomainClass.get(1)
loc = GrailsHibernateUtil.unwrapIfProxy(loc)

ByteArrayOutputStream bos = new ByteArrayOutputStream()
ObjectOutput out = new ObjectOutputStream(bos)

out.writeObject(loc)
byte[] yourBytes = bos.toByteArray()
</code>```

Body:
We do GrailsHibernateUtil.unwrapIfProxy(obj). It won't get rid of Grails injected methods and such - only of Hibernate/GORM proxy, but it should be sufficient.

edit:

Sorry for asking, but did you declare your domain class as implements Serializable?

It might be something you add/inject into your class, like in Grails non-bug 6379.

This piece of code (got it here) worked for me in grails console on a small domain class:

.

import org.codehaus.groovy.grails.orm.hibernate.cfg.GrailsHibernateUtil
import com.somegroup.domain.*

def loc = SomeDomainClass.get(1)
loc = GrailsHibernateUtil.unwrapIfProxy(loc)

ByteArrayOutputStream bos = new ByteArrayOutputStream()
ObjectOutput out = new ObjectOutputStream(bos)

out.writeObject(loc)
byte[] yourBytes = bos.toByteArray()


问:
Display what AVSpeechSynthesizer is showing as subtitles with Swift
I have an array with quotations, and am using a button to start a random quotation playing from the array.

I'm wondering, how would I have the selected random quotation also displayed in the ViewController so that people can read what the speechsynthesizer is reading?

答:
How would I have the selected random quotation also displayed in the ViewController so that people can read what the speechsynthesizer is reading?

The best way to highlight the vocalized word is using the speechSynthesizer:willSpeakRangeOfSpeechString:utterance: method of the AVSpeechSynthesizerDelegate protocol.

Instead of copying and pasting the code snippet here, take a look at this complete and useful example (ObjC and Swift) that displays the vocalized word in a bold font with the speech synthesis.

...is there some way of using Subtitles.sizeToFit() so that the Label is split into 3 or more rows, instead of just "one row till infinity"?

In the Xcode Interface Builder - Attributes Inspector, set the value of the label property Lines to 0 and adapt your constraints to get a multiline presentation.


问:
How to move scrollbar(horizontal) pointer to the specific location?
i have a pagination at bottom of a page.after each click on pagination page get refreshed with new data and the clicked number is being highlighted..
the scrollbar is horizontal as shown in below image.
scrollbar image

when i click to last number of pagination, this no gets highlighted but scrollbar thumb not being moved.

this is my code for pagination:

    .pagination::-webkit-scrollbar {
          background-color:#D9D9D9;
          height:5px;
     }

    .pagination::-webkit-scrollbar-thumb {
               -webkit-box-shadow: inset 0 0 6px #0C62B3;
    }
```

<pre class="lang-html prettyprint-override"><code>    <ul class="pagination">

                    @for (int i = 1; i <= Model.PageCount; i++)
                    {

                        if (i != Model.CurrentPageIndex)
                        {
                                <li class="page-item">@i</li>
                        }
                        else
                        {
                               <li class="page-item active">@i</li>
                        }

                    }

    </ul>
</code>```

I was trying to give hardcoded value to scrollbar:

```<code>          $(document).ready(function () {
              var navwidth = $('.pagination');
              navwidth.scrollLeft(navwidth.scrollLeft() - 200);
          });
</code>```

but nothing has happened..

答:
Because the scrollbar is already to the left the function scrollLeft() returns 0. If you minus that with 200 you get -200 which wont work. If you add 200 it will work.

Also added a little css and random text to make the list show a horizontal scrollbar when overflowing.

$(document).ready(function() {
  var navwidth = $('.pagination');
  navwidth.scrollLeft(navwidth.scrollLeft() + 200);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.pagination {
  overflow-x: scroll;
  white-space: nowrap;
}

.pagination::-webkit-scrollbar {
  background-color: #D9D9D9;
  height: 5px;
}

.pagination::-webkit-scrollbar-thumb {
  -webkit-box-shadow: inset 0 0 6px #0C62B3;
}</code>```

Lorem ipsum dolor sit amet, consectetur adipiscing elit. In tincidunt, lorem at cursus condimentum, libero enim scelerisque neque, et placerat magna turpis sed sapien. Phasellus vitae nulla sit amet est malesuada vulputate.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. In tincidunt, lorem at cursus condimentum, libero enim scelerisque neque, et placerat magna turpis sed sapien. Phasellus vitae nulla sit amet est malesuada vulputate.

```

Body:
i have a pagination at bottom of a page.after each click on pagination page get refreshed with new data and the clicked number is being highlighted..
the scrollbar is horizontal as shown in below image.
scrollbar image

when i click to last number of pagination, this no gets highlighted but scrollbar thumb not being moved.

this is my code for pagination:

    .pagination::-webkit-scrollbar {
          background-color:#D9D9D9;
          height:5px;
     }

    .pagination::-webkit-scrollbar-thumb {
               -webkit-box-shadow: inset 0 0 6px #0C62B3;
    }

                    @for (int i = 1; i <= Model.PageCount; i++)
                    {

                        if (i != Model.CurrentPageIndex)
                        {

@i

                        }
                        else
                        {

@i

                        }

                    }

I was trying to give hardcoded value to scrollbar:

          $(document).ready(function () {
              var navwidth = $('.pagination');
              navwidth.scrollLeft(navwidth.scrollLeft() - 200);
          });

but nothing has happened..

Body:
Because the scrollbar is already to the left the function scrollLeft() returns 0. If you minus that with 200 you get -200 which wont work. If you add 200 it will work.

Also added a little css and random text to make the list show a horizontal scrollbar when overflowing.

$(document).ready(function() {
  var navwidth = $('.pagination');
  navwidth.scrollLeft(navwidth.scrollLeft() + 200);
});

.pagination {
  overflow-x: scroll;
  white-space: nowrap;
}

.pagination::-webkit-scrollbar {
  background-color: #D9D9D9;
  height: 5px;
}

.pagination::-webkit-scrollbar-thumb {
  -webkit-box-shadow: inset 0 0 6px #0C62B3;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="pagination">
  <li class="page-item"><a class="page-link" href="javascript:PagerClick(@i);">Lorem ipsum dolor sit amet, consectetur adipiscing elit. In tincidunt, lorem at cursus condimentum, libero enim scelerisque neque, et placerat magna turpis sed sapien. Phasellus vitae nulla sit amet est malesuada vulputate.</a></li>
  <li class="page-item active"><a class="page-link" href="javascript:PagerClick(@i);">Lorem ipsum dolor sit amet, consectetur adipiscing elit. In tincidunt, lorem at cursus condimentum, libero enim scelerisque neque, et placerat magna turpis sed sapien. Phasellus vitae nulla sit amet est malesuada vulputate.</a></li>
</ul>


问:
Authentication with p12 key give error User cannot access account
I have a MVC web-application that update the products on the eCommerce site. Now we enrolled into the google merchant center and my objective is to update the products at the same time. I am using the Google.Apis.ShoppingContent.v2_1 API.

This is my API Credentials

This is my API service account

I have used the google account email address for the user as well as the service account email but with the same result.

I have the following

```<code>    static string[] Scopes = { ShoppingContentService.Scope.Content};
    static string P12Secret =  @"~\Content\XXXXXX-5cab03fb904a.p12";
    static string userName = "serviceaccount@gserviceaccount.com";
</code>```

    static public async Task RunTest2()
        {
            var certificate = new X509Certificate2(P12Secret, "notasecret", X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable);
            var credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(userName)
            {
                Scopes = Scopes
            }.FromCertificate(certificate));

            var service = new ShoppingContentService(new BaseClientService.Initializer
            {
                ApplicationName = ApplicationName,
                HttpClientInitializer = credential
            });

            try
            {
                var result = await service.Products.List("My MerchantID").ExecuteAsync();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
```

When I execute var result = await service.Products.List("My MerchantID").ExecuteAsync(); I get the error

e.Message = "Google.Apis.Requests.RequestError\nUser cannot access account 123456789 [401]\r\nErrors [\r\n\tMessage[User cannot access account 123456789 ] Location[ - ] Reason[auth/account_access_denied] Domain[content.ContentErrorDomain]\r\n]\r\n"

答:
Documentaiton

Service accounts are special Google accounts that can be used by applications to access Google APIs programmatically via OAuth 2.0. A service account uses an OAuth 2.0 flow that does not require human authorization. Instead, it uses a key file that only your application can access. This guide discusses how to access the Content API for Shopping with service accounts.

Service accounts need to be pre authorized.  If its not then it doesnt have access to any data.

User cannot access account 123456789

Means that it does not have access you have forgotten to grant it access.  Check the Documentaiton look for the section below follow all of the steps.

Body:
I have a MVC web-application that update the products on the eCommerce site. Now we enrolled into the google merchant center and my objective is to update the products at the same time. I am using the Google.Apis.ShoppingContent.v2_1 API.

This is my API Credentials

This is my API service account

I have used the google account email address for the user as well as the service account email but with the same result.

I have the following

    static string[] Scopes = { ShoppingContentService.Scope.Content};
    static string P12Secret =  @"~\Content\XXXXXX-5cab03fb904a.p12";
    static string userName = "serviceaccount@gserviceaccount.com";

    static public async Task RunTest2()
        {
            var certificate = new X509Certificate2(P12Secret, "notasecret", X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable);
            var credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(userName)
            {
                Scopes = Scopes
            }.FromCertificate(certificate));

            var service = new ShoppingContentService(new BaseClientService.Initializer
            {
                ApplicationName = ApplicationName,
                HttpClientInitializer = credential
            });

            try
            {
                var result = await service.Products.List("My MerchantID").ExecuteAsync();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }

When I execute var result = await service.Products.List("My MerchantID").ExecuteAsync(); I get the error

e.Message = "Google.Apis.Requests.RequestError\nUser cannot access account 123456789 [401]\r\nErrors [\r\n\tMessage[User cannot access account 123456789 ] Location[ - ] Reason[auth/account_access_denied] Domain[content.ContentErrorDomain]\r\n]\r\n"


问:
How to add space between all children of div
I have a styled div where I want some space between all the children. As the children can be any other component (buttons, divs, paragraphs, etc) in the project I can't add padding to those, so I want to find a way to do it from the styled div itself. There is also no telling how many children the div will have. Sometimes it can be empty, other times it can have three or four children.

Is there a way to do this?

I've tried several things, but so far nothing has worked.

This is the div as it is now:
(the esthetic styling is done in its parent)

```<code>const StyledBox = styled.div`
    float: right;
    min-width: 50px;
`
</code>```

This div is part of Header

```<code>const StyledParent = styled.div`
    width: 100%;
    min-height: 50px;
    display: flex;
    flex-wrap: wrap;
    flex-direction: column;
`

const StyledBottom = styled.div`
    display: flex;
    align-items: center;
    justify-content: space-between;
    flex-wrap: wrap;
    flex-direction: row;
    min-height: 65px;
`

const Header = (props) => {
    return (
        <StyledParent {...props}>
            <StyledTop {...props}>
            </StyledTop>
            <StyledBottom>
                <StyledBox {...props}></StyledBox>
            </StyledBottom>
        </StyledParent>
    )
}
</code>```

答:
You could style any element inside your div by using the * css selector :

```<code>const Div = styled.div`
 * {
   //style applied to every elements
  }
`;
</code>```

To add space after each of them, you could use the after pseudo-class like this:

```<code>const Div = styled.div`
  * {
    &::after {
      content: " "; //space inserted after each element
    }
  }
`
</code>```

Body:
I have a styled div where I want some space between all the children. As the children can be any other component (buttons, divs, paragraphs, etc) in the project I can't add padding to those, so I want to find a way to do it from the styled div itself. There is also no telling how many children the div will have. Sometimes it can be empty, other times it can have three or four children.

Is there a way to do this?

I've tried several things, but so far nothing has worked.

This is the div as it is now:
(the esthetic styling is done in its parent)

const StyledBox = styled.div`
    float: right;
    min-width: 50px;
`

This div is part of Header

const StyledParent = styled.div`
    width: 100%;
    min-height: 50px;
    display: flex;
    flex-wrap: wrap;
    flex-direction: column;
`

const StyledBottom = styled.div`
    display: flex;
    align-items: center;
    justify-content: space-between;
    flex-wrap: wrap;
    flex-direction: row;
    min-height: 65px;
`

const Header = (props) => {
    return (

            </StyledBottom>
        </StyledParent>
    )
}

Body:
You could style any element inside your div by using the * css selector :

const Div = styled.div`
 * {
   //style applied to every elements
  }
`;

To add space after each of them, you could use the after pseudo-class like this:

const Div = styled.div`
  * {
    &::after {
      content: " "; //space inserted after each element
    }
  }
`


问:
Running background processes in iPhone
Can we run following tasks in the back ground in a iPhone application:</p>

```<code>√ Camera --> Take photo (timer = infinity) (keep on taking photos)
√ Video
√ Backlight --> On for certain duration (Customizable)
√ Flickering --> 5secs (Customizable)
√ Vibration (Background)
√ Voice Call --> Long call or multiple calls (Call duration/Time b/w calls/
</code>```

答:
Camera - no

Video - no

Backlight - no

Flickering - don't know what this means

Vibration - could be triggered with Push

Voice Call - yes, VOIP is allowed

Title: Running background processes in iPhone

Body:
Can we run following tasks in the back ground in a iPhone application:

√ Camera --> Take photo (timer = infinity) (keep on taking photos)
√ Video
√ Backlight --> On for certain duration (Customizable)
√ Flickering --> 5secs (Customizable)
√ Vibration (Background)
√ Voice Call --> Long call or multiple calls (Call duration/Time b/w calls/


问:
How to match this date format with a regex?
hi to all regex master out there, I know you have a work around with regards to my problem. hehe

```<code>02-May-2011
</code>```

or

```<code>22-May-2011
</code>```

or

```<code>2-May-2011
</code>```

(dd-MMM-yyyy)
with yyyy not accepting any other characters than digit

答:
Since it is date, which you are trying to find a match, using SimpleDateFormat instead of a regex based match check should be the appropriate solution. Hopefully, the below snippet should do the job.</p>

```<code>public static boolean dateFormatValidate(String strDate,String dateFormat)
{
    SimpleDateFormat formatter = new SimpleDateFormat(dateFormat);
    String strParsed = null;
    Date parsed =null;

    try
    {
        parsed = formatter.parse(strDate);
        strParsed = formatter.format(parsed);
    }
    catch (ParseException e)
    {
        MYLogger.logger.info(e.getMessage());
    }

    return strDate.equals(strParsed);
}
</code>```

Body:
hi to all regex master out there, I know you have a work around with regards to my problem. hehe

02-May-2011

or

22-May-2011

or

2-May-2011

(dd-MMM-yyyy)
with yyyy not accepting any other characters than digit

Body:
Since it is date, which you are trying to find a match, using SimpleDateFormat instead of a regex based match check should be the appropriate solution. Hopefully, the below snippet should do the job.

public static boolean dateFormatValidate(String strDate,String dateFormat)
{
    SimpleDateFormat formatter = new SimpleDateFormat(dateFormat);
    String strParsed = null;
    Date parsed =null;

    try
    {
        parsed = formatter.parse(strDate);
        strParsed = formatter.format(parsed);
    }
    catch (ParseException e)
    {
        MYLogger.logger.info(e.getMessage());
    }

    return strDate.equals(strParsed);
}


问:
How to add partition in presto?
In hive I can do it by:

ALTER TABLE xxx ADD PARTITION
  (datehour='yy')  LOCATION
  'zz';

How can I do it in presto?

答:
Currently, Presto Hive connector does not provide means for creating new partitions at arbitrary locations. If your partition location is under table location, you can use Presto Hive connector procedures:

system.create_empty_partition -- creates a new empty partition with specified values for partition keys

system.sync_partition_metadata -- synchronizes partition list in Metastore with the partitions on the storage

If you want to create/declare partitions somewhere else than under table's location, please file an issue.

Title: How to add partition in presto?


问:
Can I use same curl handle for different urls? (trying to download data from multiple pages of one url)
I am trying to download data from one url which has multiple pages.
ex) https://stackoverflow.com/questions/tagged/c%2b%2b?sort=newest&page=2&pagesize=15
I would like to download all the data from different pages
ex) pages=1, pages=2, pages=3 etc..

If I create a curl handle with one url with certain page,
will it be okay to replace urls (only page number) without worrying about performance?

I've created curl handle every time I move to next page and download the data.
I got an advice from other people that it would be better to create a ssl session and persist its connection, so that I don't have to go through all the SSL handshake whenever I create SSL connections.

Accordint to Libcurl page, it is recommending to use same handle for performance, but I am not sure I could do it with different URLs.

答:
You can and should re-use the same curl instance whenever possible. Just keep on repeating curl_easy_setopt(CURLOPT_URL, ...); curl_easy_perform(...); calls.

Additional notes:

You can download multiple URLs in parallel if you use the curl_multi_init interface (example).

StackExchange has a very good REST API. There is no need to scrape it.


问:
Understanding problem Doctrine 2 ORM Query Builder in Symfony 4
I hope there are a few helpful and prefer German Symfony experts. For many years I have been working with PHP and now I tryed in a framework. I chose Symfony now because I like the components the most. The QueryBuilder and I stand on a war foot - I just do not understand it. Storing values works very well so far, though I doubt that I'm doing this in the sense of the framework. I'm really helpless. Currently  I managing it by chasing everything in raw format but I'm not really happy with it.

How I can implement the following with Doctrine?

```<code>use App\Entity\Questions;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Doctrine\ORM\EntityManager;

class QuestionsController extends AbstractController
{
/**
 * @Route("/addquestion", methods={"POST","HEAD"})
 */
public function addQuestion()
{
    $entityManager = $this->getDoctrine()->getManager();

    $RAW_QUERY = 'SELECT COUNT(*) AS c FROM questions WHERE questToID = '.$_POST['u'].' AND  questFrom = '.$this->getUser()->getId().';';

    $statement = $entityManager->getConnection()->prepare($RAW_QUERY);
    $statement->execute();

    $total = $statement->fetchAll();

    if($total[0]['c'] >= 3)
    {
        return new Response('error|Du kannst der selben Person maximal drei Fragen stellen.');
    }
 [...]
</code>```

I have already tried to implement this, and many other things (no avail):
Count Rows in Doctrine QueryBuilder

Since I speak bad English, I very much hope that you understand me…

答:
One simple way of doing that would be something like this (with the assumption that you have a "Question" entity - and that the fields defined there are matching with the column names from your raw query).

```<code>$em = $this->getDoctrine()->getManager();
$userQuestions = $em->getRepository(Question:class)->findAll(['questToID' => $_POST['u'], 'questFrom ' => $this->getUser()->getId()]);

$total = count($userQuestion);
</code>```

Or if you prefer to have just the count from the query instead of fetching all the matching objects and counting them, you can write the query builder part something like this (in this format this is meant to be written in your controller as you have with your raw query - in general the "correct" place would be QuestionRepository.php class from where this would be just called in controller):

```<code>$em = $this->getDoctrine()->getManager();
$qb = $em->createQueryBuilder('q');
$qb->select('count(q)');
$qb->andWhere('q.questToID = :questToID');
$qb->andWhere('q.questFrom = :questFrom');

$qb->setParameter('questToID', $_POST['u']);
$qb->setParameter('questFrom ', $this->getUser()->getId());

$total = $qb->getQuery()->getSingleScalarResult();
</code>```

Body:
I hope there are a few helpful and prefer German Symfony experts. For many years I have been working with PHP and now I tryed in a framework. I chose Symfony now because I like the components the most. The QueryBuilder and I stand on a war foot - I just do not understand it. Storing values works very well so far, though I doubt that I'm doing this in the sense of the framework. I'm really helpless. Currently  I managing it by chasing everything in raw format but I'm not really happy with it.

How I can implement the following with Doctrine?

use App\Entity\Questions;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Doctrine\ORM\EntityManager;

class QuestionsController extends AbstractController
{
/**
 * @Route("/addquestion", methods={"POST","HEAD"})
 */
public function addQuestion()
{
    $entityManager = $this->getDoctrine()->getManager();

    $RAW_QUERY = 'SELECT COUNT(*) AS c FROM questions WHERE questToID = '.$_POST['u'].' AND  questFrom = '.$this->getUser()->getId().';';

    $statement = $entityManager->getConnection()->prepare($RAW_QUERY);
    $statement->execute();

    $total = $statement->fetchAll();

    if($total[0]['c'] >= 3)
    {
        return new Response('error|Du kannst der selben Person maximal drei Fragen stellen.');
    }
 [...]

I have already tried to implement this, and many other things (no avail):
Count Rows in Doctrine QueryBuilder

Since I speak bad English, I very much hope that you understand me…

Body:
One simple way of doing that would be something like this (with the assumption that you have a "Question" entity - and that the fields defined there are matching with the column names from your raw query).

$em = $this->getDoctrine()->getManager();
$userQuestions = $em->getRepository(Question:class)->findAll(['questToID' => $_POST['u'], 'questFrom ' => $this->getUser()->getId()]);

$total = count($userQuestion);

Or if you prefer to have just the count from the query instead of fetching all the matching objects and counting them, you can write the query builder part something like this (in this format this is meant to be written in your controller as you have with your raw query - in general the "correct" place would be QuestionRepository.php class from where this would be just called in controller):

$em = $this->getDoctrine()->getManager();
$qb = $em->createQueryBuilder('q');
$qb->select('count(q)');
$qb->andWhere('q.questToID = :questToID');
$qb->andWhere('q.questFrom = :questFrom');

$qb->setParameter('questToID', $_POST['u']);
$qb->setParameter('questFrom ', $this->getUser()->getId());

$total = $qb->getQuery()->getSingleScalarResult();


问:
Suppress onChange and only use onBlur to a React input component
I have a component called Test that receives 2 props: CurrentPage and OnPageRequest: (currentPage: number) => void

When the parent component uses Test, it sets the Current page number in its state. As you update, the input field below, that value gets fed back up to the parent component via the OnPageRequest as:

OnPageRequest(e.target.value);

wherein return, the parent component updates its current page number in the state.

Test component:

```<code>const handlePageNumberBlur = (e) => {
    OnPageRequest(e.target.value);
}

render() {
    return (
        <input
            title="Current Page"
            onBlur={handlePageNumberBlur}
            aria-label="Current Page"
            min="1"
            max={TotalPages}
            placeholder="1"
            type="number"
            value={this.props.CurrentPage} />
    )
}
</code>```

I'm trying to write Test in such a way so that it only fires back the newly inputted value only when the onBlur event is triggered. But I've learned that with the above code, it never updates the value. It only does it if I have an onChange event where I do: OnPageRequest(e.target.value);

How can I get it to change only when onBlur fires?

SAMPLE: https://codesandbox.io/s/kumuc

答:
Try using defaultValue instead of value. The defaultValue prop only sets the value to the input on initial render and you won´t need to keep it updated if the value of the prop changes.

```<code><input
    { ... }
    defaultValue={this.prop.CurrentPage}
/>
</code>```

But this can also be an issue if you set CurrentPage after the input has rendered, which depends on where you get your initial value for the prop.

If you need to keep the input updated after the first render, you can update its value using Refs and the componentDidUpdate lifecycle method.

```<code>class TestComponent extends React.Component {
    constructor(props) {
        super(props);
        this.inputRef = React.createRef();
    }

    componentDidUpdate(prevProps) {
        if (this.inputRef.current.value != this.props.CurrentPage) {
            this.inputRef.current.value = this.props.CurrentPage;
        }
    }

    /* ... */

    render() {
        return <input
            { ... }
            defaultValue={this.props.CurrentPage}
            ref={this.inputRef}
        />
    }
}
</code>```

Body:
I have a component called Test that receives 2 props: CurrentPage and OnPageRequest: (currentPage: number) => void

When the parent component uses Test, it sets the Current page number in its state. As you update, the input field below, that value gets fed back up to the parent component via the OnPageRequest as:

OnPageRequest(e.target.value);

wherein return, the parent component updates its current page number in the state.

Test component:

const handlePageNumberBlur = (e) => {
    OnPageRequest(e.target.value);
}

render() {
    return (
        <input
            title="Current Page"
            onBlur={handlePageNumberBlur}
            aria-label="Current Page"
            min="1"
            max={TotalPages}
            placeholder="1"
            type="number"
            value={this.props.CurrentPage} />
    )
}

I'm trying to write Test in such a way so that it only fires back the newly inputted value only when the onBlur event is triggered. But I've learned that with the above code, it never updates the value. It only does it if I have an onChange event where I do: OnPageRequest(e.target.value);

How can I get it to change only when onBlur fires?

SAMPLE: https://codesandbox.io/s/kumuc

Body:
Try using defaultValue instead of value. The defaultValue prop only sets the value to the input on initial render and you won´t need to keep it updated if the value of the prop changes.

<input
    { ... }
    defaultValue={this.prop.CurrentPage}
/>

But this can also be an issue if you set CurrentPage after the input has rendered, which depends on where you get your initial value for the prop.

If you need to keep the input updated after the first render, you can update its value using Refs and the componentDidUpdate lifecycle method.

class TestComponent extends React.Component {
    constructor(props) {
        super(props);
        this.inputRef = React.createRef();
    }

    componentDidUpdate(prevProps) {
        if (this.inputRef.current.value != this.props.CurrentPage) {
            this.inputRef.current.value = this.props.CurrentPage;
        }
    }

    /* ... */

    render() {
        return <input
            { ... }
            defaultValue={this.props.CurrentPage}
            ref={this.inputRef}
        />
    }
}


问:
how to integrate my business with whatsup business api?
I am trying to integrate my business with whatsup business api.
Do I need to download, install business app and makes requests or I can use only business api?
If only business api is enough, how can i get the uri for which I can make requests.

I tried register my business, I didn't get any response for uri.
I am also unable to install business app.
I am getting the error:
docker-compose up -d
ERROR: Invalid interpolation format for "image" option in service "waweb": "docker.whatsapp.biz/web:v${WA_API_VERSION:?Run docker-compose with env var WA_API_VERSION (ex. WA_API_VERSION=2.21.4 docker-compose  )}"

答:
There are two major ways for a business to use WhatsApp right now. If you're a small to medium scale business and can handle the traffic through an app you can use WhatsApp for Business app from the appstore. If you feel like you have more traffic and need programmatic access, then WhatsApp Business API is your thing. In order to use WhatsApp Business API you don't need to install any app. It comes as a set of docker images that you spin in an orchestration of your choice (docker, AWS, Kubernetes, etc.)

The WhatsApp documentation lists the required steps to get start with API.

You need to create a WhatsApp account for you business on Facebook Business Manager.

You need to register your phone numbers and get the certificate from Business Manager.

There are 2 docker images that you need for your setup which are publicly available (webapp and coreapp)

When you run the docker-compose up, you also need to setup the WA_API_VERSION environment to the version of the webapp/coreapp that you want to run. The latest versions can be found here (https://developers.facebook.com/docs/whatsapp/changelog)


问:
BeautifulSoup webscraping find_all( ): finding exact match
I'm using Python and BeautifulSoup for web scraping.

Lets say I have the following html code to scrape:

```<code><body>
    <div class="product">Product 1</div>
    <div class="product">Product 2</div>
    <div class="product special">Product 3</div>
    <div class="product special">Product 4</div>
</body>
</code>```

Using BeautifulSoup, I want to find ONLY the products with the attribute class="product"
(only Product 1 and 2), not the 'special' products

If I do the following:

```<code>result = soup.find_all('div', {'class': 'product'})
</code>```

the result includes ALL the products (1,2,3, and 4).

What should I do to find products whose class EXACTLY matches 'product'??

The Code I ran:

```<code>from bs4 import BeautifulSoup
import re

text = """
<body>
    <div class="product">Product 1</div>
    <div class="product">Product 2</div>
    <div class="product special">Product 3</div>
    <div class="product special">Product 4</div>
</body>"""

soup = BeautifulSoup(text)
result = soup.findAll(attrs={'class': re.compile(r"^product$")})
print result
</code>```

Output:

```<code>[<div class="product">Product 1</div>, <div class="product">Product 2</div>, <div class="product special">Product 3</div>, <div class="product special">Product 4</div>]
</code>```

答:
```<code>soup.findAll(attrs={'class': re.compile(r"^product$")})
</code>```

This code matches anything that doesn't have the product at the end of its class.

Body:
I'm using Python and BeautifulSoup for web scraping.

Lets say I have the following html code to scrape:

Product 1

Product 2

Product 3

Product 4

Using BeautifulSoup, I want to find ONLY the products with the attribute class="product"
(only Product 1 and 2), not the 'special' products

If I do the following:

result = soup.find_all('div', {'class': 'product'})

the result includes ALL the products (1,2,3, and 4).

What should I do to find products whose class EXACTLY matches 'product'??

The Code I ran:

from bs4 import BeautifulSoup
import re

text = """

Product 1

Product 2

Product 3

Product 4

"""

soup = BeautifulSoup(text)
result = soup.findAll(attrs={'class': re.compile(r"^product$")})
print result

Output:

[
Product 1
,
Product 2
,
Product 3
,
Product 4
]

Body:
soup.findAll(attrs={'class': re.compile(r"^product$")})

This code matches anything that doesn't have the product at the end of its class.


问:
How to include layout inside layout?
How to include layout inside layout in Android?

I am creating common layout. I want to include that layout in another page.

答:
Use <include /> tag.

```<code>          <include
            android:id="@+id/some_id_if_needed"
            layout="@layout/some_layout"/>
</code>```

Also, read Creating Reusable UI Components and Merging Layouts articles.

Title: How to include layout inside layout?

Body:
Use <include /> tag.

          <include
            android:id="@+id/some_id_if_needed"
            layout="@layout/some_layout"/>

Also, read Creating Reusable UI Components and Merging Layouts articles.


问:
How to create threads in nodejs
Is there any way to create threads for running multiple methods at a time?

That way, if any method fails in between all the other threads should be killed.

答:
The nodejs 10.5.0 release has announced multithreading in Node.js. The feature is still experimental. There is a new worker_threads module available now.

You can start using worker threads if you run Node.js v10.5.0 or higher, but this is an experimental API. It is not available by default: you need to enable it by using  --experimental-worker when invoking Node.js.

Here is an example with ES6 and worker_threads enabled, tested on version 12.3.1

```<code>//package.json

  "scripts": {
  "start": "node  --experimental-modules --experimental- worker index.mjs"
  },
</code>```

Now, you need to import Worker from worker_threads.
Note: You need to declare you js files with '.mjs' extension for ES6 support.

```<code>//index.mjs
import { Worker } from 'worker_threads';

const spawnWorker = workerData => {
    return new Promise((resolve, reject) => {
        const worker = new Worker('./workerService.mjs', { workerData });
        worker.on('message', resolve);
        worker.on('error', reject);
        worker.on('exit', code => code !== 0 && reject(new Error(`Worker stopped with
        exit code ${code}`)));
    })
}

const spawnWorkers = () => {
    for (let t = 1; t <= 5; t++)
        spawnWorker('Hello').then(data => console.log(data));
}

spawnWorkers();
</code>```

Finally, we create a workerService.mjs

```<code>//workerService.mjs
import { workerData, parentPort, threadId } from 'worker_threads';

// You can do any cpu intensive tasks here, in a synchronous way
// without blocking the "main thread"
parentPort.postMessage(`${workerData} from worker ${threadId}`);
</code>```

Output:

npm run start

```<code>Hello from worker 4
Hello from worker 3
Hello from worker 1
Hello from worker 2
Hello from worker 5
</code>```

Title: How to create threads in nodejs

Body:
The nodejs 10.5.0 release has announced multithreading in Node.js. The feature is still experimental. There is a new worker_threads module available now.

You can start using worker threads if you run Node.js v10.5.0 or higher, but this is an experimental API. It is not available by default: you need to enable it by using  --experimental-worker when invoking Node.js.

Here is an example with ES6 and worker_threads enabled, tested on version 12.3.1

//package.json

  "scripts": {
  "start": "node  --experimental-modules --experimental- worker index.mjs"
  },

Now, you need to import Worker from worker_threads.
Note: You need to declare you js files with '.mjs' extension for ES6 support.

//index.mjs
import { Worker } from 'worker_threads';

const spawnWorker = workerData => {
    return new Promise((resolve, reject) => {
        const worker = new Worker('./workerService.mjs', { workerData });
        worker.on('message', resolve);
        worker.on('error', reject);
        worker.on('exit', code => code !== 0 && reject(new Error(`Worker stopped with
        exit code ${code}`)));
    })
}

const spawnWorkers = () => {
    for (let t = 1; t <= 5; t++)
        spawnWorker('Hello').then(data => console.log(data));
}

spawnWorkers();

Finally, we create a workerService.mjs

//workerService.mjs
import { workerData, parentPort, threadId } from 'worker_threads';

// You can do any cpu intensive tasks here, in a synchronous way
// without blocking the "main thread"
parentPort.postMessage(`${workerData} from worker ${threadId}`);

Output:

npm run start

Hello from worker 4
Hello from worker 3
Hello from worker 1
Hello from worker 2
Hello from worker 5


问:
How to fix 'tableview cellforrowat not called?'
I'm setting up a tableview with customtableview cell, but when i run the app, the data is not shown.

I already check all the connection, identifier, class name, etc

import UIKit

class ViewController: UITableViewController {
    @IBOutlet var testingTableView: UITableView!
    var data = ["Indomie","Kacang Tanah","Soya"]
    override func viewDidLoad() {
        super.viewDidLoad()

        testingTableView.register(UINib(nibName: "TableViewCell", bundle: nil), forCellReuseIdentifier: "customCell")
        // Do any additional setup after loading the view.
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = testingTableView.dequeueReusableCell(withIdentifier: "customCell", for: indexPath) as! customTableViewCell
        cell.customLabel.text = data[indexPath.row]
        return cell
    }

    override func numberOfSections(in tableView: UITableView) -> Int {
        return data.count
    }
}
```

This is my code for the table view, it's should call the cellforrowat but it's not

答:
I guess you need additional code as below-</p>

```<code>testingTableView.delegate = self
testingTableView.datasource = self

testingTableView.reloadData() // I think you missed it!
</code>```

Body:
I'm setting up a tableview with customtableview cell, but when i run the app, the data is not shown.

I already check all the connection, identifier, class name, etc

import UIKit

class ViewController: UITableViewController {
    @IBOutlet var testingTableView: UITableView!
    var data = ["Indomie","Kacang Tanah","Soya"]
    override func viewDidLoad() {
        super.viewDidLoad()

        testingTableView.register(UINib(nibName: "TableViewCell", bundle: nil), forCellReuseIdentifier: "customCell")
        // Do any additional setup after loading the view.
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = testingTableView.dequeueReusableCell(withIdentifier: "customCell", for: indexPath) as! customTableViewCell
        cell.customLabel.text = data[indexPath.row]
        return cell
    }

    override func numberOfSections(in tableView: UITableView) -> Int {
        return data.count
    }
}

This is my code for the table view, it's should call the cellforrowat but it's not

Body:
I guess you need additional code as below-

testingTableView.delegate = self
testingTableView.datasource = self

testingTableView.reloadData() // I think you missed it!


问:
iText certificate verification
I'm following the iText certificate verification example (it's the 3rd example found here: https://itextpdf.com/en/resources/examples/itext-7/digital-signatures-chapter-5).

I don't quite get the following piece of code (I'm using iTextsharp with C#, but code for java is similar):

```<code>PdfPKCS7 pkcs7 = base.VerifySignature(fields, name);
X509Certificate[] certs = pkcs7.SignCertificateChain;
DateTime cal = pkcs7.SignDate;
Object[] errors = CertificateVerification.VerifyCertificates(certs, certificates, null, cal);
</code>```

certificates is the list used to verify certs (certificates are trusted certificates). In the example, it's created from the next files:

```<code>public const String ADOBE = "../../../../resources/adobeRootCA.cer";
public const String CACERT = "../../../../resources/CACertSigningAuthority.crt";
public const String BRUNO = "../../../../resources/bruno.crt";
</code>```

I'm not sure where should I get those files from when trying to implement this myself.

I'm thinking of verifying the signatures certificates against trusted certificates in Windows store, but since I don't get why the example uses those files, I'm not sure if verifying against Windows store would be ok.

答:
Please refer to the first and the second chapters of Digital Signatures for PDF documents (the samples which you found on the website are from this publication; it could be easily found on the Web or requested on iText's website free of charge).

There you can found how to use java's keytool to create certificates.

For example, for bruno.crt the code is as follows:

```<code>keytool -export -alias demo -file bruno.crt -keystore ks -storepass password
</code>```

Title: iText certificate verification

Body:
I'm following the iText certificate verification example (it's the 3rd example found here: https://itextpdf.com/en/resources/examples/itext-7/digital-signatures-chapter-5).

I don't quite get the following piece of code (I'm using iTextsharp with C#, but code for java is similar):

PdfPKCS7 pkcs7 = base.VerifySignature(fields, name);
X509Certificate[] certs = pkcs7.SignCertificateChain;
DateTime cal = pkcs7.SignDate;
Object[] errors = CertificateVerification.VerifyCertificates(certs, certificates, null, cal);

certificates is the list used to verify certs (certificates are trusted certificates). In the example, it's created from the next files:

public const String ADOBE = "../../../../resources/adobeRootCA.cer";
public const String CACERT = "../../../../resources/CACertSigningAuthority.crt";
public const String BRUNO = "../../../../resources/bruno.crt";

I'm not sure where should I get those files from when trying to implement this myself.

I'm thinking of verifying the signatures certificates against trusted certificates in Windows store, but since I don't get why the example uses those files, I'm not sure if verifying against Windows store would be ok.

Body:
Please refer to the first and the second chapters of Digital Signatures for PDF documents (the samples which you found on the website are from this publication; it could be easily found on the Web or requested on iText's website free of charge).

There you can found how to use java's keytool to create certificates.

For example, for bruno.crt the code is as follows:

keytool -export -alias demo -file bruno.crt -keystore ks -storepass password


问:
How to do correct message passing between popup.js and background.js?
My extension should work like this:
Some data send from popup.js to background.js, in background.js I work with some web api services. And after that I send new data from background.js to popup.js for show in popup.html.

But if I after send from popup.js to background.js I close and open popup.html than data from background.js can't get popup.js because port doesn't exist.

I tried use localstorage. But my popup.html write on Vue and localsorage for Vue is not react and my data don't updates in popup.html if my popup.html was not closed/open.

How to do correct message passing?

答:
You are looking for VueX, which role is to store data for all the application.

https://vuex.vuejs.org/


问:
Segmentation fault when passing big integers as values in vector
Getting segmentation fault(Core Dumped) when big integers are passed. It works fine for smaller inputs.

Replaced int with long int and also tried to declare the variables globally, but still the same error. This function is used to perform a number of right circular rotations and return the value of the element at a given index. Here is the function:

```<code>    vector<long long int> circularArrayRotation(vector<long long int> a, long long int k, vector<long long int> queries) {
        vector <long long int> b;
        std::vector<long long int> result(queries.size());

        b=a;
        for(long long int j=0;j<k;j++)
        {
            for(long long int i=0;i<a.size();i++)
                a[i]=b[(a.size()+i-1)%a.size()];
            b=a;
        }

        for(long long int k=0;k<queries.size();k++)
            result[k]=a[queries[k]];
        for(long long int i=0;i<result.size();i++)
                cout<<result[i]<<endl;

        return result;

    }
</code>```

The remaining code can be found here link

答:
A vector is backed by an array of continuous memory, and your machine isn't able to allocate such a large array.

You could consider using a list instead, but would probably need to rewrite the code to use iterators if you care about performance.

Body:
Getting segmentation fault(Core Dumped) when big integers are passed. It works fine for smaller inputs.

Replaced int with long int and also tried to declare the variables globally, but still the same error. This function is used to perform a number of right circular rotations and return the value of the element at a given index. Here is the function:

    vector<long long int> circularArrayRotation(vector<long long int> a, long long int k, vector<long long int> queries) {
        vector <long long int> b;
        std::vector<long long int> result(queries.size());

        b=a;
        for(long long int j=0;j<k;j++)
        {
            for(long long int i=0;i<a.size();i++)
                a[i]=b[(a.size()+i-1)%a.size()];
            b=a;
        }

        for(long long int k=0;k<queries.size();k++)
            result[k]=a[queries[k]];
        for(long long int i=0;i<result.size();i++)
                cout<<result[i]<<endl;

        return result;

    }

The remaining code can be found here link


问:
Does sharing App Hash through OTP have any drawbacks in terms of app security
While implementing OTP for user verification in android app, i am using SMS Retriever API in order to bypass the SMS Read permission. In SMS Retriever API, we need a special format i.e <#> at the start of message & your App Hash at the end of message.

Is sharing app hash like this a safe way/ good practise or does it have any threats in terms of app security.

Is there anyway we can hide this <#> & App Hash when received at user end. Tried \u200b\u200b sending this instead of <#> but didn't work

答:
As per SMS Retriever API docs

When the user's device receives the SMS message, Google Play services uses the app hash to determine that the message is intended for your app, and makes the message text available to your app through the SMS Retriever API.

As it is clearly mentioned it is used by Google Play services so I dont think there should be any security concerns.


问:
Newly created git branches in Azure DevOps not showing up in Visual Studio 2017
I had cloned a git project hosted in Azure DevOps using Visual Studio 2017. Then a branch was created in the Azure Devops portal. Now I do not see newly created branch in Visual Studio. What do I need to do in Visual Studio 2017 to sync the newly crated branch to show up in VS 2017?</p>

答:
Make sure your local git repository is connected to Azure DevOps.

Click Sync --> Click Pull to get all changes from remote git repository.

Back to Home and click Branches, you will see local branches and remote branches at here. Double click your remote branch, then you can have the local branch and use it.


问:
What is an appropriate data type to store a timezone?
I'm thinking of simply using a string in the format "+hh:mm" (or "-hh:mm"). Is this both necessary and sufficient?

Note: I don't need to store the date or the time, just the timezone.

答:
In postgres, you can already cast any TIMESTAMP or TIMESTAMPTZ to or from a named timezone, so you don't need to look up values from a table. You can use this expression directly in a check constraint, so you don't need to create a function for this either:

```<code>CREATE TABLE locations (
    location_id SERIAL PRIMARY KEY,
    name TEXT,
    timezone TEXT NOT NULL CHECK (now() AT TIME ZONE timezone IS NOT NULL)
);
</code>```

If you try to insert a value that does not contain a valid timezone, you'll get an error that is actually rather user friendly:

```<code>INSERT INTO locations (name, timezone) VALUES ('foo', 'Adelaide/Australia');
ERROR:  time zone "Adelaide/Australia" not recognized
</code>```

Depending upon your requirements, you might need the error to be in the format that a normal constraint violation would provide you, however in many cases this will suffice.

If you are using a web framework that provides you with a list of timezones that you can have in a dropdown box, then this validation should be sufficient, and then your check constraint is just a backup.

Body:
In postgres, you can already cast any TIMESTAMP or TIMESTAMPTZ to or from a named timezone, so you don't need to look up values from a table. You can use this expression directly in a check constraint, so you don't need to create a function for this either:

CREATE TABLE locations (
    location_id SERIAL PRIMARY KEY,
    name TEXT,
    timezone TEXT NOT NULL CHECK (now() AT TIME ZONE timezone IS NOT NULL)
);

If you try to insert a value that does not contain a valid timezone, you'll get an error that is actually rather user friendly:

INSERT INTO locations (name, timezone) VALUES ('foo', 'Adelaide/Australia');
ERROR:  time zone "Adelaide/Australia" not recognized

Depending upon your requirements, you might need the error to be in the format that a normal constraint violation would provide you, however in many cases this will suffice.

If you are using a web framework that provides you with a list of timezones that you can have in a dropdown box, then this validation should be sufficient, and then your check constraint is just a backup.


问:
Upload image to two different folder locations using Laravel 5.8
This Code save image in only one folder. I want to upload the image at the same time in two different folders,
example
folder-one
and
folder-two

my controler

```<code>protected function validator(array $data)
{
    return Validator::make($data, [

       'photo_jpeg' => 'required|image|mimes:jpeg,png,jpg|max:2048',

    ]);
}
protected function create(array $data)
{
    $photo_jpeg= time() . '.' . $data['photo_jpeg']->getClientOriginalExtension();
            $data['photo_jpeg']->move(base_path() . 'public/folder-one', $photo_jpeg);

return user::create([

        'photo_jpeg' => $photo_jpeg,

       ]);

}
</code>```

答:
In controller:

```<code>public function store(Request $request){

        if($request->User_jpeg != ''){ //check file has selected

            $file = $request->User_jpeg;

            $path = base_path('public/folder-one/');

            $filename = time() . '_' . $file->getClientOriginalName();

            $file->move($path, $filename);

            \File::copy($path.$filename,base_path('public/folder-two/'.$filename));
        }

        user::create([
            'photo_jpeg' => $filename,
        ]);

    }
</code>```

In route file (web.php):

```<code>Route::post('save-image', 'YourController@store');
</code>```

Body:
This Code save image in only one folder. I want to upload the image at the same time in two different folders,
example
folder-one
and
folder-two

my controler

protected function validator(array $data)
{
    return Validator::make($data, [

       'photo_jpeg' => 'required|image|mimes:jpeg,png,jpg|max:2048',

    ]);
}
protected function create(array $data)
{
    $photo_jpeg= time() . '.' . $data['photo_jpeg']->getClientOriginalExtension();
            $data['photo_jpeg']->move(base_path() . 'public/folder-one', $photo_jpeg);

return user::create([

        'photo_jpeg' => $photo_jpeg,

       ]);

}

Body:
In controller:

public function store(Request $request){

        if($request->User_jpeg != ''){ //check file has selected

            $file = $request->User_jpeg;

            $path = base_path('public/folder-one/');

            $filename = time() . '_' . $file->getClientOriginalName();

            $file->move($path, $filename);

            \File::copy($path.$filename,base_path('public/folder-two/'.$filename));
        }

        user::create([
            'photo_jpeg' => $filename,
        ]);

    }

In route file (web.php):

Route::post('save-image', 'YourController@store');


问:
How to check if "unsorted version" of a list already exists in the set?
I want to generate a list of lists. Each sub-list will be generated by sampling from range(100). I need to make sure lists that are identical (i.e. have the exact same elements) but have different sorting do not exist in the main list (i.e. I do not want [1,2,3] and [2,1,3] in the main list at the same time). This is what I have written:

```<code>import random as rd
my_list = []
while len(my_list) < 50:
    p = rd.sample(range(100), 10)
    if p not in my_list: my_list.append(p)
</code>```

The issue is if p not in my_list does not do the job as it does not consider [1,2,3] and [2,1,3] identical. I thought of doing something like this:

```<code>my_list = []
while len(my_list) < 50:
    p = rd.sample(range(100), 10)
    for i in range(len(my_list)):
        if set(p) != set(my_list[i]): my_list.append(p)
</code>```

But it seems this gets stuck in the first loop and the program never ends. I was wondering if there is a simple way of doing this in Python?

答:
The other answers seem to have missed the non-quadratic solution of keeping a set of frozensets:

```<code>def unique_without_order_retaining_order(L):
    output = []
    seen = set()
    for item in L:
        f = frozenset(item)
        if f not in seen:
           seen.add(f)
           output.append(item)
    return output
</code>```

This can be adapted to be a generator.

Body:
I want to generate a list of lists. Each sub-list will be generated by sampling from range(100). I need to make sure lists that are identical (i.e. have the exact same elements) but have different sorting do not exist in the main list (i.e. I do not want [1,2,3] and [2,1,3] in the main list at the same time). This is what I have written:

import random as rd
my_list = []
while len(my_list) < 50:
    p = rd.sample(range(100), 10)
    if p not in my_list: my_list.append(p)

The issue is if p not in my_list does not do the job as it does not consider [1,2,3] and [2,1,3] identical. I thought of doing something like this:

my_list = []
while len(my_list) < 50:
    p = rd.sample(range(100), 10)
    for i in range(len(my_list)):
        if set(p) != set(my_list[i]): my_list.append(p)

But it seems this gets stuck in the first loop and the program never ends. I was wondering if there is a simple way of doing this in Python?

Body:
The other answers seem to have missed the non-quadratic solution of keeping a set of frozensets:

def unique_without_order_retaining_order(L):
    output = []
    seen = set()
    for item in L:
        f = frozenset(item)
        if f not in seen:
           seen.add(f)
           output.append(item)
    return output

This can be adapted to be a generator.


问:
Jquery ajax data
I am using the qTip plugin to post a imdb URL to an IMDB grabber script and display movie info on that url.

Everything works until I have more than one qtip on the page.

What i need to do Is only post the data of the image that is being hovered. This is the code should make a bit more sense then me.

Script -

```<code>var link = $("#link").val();
var imdbLink =  { "link" : link };  // note change to data...

$('.moviebox').each(function() {
    $(this).qtip({
       style: { name: 'light' },
       content: {
         method: 'GET',
         data: imdbLink,   // you could make this { "link" : link }
         url: '/bin/imdb/imdb.example.php',
         text: '<img class="throbber" src="/images/loading.gif" alt="Loading..." />'
       },
       position: {
             corner: {
               target: 'bottomright',
              tooltip: 'bottomleft'
            }
          }
    });
    });
</code>```

html--

```<code>  <div class="moviebox rounded"><a href="#">
  <img src="http://1.bp.blogspot.com/_mySxtRcQIag/S6deHcoChaI/AAAAAAAAObc/Z1Xg3aB_wkU/s200/rising_sun.jpg" />
  <form method="get" action="">
    <input type="text" name="link" id="link" style="display:none" value="http://us.imdb.com/Title?0107969"/>
 </form>
  </a></div>

  <div class="moviebox rounded"><a href="#"><img src="http://2.bp.blogspot.com/_mySxtRcQIag/S6dUoGd4_TI/AAAAAAAAObM/4Mbohcy0Owo/s200/grumpy_old_men.jpg" />
   <form method="get" action="">
    <input type="text" name="link" id="link" style="display:none" value="http://us.imdb.com/Title?0107050"/>
 </form>
 </a>
</code>```

You will see that both inputs have the same ID which is causing an issue. how would I get around this keeping the IDs the same????

答:
```<code>$('.moviebox').each(function() {
   var imdbLink =  { "link" : $(this).find("input.link").val() };
   $(this).qtip({
      // qTip code
   });
});
</code>```

ContentLicense: CC BY-SA 2.5

Title: Jquery ajax data

Body:
I am using the qTip plugin to post a imdb URL to an IMDB grabber script and display movie info on that url.

Everything works until I have more than one qtip on the page.

What i need to do Is only post the data of the image that is being hovered. This is the code should make a bit more sense then me.

Script -

var link = $("#link").val();
var imdbLink =  { "link" : link };  // note change to data...

$('.moviebox').each(function() {
    $(this).qtip({
       style: { name: 'light' },
       content: {
         method: 'GET',
         data: imdbLink,   // you could make this { "link" : link }
         url: '/bin/imdb/imdb.example.php',
         text: ''
       },
       position: {
             corner: {
               target: 'bottomright',
              tooltip: 'bottomleft'
            }
          }
    });
    });

html--

  <form method="get" action="">
    <input type="text" name="link" id="link" style="display:none" value="http://us.imdb.com/Title?0107969"/>
 </form>

   <form method="get" action="">
    <input type="text" name="link" id="link" style="display:none" value="http://us.imdb.com/Title?0107050"/>
 </form>

You will see that both inputs have the same ID which is causing an issue. how would I get around this keeping the IDs the same????


问:
How to send mail from a custom UITableViewCell using MFMailComposerViewController
I want to send mail while clicking a button in a custom UITableViewCell using MFMailComposeViewController.

Appreciate if answer is in Objective-C.

答:
Make sure you are testing it in Real device not in simulator and you have a mail ID configured in your device </p>

```<code>#import <MessageUI/MessageUI.h>
#import <MessageUI/MFMailComposeViewController.h>

@interface ViewController ()<MFMailComposeViewControllerDelegate>

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (IBAction)sendmail:(id)sender {

    if ([MFMailComposeViewController canSendMail])
    {
            MFMailComposeViewController *mailer = [[MFMailComposeViewController alloc] init];
            mailer.mailComposeDelegate = self;
            [mailer setSubject:@"Subject"];
            NSArray *toRecipients = [NSArray arrayWithObjects:@"Recipients", nil];
            [mailer setToRecipients:toRecipients];
            NSString *emailBody = @"Body";
            [mailer setMessageBody:emailBody isHTML:NO];
            [self presentViewController:mailer animated:YES completion:nil];
    }
}

- (void) mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
{

    // Close the Mail Interface
    [self dismissViewControllerAnimated:NO completion:NULL];
}
</code>```

Body:
Make sure you are testing it in Real device not in simulator and you have a mail ID configured in your device

#import <MessageUI/MessageUI.h>
#import <MessageUI/MFMailComposeViewController.h>

@interface ViewController ()<MFMailComposeViewControllerDelegate>

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (IBAction)sendmail:(id)sender {

    if ([MFMailComposeViewController canSendMail])
    {
            MFMailComposeViewController *mailer = [[MFMailComposeViewController alloc] init];
            mailer.mailComposeDelegate = self;
            [mailer setSubject:@"Subject"];
            NSArray *toRecipients = [NSArray arrayWithObjects:@"Recipients", nil];
            [mailer setToRecipients:toRecipients];
            NSString *emailBody = @"Body";
            [mailer setMessageBody:emailBody isHTML:NO];
            [self presentViewController:mailer animated:YES completion:nil];
    }
}

- (void) mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
{

    // Close the Mail Interface
    [self dismissViewControllerAnimated:NO completion:NULL];
}