问:
Flexbox grid 1col 1row 3boxes
How can I make this grid without creating 2 columns?

答:
Flex makes life super easy..

```<code>.container {
display:flex;
}

.left {
    flex:2;
    background-color: #c1c1c1;
}
.container_right {display: flex;
                    flex: 1;
                    flex-direction:column}
.right {
    flex:1;
background-color: #456456;
}
</code>```

and the html..

```<code><div class="container">
    <div class="left">aaaaaaaaaaaa</div>

    <div class="container_right">
        <div class="right">bbbbbbbbbbbb</div>
        <div class="right">cccccccccccc</div>
    </div>

</div>
</code>```

You just have to think of everything as a container.. everything inside that container can be flexed..

With  Flex you need to avoid defining anything with px if possible. stick with units of

%

vw/vh r
rem/em

Title: Flexbox grid 1col 1row 3boxes

Body:
Flex makes life super easy..

.container {
display:flex;
}

.left {
    flex:2;
    background-color: #c1c1c1;
}
.container_right {display: flex;
                    flex: 1;
                    flex-direction:column}
.right {
    flex:1;
background-color: #456456;
}

and the html..

<div class="container">
    <div class="left">aaaaaaaaaaaa</div>

    <div class="container_right">
        <div class="right">bbbbbbbbbbbb</div>
        <div class="right">cccccccccccc</div>
    </div>

</div>

You just have to think of everything as a container.. everything inside that container can be flexed..

With  Flex you need to avoid defining anything with px if possible. stick with units of

%

vw/vh r
rem/em


来源: stackexchange

问:
jQuery(...).autocomplete is not a function at fire jquery-1.10.2.js
So I am working on an MVC 5 Application which got written in 2014 and was using older versions of JQuery and as such some functions have been deprecated and as a result, through the use of Google Chrome's Developer Tools via F12 hot key, I keep getting these console errors. I have imported JQuery library before JQuery UI according to these two SO posts:

Uncaught TypeError: $(...).autocomplete is not a function and TypeError: $(...).autocomplete is not a function as shown below but this attempt still does not remedy the problem.

_Layout.cshtml:

```<code><script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
<script src="//cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>

<script type="text/javascript" src="@Url.Content("~/Content/Template/js/custom/general.js")"></script>

<script type="text/javascript" src="@Url.Content("~/Content/Template/js/plugins/jquery.jgrowl.js")"></script>
<script type="text/javascript" src="@Url.Content("~/Content/Template/js/plugins/jquery.alerts.js")"></script>
<script type="text/javascript" src="@Url.Content("~/Content/Template/js/custom/elements.js")"></script>
<script type="text/javascript" src="@Url.Content("~/Content/Template/js/plugins/colorpicker.js")"></script>

<script src="http://code.jquery.com/jquery-1.9.0.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.js"></script>
</code>```

General.js

```<code>jQuery(document).ready(function()
{
    //search box of header
    jQuery('#keyword').bind('focusin focusout', function(e)
    {
        var t = jQuery(this);
        if(e.type == 'focusin' && t.val() == 'Search here')
        {
            t.val('');
        }
        else if(e.type == 'focusout' && t.val() == '')
        {
            t.val('Search here');
        }
    });

    jQuery( "#keyword" ).autocomplete({
        source: availableTags
    });
}
</code>```

And the above produces an:

Uncaught TypeError: jQuery(...).autocomplete is not a function

```<code>at HTMLDocument.<anonymous> (general.js:373)
at fire (jquery-1.10.2.js:3048)
at Object.fireWith [as resolveWith] (jquery-1.10.2.js:3160)
at Function.ready (jquery-1.10.2.js:433)
at HTMLDocument.completed (jquery-1.10.2.js:104)
</code>```

My search box is not even showing and I am suspecting its a result of these errors I keep getting.

答:
A couple of things to correct:

1)  and then . Don't include jQuery twice. Include the more recent version, and include it once, before all the other scripts. In other words, delete the reference to 1.9.0. Then see if you still have a problem. Including it twice can cause weird conflicts.

2) .bind was superseded by .on in jQuery 1.7, and deprecated in 3.0. Use .on for forward compatibility and better functionality.

ContentLicense: CC BY-SA 3.0

Body:
So I am working on an MVC 5 Application which got written in 2014 and was using older versions of JQuery and as such some functions have been deprecated and as a result, through the use of Google Chrome's Developer Tools via F12 hot key, I keep getting these console errors. I have imported JQuery library before JQuery UI according to these two SO posts:

Uncaught TypeError: $(...).autocomplete is not a function and TypeError: $(...).autocomplete is not a function as shown below but this attempt still does not remedy the problem.

_Layout.cshtml:

General.js

jQuery(document).ready(function()
{
    //search box of header
    jQuery('#keyword').bind('focusin focusout', function(e)
    {
        var t = jQuery(this);
        if(e.type == 'focusin' && t.val() == 'Search here')
        {
            t.val('');
        }
        else if(e.type == 'focusout' && t.val() == '')
        {
            t.val('Search here');
        }
    });

    jQuery( "#keyword" ).autocomplete({
        source: availableTags
    });
}

And the above produces an:

Uncaught TypeError: jQuery(...).autocomplete is not a function

at HTMLDocument.<anonymous> (general.js:373)
at fire (jquery-1.10.2.js:3048)
at Object.fireWith [as resolveWith] (jquery-1.10.2.js:3160)
at Function.ready (jquery-1.10.2.js:433)
at HTMLDocument.completed (jquery-1.10.2.js:104)

My search box is not even showing and I am suspecting its a result of these errors I keep getting.

Body:
A couple of things to correct:

1) <script src="//code.jquery.com/jquery-1.10.2.js"></script> and then <script src="http://code.jquery.com/jquery-1.9.0.js"></script>. Don't include jQuery twice. Include the more recent version, and include it once, before all the other scripts. In other words, delete the reference to 1.9.0. Then see if you still have a problem. Including it twice can cause weird conflicts.

2) .bind was superseded by .on in jQuery 1.7, and deprecated in 3.0. Use .on for forward compatibility and better functionality.


问:
Query regarding initialization of a vector in c++
I was trying the vector implementation in C++ stl and couldn't figure out what exactly does this mean:

vector< int > vec[N]

If we simply write int a[10],it's an array of 10 elements. Doesn't the same logic apply to vectors as well?
Isn't it a vector of arrays containing N elements each.Also,when I tried the .size() function on vec it gave an error" error: request for member ‘size’ in ‘vec’, which is of non-class type ‘std::vector [3]'"(Considering N=3)

Please correct me if I misunderstood the concept.

Thanks

答:
Vector is a template class, with array as underlying data structure. Although you don't need to assign size to a vector because it increases its size dynamically, but you may want to reserve space to it while declaring. You can do it by "std::vector< int> vec(size)".
Your syntax actually seems an array of vector of int type, and not a vector of arrays.</p>


问:
How to show Spark application's percentage of completion on AWS EMR (and Boto3)?
I am running a Spark step on AWS EMR, this step is added to EMR through Boto3, I will like to return to the user a percentage of completion of the task, is there anyway to do this?

I was thinking to calculate this percentage with the number of completed stages of Spark, I know this won't be too precise, as the stage 4 may take double time than stage 5 but I am fine with that.

Is it possible to access this information with boto3?

I checked the method list_steps (here are the docs) but in the response I am getting only if its running without other information.

答:
DISCLAIMER: I know nothing about AWS EMR and Boto3

I will like to return to the user a percentage of completion of the task, is there anyway to do this?

Any way? Perhaps. Just register a SparkListener and intercept events as they come. That's how web UI works under the covers (which is the definitive source of truth for Spark applications).

Use spark.extraListeners property to register a SparkListener and do whatever you want with the events.

Quoting the official documentation's Application Properties:

spark.extraListeners A comma-separated list of classes that implement SparkListener; when initializing SparkContext, instances of these classes will be created and registered with Spark's listener bus. If a class has a single-argument constructor that accepts a SparkConf, that constructor will be called; otherwise, a zero-argument constructor will be called.

You could also consider REST API interface:

In addition to viewing the metrics in the UI, they are also available as JSON. This gives developers an easy way to create new visualizations and monitoring tools for Spark. The JSON is available for both running applications, and in the history server. The endpoints are mounted at /api/v1. Eg., for the history server, they would typically be accessible at http://:18080/api/v1, and for a running application, at http://localhost:4040/api/v1.


问:
Python - Best way to append a sequence of numbers to a text file?
Let's say that I have textfile of a series of numbers that looks like this:

```<code>18,18,19,19,16,20,19,20,18,20,21
</code>```

That's only a preview of hundreds of numbers separated by commas. I want to be able to manipulate the data in python in a [list]. So I have a variable src that I want to append the integer values to from the text file.

Like so:

```<code>text_file = open("sequence.txt","r")
src = []

for entry in text_file.read():
    if(entry != ','):
        src.append(int(entry))
</code>```

Obviously this get's rid of the ',' between each entry in my textfile however values like 20 in the textfile will be appended to the list as two separate entries [2,0].

What's the best way to append these values ?
Thanks !

答:
If the text file only contains one single line you can do it much simpler

```<code>src = list(map(int, open("sequence.txt","r").read().split(",")))
</code>```

Of course it would be better to also close the file after reading, so

```<code>with open("sequence.txt","r") as f:
    src = list(map(int, f.read().split(",")))
</code>```

Body:
Let's say that I have textfile of a series of numbers that looks like this:

18,18,19,19,16,20,19,20,18,20,21

That's only a preview of hundreds of numbers separated by commas. I want to be able to manipulate the data in python in a [list]. So I have a variable src that I want to append the integer values to from the text file.

Like so:

text_file = open("sequence.txt","r")
src = []

for entry in text_file.read():
    if(entry != ','):
        src.append(int(entry))

Obviously this get's rid of the ',' between each entry in my textfile however values like 20 in the textfile will be appended to the list as two separate entries [2,0].

What's the best way to append these values ?
Thanks !

Body:
If the text file only contains one single line you can do it much simpler

src = list(map(int, open("sequence.txt","r").read().split(",")))

Of course it would be better to also close the file after reading, so

with open("sequence.txt","r") as f:
    src = list(map(int, f.read().split(",")))


问:
Will conditionals that are always false be removed by compiler in C#
Say I have the following code snippet in c#

```<code>static const bool DO_PERFORMANCE_CODE = false;

if (DO_PERFORMANCE_CODE)
{
   // performance monitoring code goes here
}
</code>```

Will that code get removed by the compiler? This is the functionality I'd like. Basically I want to mimic the conditional compilation stuff in C#, but I want more configurations other than Release and Debug. If there is a better way of doing this, I'd be open to hearing it.

答:
Defining your own symbols is probably cleaner, but I was curious as to what the compiler would do, so I did some experimenting (using VS 2008 in release mode).

With this:

```<code>class Program
{
    static void Main(string[] args)
    {
        bool foo = false;

        if (foo)
        {
            Console.WriteLine("Hello, world?");
        }
    }
}
</code>```

The compiler still generates the code for the if statement:

```<code>.method private hidebysig static void  Main(string[] args) cil managed
{
  .entrypoint
  // Code size       16 (0x10)
  .maxstack  1
  .locals init ([0] bool foo)
  IL_0000:  ldc.i4.0
  IL_0001:  stloc.0
  IL_0002:  ldloc.0
  IL_0003:  brfalse.s  IL_000f
  IL_0005:  ldstr      "Hello, world\?"
  IL_000a:  call       void [mscorlib]System.Console::WriteLine(string)
  IL_000f:  ret
} // end of method Program::Main
</code>```

If instead you do:

```<code>class Program
{
    static void Main(string[] args)
    {
        bool foo = false;

        if (false)
        {
            Console.WriteLine("Hello, world?");
        }
    }
}
</code>```

It doesn't generate code for the if statement:

```<code>.method private hidebysig static void  Main(string[] args) cil managed
{
  .entrypoint
  // Code size       1 (0x1)
  .maxstack  8
  IL_0000:  ret
} // end of method Program::Main
</code>```

It also seems to skip the variable that is assigned a value that is never used.

I checked with ildasm.exe, the disassembler that comes with visual studio.

OwnerDisplayName: WindyCityEagle

ContentLicense: CC BY-SA 2.5

Body:
Say I have the following code snippet in c#

static const bool DO_PERFORMANCE_CODE = false;

if (DO_PERFORMANCE_CODE)
{
   // performance monitoring code goes here
}

Will that code get removed by the compiler? This is the functionality I'd like. Basically I want to mimic the conditional compilation stuff in C#, but I want more configurations other than Release and Debug. If there is a better way of doing this, I'd be open to hearing it.

LastEditorDisplayName: Dana

Body:
Defining your own symbols is probably cleaner, but I was curious as to what the compiler would do, so I did some experimenting (using VS 2008 in release mode).

With this:

class Program
{
    static void Main(string[] args)
    {
        bool foo = false;

        if (foo)
        {
            Console.WriteLine("Hello, world?");
        }
    }
}

The compiler still generates the code for the if statement:

.method private hidebysig static void  Main(string[] args) cil managed
{
  .entrypoint
  // Code size       16 (0x10)
  .maxstack  1
  .locals init ([0] bool foo)
  IL_0000:  ldc.i4.0
  IL_0001:  stloc.0
  IL_0002:  ldloc.0
  IL_0003:  brfalse.s  IL_000f
  IL_0005:  ldstr      "Hello, world\?"
  IL_000a:  call       void [mscorlib]System.Console::WriteLine(string)
  IL_000f:  ret
} // end of method Program::Main

If instead you do:

class Program
{
    static void Main(string[] args)
    {
        bool foo = false;

        if (false)
        {
            Console.WriteLine("Hello, world?");
        }
    }
}

It doesn't generate code for the if statement:

.method private hidebysig static void  Main(string[] args) cil managed
{
  .entrypoint
  // Code size       1 (0x1)
  .maxstack  8
  IL_0000:  ret
} // end of method Program::Main

It also seems to skip the variable that is assigned a value that is never used.

I checked with ildasm.exe, the disassembler that comes with visual studio.

OwnerDisplayName: Dana


问:
What is the meaning of "$" in MySQL?
Example:

```<code>SELECT * FROM table1 WHERE $.``.age > 20
</code>```

I have tried the following

Valid queries:

```<code>select * from table1 where $.``.age > 20
</code>```

```<code>select * from table1 where ``.age > 20
</code>```

```<code>select * from table1 where `table1.age` > 20
</code>```

```<code>select * from table1 where $$.``.age > 20`
</code>```

Invalid queries

```<code>       select * from table1 where $.\`table1\`.age > 20
</code>```

答:
$ is valid in unquoted identifiers but doesn't have any special meaning as far as I know. You could replicate your question with any other text:

```<code>mysql> select *
    -> from information_schema.engines
    -> where typewhateverhere.``.transactions='YES';
+--------+---------+------------------------------------------------------------+--------------+------+------------+
| ENGINE | SUPPORT | COMMENT                                                    | TRANSACTIONS | XA   | SAVEPOINTS |
+--------+---------+------------------------------------------------------------+--------------+------+------------+
| InnoDB | DEFAULT | Supports transactions, row-level locking, and foreign keys | YES          | YES  | YES        |
+--------+---------+------------------------------------------------------------+--------------+------+------------+
1 row in set (0.00 sec)
</code>```

I don't have the faintest idea of what does syntax mean for MySQL, though, it doesn't seem documented among Identifier Qualifiers.

Title: What is the meaning of "$" in MySQL?

Body:
Example:

SELECT * FROM table1 WHERE $.``.age > 20

I have tried the following

Valid queries:

select * from table1 where $.``.age > 20

select * from table1 where ``.age > 20

select * from table1 where `table1.age` > 20

select * from table1 where $$.``.age > 20`

Invalid queries

       select * from table1 where $.\`table1\`.age > 20

Body:
$ is valid in unquoted identifiers but doesn't have any special meaning as far as I know. You could replicate your question with any other text:

mysql> select *
    -> from information_schema.engines
    -> where typewhateverhere.``.transactions='YES';
+--------+---------+------------------------------------------------------------+--------------+------+------------+
| ENGINE | SUPPORT | COMMENT                                                    | TRANSACTIONS | XA   | SAVEPOINTS |
+--------+---------+------------------------------------------------------------+--------------+------+------------+
| InnoDB | DEFAULT | Supports transactions, row-level locking, and foreign keys | YES          | YES  | YES        |
+--------+---------+------------------------------------------------------------+--------------+------+------------+
1 row in set (0.00 sec)

I don't have the faintest idea of what does syntax mean for MySQL, though, it doesn't seem documented among Identifier Qualifiers.


问:
Query Fine Tuning
I am fairly new to sql and would like to ask for your assistance regarding this query. Is there another way to rewrite this?

```<code> Select *
 From emp
 Where emp_no IN (
     Select emp_no
     From dept_emp
     Where dept_no = 'd002'
     );
</code>```

Any assistance is greatly appreciated.

Thanks.

答:
You can use join like this:

select * from emp e, dept_emp d where e.emp_no = d.emp_no and d.dept_no = 'd002'

Title: Query Fine Tuning

Body:
I am fairly new to sql and would like to ask for your assistance regarding this query. Is there another way to rewrite this?

 Select *
 From emp
 Where emp_no IN (
     Select emp_no
     From dept_emp
     Where dept_no = 'd002'
     );

Any assistance is greatly appreciated.

Thanks.


问:
Is there a way to start formflow dialog on ConversationUpdate event?
The end goal is this:

Ms botduilder sdk, chatbot for Slack.

When the user is added to group chat with bot (ActivityTypes.ConversationUpdate and activity.MembersAdded.Count != 0), I would like to immediately start from collecting data from him using formflow dialog via private messages. But i can't find a way to do that from this point, seems like you need to have some message from user already.

Is that correct and the only workaround is to ask user for some text typed first(or button "lets start")?

I've also tried this solution with resolving dialog stack from proactive examples:

```<code>else if (activity.Type == ActivityTypes.ConversationUpdate)
{
    if (activity.MembersAdded.Count != 0)
    {
        using (var scope = DialogModule.BeginLifetimeScope(Conversation.Container, activity))
        {
            var botData = scope.Resolve<IBotData>();
            await botData.LoadAsync(CancellationToken.None);

            //This is our dialog stack
            var stack = scope.Resolve<IDialogStack>();

            //interrupt the stack. This means that we're stopping whatever conversation that is currently happening with the user
            //Then adding this stack to run and once it's finished, we will be back to the original conversation

            var questions = new WelcomePoll();
            var myform = new FormDialog<WelcomePoll>(questions, WelcomePoll.BuildForm, FormOptions.PromptInStart, null);

            stack.Call(myform, Resume); //GOT "STACK IS EMPTY" EXCEPTION

                        return new HttpResponseMessage(System.Net.HttpStatusCode.Accepted);
        }
    }
}
</code>```

But got System.InvalidOperationException: 'Stack is empty' on stack.Call line. Maybe i need to create stack first but i couldn't find correct method.
Thank you.

答:
Disclaimer: my answer a bit more generic than your question. See the launch of a Dialog from ConversationUpdate at the end of the answer

Sending "real" proactive messages is possible in Microsoft Bot Framework but not in every channel.

Important point: when I say "real proactive messages", it is to make a distinction from what Microsoft is calling proactive message in the documentation (which is sending messages from the bot but to someone it already talks to in the past): here I am talking about sending a message to a customer that never talks to the bot before.

Sending proactive messages

The main pain for sending proactive messages is knowing the ID of the 2 ChannelAccount (= users, that is to say your bot and your end-user) that you will set in the Conversation object.

Those ChannelAccount objects got an ID that depend on the channel you are currently using. For example from what I previously analysed during my work on Bot Framework:

For Skype the bot ID is a concatenation of "28:" and its Microsoft AppId, but you need to know the User ID and a conversation between them MUST HAVE EXISTED => you can't really do a proactive message

For Facebook messager, the bot ID is the FB Page ID, but the user ID is a specific messenger ID that you cannot request easily => complicated, must well know Facebook APIs

For Slack, the bot ID is a concatenation of its Slack's Bot_id, a ':' and Slack's Team_id. The user ID is a concatenation of its Slack's id, a ':' and Slack's Team_id  => interesting

For Twilio SMS, bot ID and user ID are their phone numbers => easy

For email channel it is their emails

...

If you want to know how to start a Conversation once you got those IDs, jump to the section at the end.

Slack IDs focus

The advantage of Slack is the possibility to get all the necessary parameters to start a conversation by only knowing a few information and requesting their API. For example you can start a conversation by knowing only:

Bot Slack's username

User email address or  Slack's username

Then you can use Slack's API to get what the bot really needs.

How to get Slack data?

1 method to call the service, 1 using it to get the right data:

```<code>public class SlackService
{
    internal static async Task<SlackMembersRootObject> GetSlackUsersList(string slackApiToken, CancellationToken ct)
    {
        using (var client = new HttpClient())
        {
            using (var response = await client.GetAsync($"https://slack.com/api/users.list?token=" + $"{slackApiToken}", ct).ConfigureAwait(false))
            {
                var jsonString = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
                var rootObject = Newtonsoft.Json.JsonConvert.DeserializeObject<SlackMembersRootObject>(jsonString);
                return rootObject;
            }
        }
    }
}

public static async Task StartSlackDirectMessage(string msAppId, string msAppPassword, string slackApiToken, string message, string botSlackUsername, string botName, string destEmailAddress, string destName, string lang, CancellationToken ct)
{
    // Getting Slack user (and bot) list
    var slackUsersList = await SlackService.GetSlackUsersList(slackApiToken, CancellationToken.None);

    // Get Bot SlackId by searching its "username", you can also search by other criteria
    var slackBotUser = slackUsersList.Members.FirstOrDefault(x => x.Name == botSlackUsername);
    if (slackBotUser == null)
    {
        throw new Exception($"Slack API : no bot found for name '{botSlackUsername}'");
    }

    // Get User SlackId by email address
    var slackTargetedUser = slackUsersList.Members.FirstOrDefault(x => x.Profile.Email == destEmailAddress);
    if (slackTargetedUser != null)
    {
        // if found, starting the conversation by passing the right IDs
        await StartDirectMessage(msAppId, msAppPassword, "https://slack.botframework.com/", "slack", $"{slackBotUser.Profile.Bot_id}:{slackBotUser.Team_id}", botName, $"{slackTargetedUser.Id}:{slackTargetedUser.Team_id}", destName, message, lang, ct);
    }
    else
    {
        throw new Exception($"Slack API : no user found for email '{destEmailAddress}'");
    }
}
</code>```

How to start a conversation?
Once you know the relevant information about your bot and user (which depend on the channel, once again), you can start your conversation.

Create conversation

Create message

Send message to conversation

Sample method:

```<code>private static async Task StartDirectMessage(string msAppId, string msAppPassword, string connectorClientUrl, string channelId, string fromId, string fromName, string recipientId, string recipientName, string message, string locale, CancellationToken token)
{
    // Init connector
    MicrosoftAppCredentials.TrustServiceUrl(connectorClientUrl, DateTime.Now.AddDays(7));
    var account = new MicrosoftAppCredentials(msAppId, msAppPassword);
    var connector = new ConnectorClient(new Uri(connectorClientUrl), account);

    // Init conversation members
    ChannelAccount channelFrom = new ChannelAccount(fromId, fromName);
    ChannelAccount channelTo = new ChannelAccount(recipientId, recipientName);

    // Create Conversation
    var conversation = await connector.Conversations.CreateDirectConversationAsync(channelFrom, channelTo);

    // Create message Activity and send it to Conversation
    IMessageActivity newMessage = Activity.CreateMessageActivity();
    newMessage.Type = ActivityTypes.Message;
    newMessage.From = channelFrom;
    newMessage.Recipient = channelTo;

    newMessage.Locale = (locale ?? "en-US");
    newMessage.ChannelId = channelId;
    newMessage.Conversation = new ConversationAccount(id: conversation.Id);
    newMessage.Text = message;
    await connector.Conversations.SendToConversationAsync((Activity)newMessage);
}
</code>```

So back to your context:

You got a ConversationUpdate on a group conversation (ActivityTypes.ConversationUpdate and activity.MembersAdded.Count != 0): in this ConversationUpdate, you can get the userId and your botId. Then you start a new Conversation (using code above), then create a fake message that you don't send and get the IDialogTask from it: you will be able to launch your Dialog

Example:

```<code>if (activity.MembersAdded.Count != 0)
{
    // We have to create a new conversation between Bot and AddedUser

    #region Conversation creation
    // Connector init
    MicrosoftAppCredentials.TrustServiceUrl(activity.ServiceUrl, DateTime.Now.AddDays(7));
    var account = new MicrosoftAppCredentials("yourMsAppId", "yourMsAppPassword");
    var connector = new ConnectorClient(new Uri(activity.ServiceUrl), account);

    // From the conversationUpdate message, Recipient = bot and From = User
    ChannelAccount botChannelAccount = new ChannelAccount(activity.Recipient.Id, activity.Recipient.Name);
    ChannelAccount userChannelAccount = new ChannelAccount(activity.From.Id, activity.From.Name);

    // Create Conversation
    var conversation = await connector.Conversations.CreateDirectConversationAsync(botChannelAccount, userChannelAccount);
    #endregion

    // Then we prepare a fake message from bot to user, mandatory to get the working IDialogTask. This message MUST be from User to Bot, if you want the following Dialog to be from Bot to User
    IMessageActivity fakeMessage = Activity.CreateMessageActivity();
    fakeMessage.From = userChannelAccount;
    fakeMessage.Recipient = botChannelAccount;
    fakeMessage.ChannelId = activity.ChannelId;
    fakeMessage.Conversation = new ConversationAccount(id: conversation.Id);

    fakeMessage.ServiceUrl = activity.ServiceUrl;
    fakeMessage.Id = Guid.NewGuid().ToString();

    // Then use this fake message to launch the new dialog
    using (var scope = DialogModule.BeginLifetimeScope(Conversation.Container, fakeMessage))
    {
        var botData = scope.Resolve<IBotData>();
        await botData.LoadAsync(CancellationToken.None);

        //This is our dialog stack
        var task = scope.Resolve<IDialogTask>();

        //interrupt the stack. This means that we're stopping whatever conversation that is currently happening with the user
        //Then adding this stack to run and once it's finished, we will be back to the original conversation
        var dialog = new DemoDialog();
        task.Call(dialog.Void<object, IMessageActivity>(), null);

        await task.PollAsync(CancellationToken.None);

        //flush dialog stack
        await botData.FlushAsync(CancellationToken.None);

    }
}
</code>```

Body:
The end goal is this:

Ms botduilder sdk, chatbot for Slack.

When the user is added to group chat with bot (ActivityTypes.ConversationUpdate and activity.MembersAdded.Count != 0), I would like to immediately start from collecting data from him using formflow dialog via private messages. But i can't find a way to do that from this point, seems like you need to have some message from user already.

Is that correct and the only workaround is to ask user for some text typed first(or button "lets start")?

I've also tried this solution with resolving dialog stack from proactive examples:

else if (activity.Type == ActivityTypes.ConversationUpdate)
{
    if (activity.MembersAdded.Count != 0)
    {
        using (var scope = DialogModule.BeginLifetimeScope(Conversation.Container, activity))
        {
            var botData = scope.Resolve<IBotData>();
            await botData.LoadAsync(CancellationToken.None);

            //This is our dialog stack
            var stack = scope.Resolve<IDialogStack>();

            //interrupt the stack. This means that we're stopping whatever conversation that is currently happening with the user
            //Then adding this stack to run and once it's finished, we will be back to the original conversation

            var questions = new WelcomePoll();
            var myform = new FormDialog<WelcomePoll>(questions, WelcomePoll.BuildForm, FormOptions.PromptInStart, null);

            stack.Call(myform, Resume); //GOT "STACK IS EMPTY" EXCEPTION

                        return new HttpResponseMessage(System.Net.HttpStatusCode.Accepted);
        }
    }
}

But got System.InvalidOperationException: 'Stack is empty' on stack.Call line. Maybe i need to create stack first but i couldn't find correct method.
Thank you.

Body:
Disclaimer: my answer a bit more generic than your question. See the launch of a Dialog from ConversationUpdate at the end of the answer

Sending "real" proactive messages is possible in Microsoft Bot Framework but not in every channel.

Important point: when I say "real proactive messages", it is to make a distinction from what Microsoft is calling proactive message in the documentation (which is sending messages from the bot but to someone it already talks to in the past): here I am talking about sending a message to a customer that never talks to the bot before.

Sending proactive messages

The main pain for sending proactive messages is knowing the ID of the 2 ChannelAccount (= users, that is to say your bot and your end-user) that you will set in the Conversation object.

Those ChannelAccount objects got an ID that depend on the channel you are currently using. For example from what I previously analysed during my work on Bot Framework:

For Skype the bot ID is a concatenation of "28:" and its Microsoft AppId, but you need to know the User ID and a conversation between them MUST HAVE EXISTED => you can't really do a proactive message

For Facebook messager, the bot ID is the FB Page ID, but the user ID is a specific messenger ID that you cannot request easily => complicated, must well know Facebook APIs

For Slack, the bot ID is a concatenation of its Slack's Bot_id, a ':' and Slack's Team_id. The user ID is a concatenation of its Slack's id, a ':' and Slack's Team_id  => interesting

For Twilio SMS, bot ID and user ID are their phone numbers => easy

For email channel it is their emails

...

If you want to know how to start a Conversation once you got those IDs, jump to the section at the end.

Slack IDs focus

The advantage of Slack is the possibility to get all the necessary parameters to start a conversation by only knowing a few information and requesting their API. For example you can start a conversation by knowing only:

Bot Slack's username

User email address or  Slack's username

Then you can use Slack's API to get what the bot really needs.

How to get Slack data?

1 method to call the service, 1 using it to get the right data:

public class SlackService
{
    internal static async Task<SlackMembersRootObject> GetSlackUsersList(string slackApiToken, CancellationToken ct)
    {
        using (var client = new HttpClient())
        {
            using (var response = await client.GetAsync($"https://slack.com/api/users.list?token=" + $"{slackApiToken}", ct).ConfigureAwait(false))
            {
                var jsonString = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
                var rootObject = Newtonsoft.Json.JsonConvert.DeserializeObject<SlackMembersRootObject>(jsonString);
                return rootObject;
            }
        }
    }
}

public static async Task StartSlackDirectMessage(string msAppId, string msAppPassword, string slackApiToken, string message, string botSlackUsername, string botName, string destEmailAddress, string destName, string lang, CancellationToken ct)
{
    // Getting Slack user (and bot) list
    var slackUsersList = await SlackService.GetSlackUsersList(slackApiToken, CancellationToken.None);

    // Get Bot SlackId by searching its "username", you can also search by other criteria
    var slackBotUser = slackUsersList.Members.FirstOrDefault(x => x.Name == botSlackUsername);
    if (slackBotUser == null)
    {
        throw new Exception($"Slack API : no bot found for name '{botSlackUsername}'");
    }

    // Get User SlackId by email address
    var slackTargetedUser = slackUsersList.Members.FirstOrDefault(x => x.Profile.Email == destEmailAddress);
    if (slackTargetedUser != null)
    {
        // if found, starting the conversation by passing the right IDs
        await StartDirectMessage(msAppId, msAppPassword, "https://slack.botframework.com/", "slack", $"{slackBotUser.Profile.Bot_id}:{slackBotUser.Team_id}", botName, $"{slackTargetedUser.Id}:{slackTargetedUser.Team_id}", destName, message, lang, ct);
    }
    else
    {
        throw new Exception($"Slack API : no user found for email '{destEmailAddress}'");
    }
}

How to start a conversation?
Once you know the relevant information about your bot and user (which depend on the channel, once again), you can start your conversation.

Create conversation

Create message

Send message to conversation

Sample method:

private static async Task StartDirectMessage(string msAppId, string msAppPassword, string connectorClientUrl, string channelId, string fromId, string fromName, string recipientId, string recipientName, string message, string locale, CancellationToken token)
{
    // Init connector
    MicrosoftAppCredentials.TrustServiceUrl(connectorClientUrl, DateTime.Now.AddDays(7));
    var account = new MicrosoftAppCredentials(msAppId, msAppPassword);
    var connector = new ConnectorClient(new Uri(connectorClientUrl), account);

    // Init conversation members
    ChannelAccount channelFrom = new ChannelAccount(fromId, fromName);
    ChannelAccount channelTo = new ChannelAccount(recipientId, recipientName);

    // Create Conversation
    var conversation = await connector.Conversations.CreateDirectConversationAsync(channelFrom, channelTo);

    // Create message Activity and send it to Conversation
    IMessageActivity newMessage = Activity.CreateMessageActivity();
    newMessage.Type = ActivityTypes.Message;
    newMessage.From = channelFrom;
    newMessage.Recipient = channelTo;

    newMessage.Locale = (locale ?? "en-US");
    newMessage.ChannelId = channelId;
    newMessage.Conversation = new ConversationAccount(id: conversation.Id);
    newMessage.Text = message;
    await connector.Conversations.SendToConversationAsync((Activity)newMessage);
}

So back to your context:

You got a ConversationUpdate on a group conversation (ActivityTypes.ConversationUpdate and activity.MembersAdded.Count != 0): in this ConversationUpdate, you can get the userId and your botId. Then you start a new Conversation (using code above), then create a fake message that you don't send and get the IDialogTask from it: you will be able to launch your Dialog

Example:

if (activity.MembersAdded.Count != 0)
{
    // We have to create a new conversation between Bot and AddedUser

    #region Conversation creation
    // Connector init
    MicrosoftAppCredentials.TrustServiceUrl(activity.ServiceUrl, DateTime.Now.AddDays(7));
    var account = new MicrosoftAppCredentials("yourMsAppId", "yourMsAppPassword");
    var connector = new ConnectorClient(new Uri(activity.ServiceUrl), account);

    // From the conversationUpdate message, Recipient = bot and From = User
    ChannelAccount botChannelAccount = new ChannelAccount(activity.Recipient.Id, activity.Recipient.Name);
    ChannelAccount userChannelAccount = new ChannelAccount(activity.From.Id, activity.From.Name);

    // Create Conversation
    var conversation = await connector.Conversations.CreateDirectConversationAsync(botChannelAccount, userChannelAccount);
    #endregion

    // Then we prepare a fake message from bot to user, mandatory to get the working IDialogTask. This message MUST be from User to Bot, if you want the following Dialog to be from Bot to User
    IMessageActivity fakeMessage = Activity.CreateMessageActivity();
    fakeMessage.From = userChannelAccount;
    fakeMessage.Recipient = botChannelAccount;
    fakeMessage.ChannelId = activity.ChannelId;
    fakeMessage.Conversation = new ConversationAccount(id: conversation.Id);

    fakeMessage.ServiceUrl = activity.ServiceUrl;
    fakeMessage.Id = Guid.NewGuid().ToString();

    // Then use this fake message to launch the new dialog
    using (var scope = DialogModule.BeginLifetimeScope(Conversation.Container, fakeMessage))
    {
        var botData = scope.Resolve<IBotData>();
        await botData.LoadAsync(CancellationToken.None);

        //This is our dialog stack
        var task = scope.Resolve<IDialogTask>();

        //interrupt the stack. This means that we're stopping whatever conversation that is currently happening with the user
        //Then adding this stack to run and once it's finished, we will be back to the original conversation
        var dialog = new DemoDialog();
        task.Call(dialog.Void<object, IMessageActivity>(), null);

        await task.PollAsync(CancellationToken.None);

        //flush dialog stack
        await botData.FlushAsync(CancellationToken.None);

    }
}


问:
How to replace \" with empty value
I have a JSON string:

```<code>{
    "key1": "abc",
    "key2": "def",
    "key3": "gh\"i\"j"
}
</code>```

Expected o/p:

```<code>{
    "key1": "abc",
    "key2": "def",
    "key3": "ghij"
}
</code>```

Java string replace() and replaceAll() are replacing all double quotes:

```<code>System.out.println(a.replaceAll("\\\"",""));

System.out.println(a.replace("\"",""));
</code>```

Output:

```<code>{
    key1: abc,
    key2: def,
    key3: ghij
}
</code>```

The reason I'm trying to replace \" is that some operation has to be done using JSON, escaping special characters and storing the JSON string to a database. Here the json becomes invalid because of \".

How can I replace only \" with empty value?

答:
You want to replace \" with an empty string.

\ has a special meaning in regular expressions so you need to escape it. Hence, you need to replace \\" with an empty string.

Then, writing the string \\" in a string in java requires to escape each \ + the ".

Hence, the expression is \\ \\ \" (I added some spaces for readability):

Finally, you need to write it like this :

```<code>a.replaceAll("\\\\\"", "");
</code>```

Title: How to replace \" with empty value

Body:
I have a JSON string:

{
    "key1": "abc",
    "key2": "def",
    "key3": "gh\"i\"j"
}

Expected o/p:

{
    "key1": "abc",
    "key2": "def",
    "key3": "ghij"
}

Java string replace() and replaceAll() are replacing all double quotes:

System.out.println(a.replaceAll("\\\"",""));

System.out.println(a.replace("\"",""));

Output:

{
    key1: abc,
    key2: def,
    key3: ghij
}

The reason I'm trying to replace \" is that some operation has to be done using JSON, escaping special characters and storing the JSON string to a database. Here the json becomes invalid because of \".

How can I replace only \" with empty value?

Body:
You want to replace \" with an empty string.

\ has a special meaning in regular expressions so you need to escape it. Hence, you need to replace \\" with an empty string.

Then, writing the string \\" in a string in java requires to escape each \ + the ".

Hence, the expression is \\ \\ \" (I added some spaces for readability):

Finally, you need to write it like this :

a.replaceAll("\\\\\"", "");


问:
Making the arduino do the task based on value returned by a function in python
in the code below, function openthedoor(set_accepted_list,set_list_ant_id) returns a set of values called as set_for_comparison.Once you print set_for_comparison, you get a set['5','8','32']. I wrote an ardunio code to blink an LED whenever functionopenthedoor(set_accepted_list,set_list_ant_id) return some value. I call all the functions in the later part of the code. But when i run the code, the LED only blink once and then stops, eventhough the function is returning values. Any suggestions?

Python_code:

```<code>set_for_comparison = set()
def openthedoor(set_accepted_list,set_list_ant_id):
if len(set_accepted_list &  set_list_ant_id) >0:
    print"yes"
else:
    print"no"
set_for_comparison = set(set_accepted_list &  set_list_ant_id)
return set_for_comparison
</code>```

I will use set_for_comparison for blinking the LED. The python code which uses the value returned for blinking the LED is shown below .

```<code>def code_controlling_gate(set_for_comparison):
connected = False
ser = serial.Serial("COM11",9600)   #for communicating with the arduino
while not connected:
    serin = ser.read()
    connected = True
ser.write('1')
while ser.read() == '1':
    ser.read()
ser.close()
</code>```

Arduino code

```<code>void setup() {
  Serial.begin(9600);  #baud rate
  pinMode(10,OUTPUT);  #output pin to connect arduino
  Serial.write('1');
}
void loop() {
  while(Serial.available()<0){
  digitalWrite(10,HIGH);
  delay(50);
  digitalWrite(10,LOW);
  delay(50);
  Serial.read();
  }
}
</code>```

答:
Because you only call serial.write(1) in your setup(){...} so in your python script connected will only be true once per reboot of your arduino.

You need to call serial.write within the loop(){..}

Body:
in the code below, function openthedoor(set_accepted_list,set_list_ant_id) returns a set of values called as set_for_comparison.Once you print set_for_comparison, you get a set['5','8','32']. I wrote an ardunio code to blink an LED whenever functionopenthedoor(set_accepted_list,set_list_ant_id) return some value. I call all the functions in the later part of the code. But when i run the code, the LED only blink once and then stops, eventhough the function is returning values. Any suggestions?

Python_code:

set_for_comparison = set()
def openthedoor(set_accepted_list,set_list_ant_id):
if len(set_accepted_list &  set_list_ant_id) >0:
    print"yes"
else:
    print"no"
set_for_comparison = set(set_accepted_list &  set_list_ant_id)
return set_for_comparison

I will use set_for_comparison for blinking the LED. The python code which uses the value returned for blinking the LED is shown below .

def code_controlling_gate(set_for_comparison):
connected = False
ser = serial.Serial("COM11",9600)   #for communicating with the arduino
while not connected:
    serin = ser.read()
    connected = True
ser.write('1')
while ser.read() == '1':
    ser.read()
ser.close()

Arduino code

void setup() {
  Serial.begin(9600);  #baud rate
  pinMode(10,OUTPUT);  #output pin to connect arduino
  Serial.write('1');
}
void loop() {
  while(Serial.available()<0){
  digitalWrite(10,HIGH);
  delay(50);
  digitalWrite(10,LOW);
  delay(50);
  Serial.read();
  }
}


问:
Getting date value null in ajax request
I am using Ajax request to send the value of date to my API Controller here is my ajax call

```<code> $("#txtpdate").on("changeDate", function (e) {
        var Date =$('#txtpdate').val();
        console.log(Date);
        $.ajax({
            type: 'POST',
            contentType: false,
            url: '/api/ServiceProvider/GetUpdatedPrice',
            data:{date: Date  },
            cache: false
        }).done(function (response) {

        });
});
</code>```

And here is my api controller

```<code>[HttpPost]
[Route("GetUpdatedPrice")]
public  ServiceProviderDocuments GetUpdatedPrice(DateTime date)
{
    return  ServiceProviderDocumentsGateway.GetUpdatedPriceofBike(date);
}
</code>```

I am getting the desired value in console.log(Date) but when I reached to the controller it is showing null value
please take a look on the below image

答:
Do the following:

Change the type of the parameter to string:

```<code>[HttpPost]
[Route("GetUpdatedPrice")]
public  ServiceProviderDocuments GetUpdatedPrice(string date)
{
    //Convert date to Datetime here
}
</code>```

Change the contentType to:

```<code>contentType: 'application/json; charset=utf-8',
</code>```

Stringify the date:

```<code>data: JSON.stringify({ date: Date }),
</code>```

Title: Getting date value null in ajax request

Body:
I am using Ajax request to send the value of date to my API Controller here is my ajax call

 $("#txtpdate").on("changeDate", function (e) {
        var Date =$('#txtpdate').val();
        console.log(Date);
        $.ajax({
            type: 'POST',
            contentType: false,
            url: '/api/ServiceProvider/GetUpdatedPrice',
            data:{date: Date  },
            cache: false
        }).done(function (response) {

        });
});

And here is my api controller

[HttpPost]
[Route("GetUpdatedPrice")]
public  ServiceProviderDocuments GetUpdatedPrice(DateTime date)
{
    return  ServiceProviderDocumentsGateway.GetUpdatedPriceofBike(date);
}

I am getting the desired value in console.log(Date) but when I reached to the controller it is showing null value
please take a look on the below image

Body:
Do the following:

Change the type of the parameter to string:

[HttpPost]
[Route("GetUpdatedPrice")]
public  ServiceProviderDocuments GetUpdatedPrice(string date)
{
    //Convert date to Datetime here
}

Change the contentType to:

contentType: 'application/json; charset=utf-8',

Stringify the date:

data: JSON.stringify({ date: Date }),


问:
Python create sorted list based on attribute
I need to create a list of dictionary values, sorted based on whether or not the value is empty, my attempt gets the desired output but has to iterate twice over the dictionary, I was wondering if there was a way to do this only iterating once? My actual dictionary contains like 50,000 values and just iterating once would save some time when doing it repeatedly

```<code>d = {'id1':[],
     'id2':[1],
     'id3':[1]}
l = [v for v in d.values() if v]+[v for v in d.values() if not v]
print (l)
</code>```

this is my desired output:

```<code>[[1], [1], []]
</code>```

答:
You can sort with respect to length:</p>

```<code>l = sorted(d.values(), key=len, reverse=True)
</code>```

Body:
I need to create a list of dictionary values, sorted based on whether or not the value is empty, my attempt gets the desired output but has to iterate twice over the dictionary, I was wondering if there was a way to do this only iterating once? My actual dictionary contains like 50,000 values and just iterating once would save some time when doing it repeatedly

d = {'id1':[],
     'id2':[1],
     'id3':[1]}
l = [v for v in d.values() if v]+[v for v in d.values() if not v]
print (l)

this is my desired output:

[[1], [1], []]

Body:
You can sort with respect to length:

l = sorted(d.values(), key=len, reverse=True)


问:
How do you find out the caller function in JavaScript when use strict is enabled?
Is it possible to see the callee/caller of a function when use strict is enabled?

'use strict';

function jamie (){
    console.info(arguments.callee.caller.name);
    //this will output the below error
    //uncaught TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them
};

function jiminyCricket (){
   jamie();
}

jiminyCricket ();```

答:
It does not worked for me
Here is what I finally do, just in case it helps someone</p>

```<code>function callerName() {
  try {
    throw new Error();
  }
  catch (e) {
    try {
      return e.stack.split('at ')[3].split(' ')[0];
    } catch (e) {
      return '';
    }
  }

}
function currentFunction(){
  let whoCallMe = callerName();
  console.log(whoCallMe);
}
</code>```

Body:
It does not worked for me
Here is what I finally do, just in case it helps someone

function callerName() {
  try {
    throw new Error();
  }
  catch (e) {
    try {
      return e.stack.split('at ')[3].split(' ')[0];
    } catch (e) {
      return '';
    }
  }

}
function currentFunction(){
  let whoCallMe = callerName();
  console.log(whoCallMe);
}


问:
How to call a function to execute on the url
I wrote a code which is working fine but now I want it to be in a function so as to call it on the url. I will really appreciate if you guys can help.

Here is my code.

```<code>$conn = mysqli_connect("localhost","root","","db");
if(mysqli_connect_errno()){
    echo "Unable to connect".mysqli_connect_error();
}

function day(){
$sql = "SELECT *, DATE_FORMAT(user_registerdate, '%m/%d/%Y') FROM ts_user
        WHERE DATE(user_registerdate) = CURDATE() - INTERVAL 5 DAY";
    if($result = mysqli_query($conn,$sql)){
        while($row = mysqli_fetch_assoc($result)){
            echo $row['user_uname']."<br />";
        }
    }
}
</code>```

And am calling it on the url as
http://localhost/test/index.php/day

Please telling me what am doing wrong. am I calling it wrongly on the url?

答:
You have to tell PHP, that you are using $conn from another scope.
http://php.net/manual/en/language.variables.scope.php

Simply use global $conn inside function tags.

```<code>$conn = mysqli_connect("localhost","root","","db");
if(mysqli_connect_errno()){
echo "Unable to connect".mysqli_connect_error();
}
function day(){
    global $conn;
    $sql = "SELECT *, DATE_FORMAT(user_registerdate, '%m/%d/%Y') FROM ts_user
        WHERE DATE(user_registerdate) = CURDATE() - INTERVAL 5 DAY";
    if($result = mysqli_query($conn,$sql)){
        while($row = mysqli_fetch_assoc($result)){
            echo $row['user_uname']."<br />";
        }
    }
}
</code>```

Body:
I wrote a code which is working fine but now I want it to be in a function so as to call it on the url. I will really appreciate if you guys can help.

Here is my code.

$conn = mysqli_connect("localhost","root","","db");
if(mysqli_connect_errno()){
    echo "Unable to connect".mysqli_connect_error();
}

function day(){
$sql = "SELECT *, DATE_FORMAT(user_registerdate, '%m/%d/%Y') FROM ts_user
        WHERE DATE(user_registerdate) = CURDATE() - INTERVAL 5 DAY";
    if($result = mysqli_query($conn,$sql)){
        while($row = mysqli_fetch_assoc($result)){
            echo $row['user_uname']."
";
        }
    }
}

And am calling it on the url as
http://localhost/test/index.php/day

Please telling me what am doing wrong. am I calling it wrongly on the url?

Body:
You have to tell PHP, that you are using $conn from another scope.
http://php.net/manual/en/language.variables.scope.php

Simply use global $conn inside function tags.

$conn = mysqli_connect("localhost","root","","db");
if(mysqli_connect_errno()){
echo "Unable to connect".mysqli_connect_error();
}
function day(){
    global $conn;
    $sql = "SELECT *, DATE_FORMAT(user_registerdate, '%m/%d/%Y') FROM ts_user
        WHERE DATE(user_registerdate) = CURDATE() - INTERVAL 5 DAY";
    if($result = mysqli_query($conn,$sql)){
        while($row = mysqli_fetch_assoc($result)){
            echo $row['user_uname']."<br />";
        }
    }
}


问:
Highcharts display value of the average with addPlotLine
Looking at http://jsfiddle.net/0tfkfh2v/16/ which does what I want but it doesn't display the average amount - how would I get around this?

```<code>yAxis.addPlotLine({
    value: (sum/count),
    color: 'red',
    width: 2,
    id: 'avgLine'
});
</code>```

Thanks

答:
Add label inside yAxis.addPlotLine({...})

Fiddle Demo

```<code> yAxis.addPlotLine({
    value: (sum / count),
    label: {
      text: (sum / count).toFixed(2),
      verticalAlign: 'middle',
      align: 'right',
      rotation: 0,
    },
    color: 'red',
    width: 2,
    id: 'avgLine'
  });
</code>```

Body:
Looking at http://jsfiddle.net/0tfkfh2v/16/ which does what I want but it doesn't display the average amount - how would I get around this?

yAxis.addPlotLine({
    value: (sum/count),
    color: 'red',
    width: 2,
    id: 'avgLine'
});

Thanks

Body:
Add label inside yAxis.addPlotLine({...})

Fiddle Demo

 yAxis.addPlotLine({
    value: (sum / count),
    label: {
      text: (sum / count).toFixed(2),
      verticalAlign: 'middle',
      align: 'right',
      rotation: 0,
    },
    color: 'red',
    width: 2,
    id: 'avgLine'
  });


问:
Link encryption with django and python
I'm having a download application and I want to encrypt the links for file downloads, so that the user doesn't know the id of the file. Furthermore I'd like to include date/time in the link, and check when serving the file if the link is still valid.

There's a similar question asked here, but I'm running into problems with the character encodings, since I'd like to have urls like /file/encrypted_string/ pointing to the views for downloading, so best would be if the encrypted result only contains letters and numbers. I prefer not using a hash, because I do not want to store a mapping hash <> file somewhere. I do not know if there's a good encryption out there that fulfills my needs...

答:
Sounds like it would be easy, especially if you don't mind using the same encryption key forever. Just delimit a string (/ or : works as well as anything) for the file name, the date/time, and anything else you want to include, then encrypt and b64 it! Remember to use urlsafe_b64encode, not the regular b64encode, which will produce broken urls. It'll be a long string, but so what?

I've done this a few times, using a slight variation: Add a few random characters as the last piece of the key and include that at the beginning or end of the string - more secure than always reusing the same key, without the headaches of a database mapping. As long as your key is complex enough the exposed bits won't be enough to let crackers generate requests at will.

Of course, if the file doesn't exist, don't let them see the decoded result...

Title: Link encryption with django and python


问:
How to use spinner items as input to get a result
I'm new to android. I'm building an app for city bus fare. I will use two spinners as 'starting' point and 'destination'. I want to match these two input and get the result as 'fare cost' in a textview. Please give me some easy idea of how to implement this.</p>

答: use spinner.getSelectedItem() it return selected object or                         spinner.getSelectedItemPosition() it will return selected item position based on selection of both spinner you will calculate you fare cost</p>


问:
Enumeration is throwing concurrentModification Exception. why?
Enumeration is Fail-safe. Fail-safe iterators will work on the cloning of the original collection. then why it is throwing concurrentModificationException? please clarify.

Please find my code:

```<code>public static void main(String[] args) {

    Vector<String> v=new Vector<String>();
    v.add("Amit");
    v.add("Raj");
    v.add("Pathak");
    v.add("Sumit");
    v.add("Aron");
    v.add("Trek");

    Enumeration en=(Enumeration) Collections.enumeration(v);

    while(en.hasMoreElements())
    {
        String value=(String) en.nextElement();
        System.out.println(value);
        v.remove(value);//modifying the collection

    }

}
</code>```

Find the error message below

```<code>Exception in thread "main" java.util.ConcurrentModificationException
at java.util.Vector$Itr.checkForComodification(Unknown Source)
at java.util.Vector$Itr.next(Unknown Source)
at java.util.Collections$2.nextElement(Unknown Source)
at valar.org.src.EnumerationTest.main(EnumerationTest.java:24)
</code>```

答:
Collections.enumeration(Collection) will create an iterator from the collection passed as parameter :

```<code>public static <T> Enumeration<T> enumeration(final Collection<T> c) {
    return new Enumeration<T>() {
        private final Iterator<T> i = c.iterator();

        public boolean hasMoreElements() {
            return i.hasNext();
        }

        public T nextElement() {
            return i.next();
        }
    };
}
</code>```

It means that the iterator is backed to the collection which you remove element in the iterator loop and you cannot remove an element of the collection on which you iterate with the iterator.

You should create a copy of the Vector you pass in the enumeration() invocation :

```<code>Enumeration<String> en = Collections.enumeration(new Vector<String>(v));
</code>```

And as a side note, you should favor List interface and ArrayList implementation over Vector (that is synchronized) and declare generics collection that spares cast and increase the type safety of the code.

So it would give this code (I left the Vector use as it is maybe a not modifiable constraint but I specified the generics as it is often simpler to add even in a legacy code):

```<code>Vector<String> v = new Vector<String>();
v.add("Amit");
v.add("Raj");
v.add("Pathak");
v.add("Sumit");
v.add("Aron");
v.add("Trek");

Enumeration<String> en = Collections.enumeration(new Vector<String>(v));

while (en.hasMoreElements()) {
    String value = (String) en.nextElement();
    System.out.println(value);
    v.remove(value);// modifying the collection
}
</code>```

Body:
Enumeration is Fail-safe. Fail-safe iterators will work on the cloning of the original collection. then why it is throwing concurrentModificationException? please clarify.

Please find my code:

public static void main(String[] args) {

    Vector<String> v=new Vector<String>();
    v.add("Amit");
    v.add("Raj");
    v.add("Pathak");
    v.add("Sumit");
    v.add("Aron");
    v.add("Trek");

    Enumeration en=(Enumeration) Collections.enumeration(v);

    while(en.hasMoreElements())
    {
        String value=(String) en.nextElement();
        System.out.println(value);
        v.remove(value);//modifying the collection

    }

}

Find the error message below

Exception in thread "main" java.util.ConcurrentModificationException
at java.util.Vector$Itr.checkForComodification(Unknown Source)
at java.util.Vector$Itr.next(Unknown Source)
at java.util.Collections$2.nextElement(Unknown Source)
at valar.org.src.EnumerationTest.main(EnumerationTest.java:24)

Body:
Collections.enumeration(Collection) will create an iterator from the collection passed as parameter :

public static <T> Enumeration<T> enumeration(final Collection<T> c) {
    return new Enumeration<T>() {
        private final Iterator<T> i = c.iterator();

        public boolean hasMoreElements() {
            return i.hasNext();
        }

        public T nextElement() {
            return i.next();
        }
    };
}

It means that the iterator is backed to the collection which you remove element in the iterator loop and you cannot remove an element of the collection on which you iterate with the iterator.

You should create a copy of the Vector you pass in the enumeration() invocation :

Enumeration<String> en = Collections.enumeration(new Vector<String>(v));

And as a side note, you should favor List interface and ArrayList implementation over Vector (that is synchronized) and declare generics collection that spares cast and increase the type safety of the code.

So it would give this code (I left the Vector use as it is maybe a not modifiable constraint but I specified the generics as it is often simpler to add even in a legacy code):

Vector<String> v = new Vector<String>();
v.add("Amit");
v.add("Raj");
v.add("Pathak");
v.add("Sumit");
v.add("Aron");
v.add("Trek");

Enumeration<String> en = Collections.enumeration(new Vector<String>(v));

while (en.hasMoreElements()) {
    String value = (String) en.nextElement();
    System.out.println(value);
    v.remove(value);// modifying the collection
}


问:
Angularjs orderBy: how to call default comparator from custom sort function
I have a custom sort function to convert strings to numbers for one column in a grid. The other columns are comprised of strings or date values. I have a custom sort function which checks for the number column and performs the conversion, but for the other values I want the default comparator's behavior. How do I achieve this?

$scope.sort = function (keyname) {
  $scope.sortKey = keyname;
  $scope.reverse = !$scope.reverse;
};

$scope.sortSubGrid = function (a, b) {
  if ($scope.sortKey === 'caseNumber') {
    return = parseInt(b.value) -parseInt(a.value);
  }
  else {
    return = a.value > b.value;
  }
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><tr dir-paginate="agreement in agreements|orderBy:sortKey:reverse:sortSubGrid" ...></code>```

The second half of the sortSubGrid function is intended to sort the non-numeric columns, but isn't achieving the results I expect, which is simply the results the default comparator provides. How do I get the default behavior for this second clause?

答:
According to the code in orderBy.js you can use either the default or the custom but no both as you describe, it would be a nice functionality though.

```<code>// Define the `compare()` function. Use a default comparator if none is specified.
var compare = isFunction(compareFn) ? compareFn : defaultCompare;
</code>```

So you can always get the original defaultCompare code and modify it.

```<code>// source orderBy.js
function defaultCompare(v1, v2) {
  var result = 0;
  var type1 = v1.type;
  var type2 = v2.type;

  if (type1 === type2) {
    var value1 = v1.value;
    var value2 = v2.value;

    if (type1 === 'string') {
      // Compare strings case-insensitively
      value1 = value1.toLowerCase();
      value2 = value2.toLowerCase();
    } else if (type1 === 'object') {
      // For basic objects, use the position of the object
      // in the collection instead of the value
      if (isObject(value1)) value1 = v1.index;
      if (isObject(value2)) value2 = v2.index;
    }

    if (value1 !== value2) {
      result = value1 < value2 ? -1 : 1;
    }
  } else {
    result = type1 < type2 ? -1 : 1;
  }

  return result;
}
</code>```

Body:
I have a custom sort function to convert strings to numbers for one column in a grid. The other columns are comprised of strings or date values. I have a custom sort function which checks for the number column and performs the conversion, but for the other values I want the default comparator's behavior. How do I achieve this?

$scope.sort = function (keyname) {
  $scope.sortKey = keyname;
  $scope.reverse = !$scope.reverse;
};

$scope.sortSubGrid = function (a, b) {
  if ($scope.sortKey === 'caseNumber') {
    return = parseInt(b.value) -parseInt(a.value);
  }
  else {
    return = a.value > b.value;
  }
};

The second half of the sortSubGrid function is intended to sort the non-numeric columns, but isn't achieving the results I expect, which is simply the results the default comparator provides. How do I get the default behavior for this second clause?

Body:
According to the code in orderBy.js you can use either the default or the custom but no both as you describe, it would be a nice functionality though.

// Define the `compare()` function. Use a default comparator if none is specified.
var compare = isFunction(compareFn) ? compareFn : defaultCompare;

So you can always get the original defaultCompare code and modify it.

// source orderBy.js
function defaultCompare(v1, v2) {
  var result = 0;
  var type1 = v1.type;
  var type2 = v2.type;

  if (type1 === type2) {
    var value1 = v1.value;
    var value2 = v2.value;

    if (type1 === 'string') {
      // Compare strings case-insensitively
      value1 = value1.toLowerCase();
      value2 = value2.toLowerCase();
    } else if (type1 === 'object') {
      // For basic objects, use the position of the object
      // in the collection instead of the value
      if (isObject(value1)) value1 = v1.index;
      if (isObject(value2)) value2 = v2.index;
    }

    if (value1 !== value2) {
      result = value1 < value2 ? -1 : 1;
    }
  } else {
    result = type1 < type2 ? -1 : 1;
  }

  return result;
}

ContentLicense: CC BY-SA 4.0


问:
getting confusion on this explain this loop result in java
```<code>int a = 0, b = 0;

for (int i = 0; i < 5; i++) {
    if (++a > 2 || ++b > 2) {
        a++;
    }
}

System.out.println("a= " + a + " b=" + b);
</code>```

can you explain the logic please?

答:
i=0 a=1 (1st condition is false so 2nd is check) b=1

i=1 a=2 (1st condition is false so 2nd is check) b=2

i=2 ++a increment a , a=3 condition is true enter in if condition and a become 4 and b remain 2

similarly i=3 a=6 b=2 and i=4 a=8 b=2;

In case of or(||) condition whenever compiler encounter true condition it stop checking other statement

Body:
int a = 0, b = 0;

for (int i = 0; i < 5; i++) {
    if (++a > 2 || ++b > 2) {
        a++;
    }
}

System.out.println("a= " + a + " b=" + b);

can you explain the logic please?


问:
matlab running all linprog algortithms (is there a matlab-list of algorithms?)
Matlab offers multiple algorithms for solving Linear Programs.
For example Matlab R2012b offers: 'active-set', 'trust-region-reflective', 'interior-point', 'interior-point-convex', 'levenberg-marquardt', 'trust-region-dogleg', 'lm-line-search', or 'sqp'.

But other versions of Matlab support different algorithms.

I would like to run a loop over all algorithms that are supported by the users Matlab-Version. And I would like them to be ordered like the recommendation order of Matlab.

I would like to implement something like this:

```<code>i=1;
x=[];
while (isempty(x))
    options=optimset(options,'Algorithm',Here_I_need_a_list_of_Algorithms(i))
    x = linprog(f,A,b,Aeq,beq,lb,ub,x0,options);
end
</code>```

In 99% this code should be equivalent to

```<code>x = linprog(f,A,b,Aeq,beq,lb,ub,x0,options);
</code>```

but sometimes the algorithm gives back an empty array because of numerical problems (exitflag -4). If there is a chance that one of the other algorithms can find a solution I would like to try them too.

So my question is:
Is there a possibility to automatically get a list of all linprog-algorithms that are supported by the installed Matlab-version ordered like Matlab recommends them.

I think looping through all algorithms can make sense in other scenarios too. For example when you need very precise data and have a lot of time, you could run them all and than evaluate which gives the best results.
Or one would like to loop through all algorithms, if one wants to find which algorithms is the best for LPs with a certain structure.

答:
There's no automatic way to do this as far as I know. If you really want to do it, the easiest thing to do would be to go to the online documentation, and check through previous versions (online documentation is available for old versions, not just the most recent release), and construct some variables like this:

```<code>r2012balgos = {'active-set', 'trust-region-reflective', 'interior-point', 'interior-point-convex', 'levenberg-marquardt', 'trust-region-dogleg', 'lm-line-search', 'sqp'};

...

r2017aalgos = {...};

v = ver('matlab');

switch v.Release
    case '(R2012b)'
        algos = r2012balgos;
    ....
    case '(R2017a)'
        algos = r2017aalgos;
end

% loop through each of the algorithms
</code>```

Seems boring, but it should only take you about 30 minutes.

There's a reason MathWorks aren't making this as easy as you might hope, though, because what you're asking for isn't a great idea.

It is possible to construct artificial problems where one algorithm finds a solution and the others don't. But in practice, typically if the recommended algorithm doesn't find a solution this doesn't indicate that you should switch algorithms, it indicates that your problem wasn't well-formulated, and you should consider modifying it, perhaps by modifying some constraints, or reformulating the objective function.

And after all, why stop with just looping through the alternative algorithms? Why not also loop through lots of values for other options such as constraint tolerances, optimality tolerances, maximum number of function evaluations, etc.? These may have just as much likelihood of affecting things as a choice of algorithm. And soon you're running an optimisation algorithm to search through the space of meta-parameters for your original optimisation.

That's not a great plan - probably better to just choose one of the recommended algorithms, stick to that, and if things don't work out then focus on improving your formulation of the problems rather than over-tweaking the optimisation itself.

Body:
Matlab offers multiple algorithms for solving Linear Programs.
For example Matlab R2012b offers: 'active-set', 'trust-region-reflective', 'interior-point', 'interior-point-convex', 'levenberg-marquardt', 'trust-region-dogleg', 'lm-line-search', or 'sqp'.

But other versions of Matlab support different algorithms.

I would like to run a loop over all algorithms that are supported by the users Matlab-Version. And I would like them to be ordered like the recommendation order of Matlab.

I would like to implement something like this:

i=1;
x=[];
while (isempty(x))
    options=optimset(options,'Algorithm',Here_I_need_a_list_of_Algorithms(i))
    x = linprog(f,A,b,Aeq,beq,lb,ub,x0,options);
end

In 99% this code should be equivalent to

x = linprog(f,A,b,Aeq,beq,lb,ub,x0,options);

but sometimes the algorithm gives back an empty array because of numerical problems (exitflag -4). If there is a chance that one of the other algorithms can find a solution I would like to try them too.

So my question is:
Is there a possibility to automatically get a list of all linprog-algorithms that are supported by the installed Matlab-version ordered like Matlab recommends them.

I think looping through all algorithms can make sense in other scenarios too. For example when you need very precise data and have a lot of time, you could run them all and than evaluate which gives the best results.
Or one would like to loop through all algorithms, if one wants to find which algorithms is the best for LPs with a certain structure.

Body:
There's no automatic way to do this as far as I know. If you really want to do it, the easiest thing to do would be to go to the online documentation, and check through previous versions (online documentation is available for old versions, not just the most recent release), and construct some variables like this:

r2012balgos = {'active-set', 'trust-region-reflective', 'interior-point', 'interior-point-convex', 'levenberg-marquardt', 'trust-region-dogleg', 'lm-line-search', 'sqp'};

...

r2017aalgos = {...};

v = ver('matlab');

switch v.Release
    case '(R2012b)'
        algos = r2012balgos;
    ....
    case '(R2017a)'
        algos = r2017aalgos;
end

% loop through each of the algorithms

Seems boring, but it should only take you about 30 minutes.

There's a reason MathWorks aren't making this as easy as you might hope, though, because what you're asking for isn't a great idea.

It is possible to construct artificial problems where one algorithm finds a solution and the others don't. But in practice, typically if the recommended algorithm doesn't find a solution this doesn't indicate that you should switch algorithms, it indicates that your problem wasn't well-formulated, and you should consider modifying it, perhaps by modifying some constraints, or reformulating the objective function.

And after all, why stop with just looping through the alternative algorithms? Why not also loop through lots of values for other options such as constraint tolerances, optimality tolerances, maximum number of function evaluations, etc.? These may have just as much likelihood of affecting things as a choice of algorithm. And soon you're running an optimisation algorithm to search through the space of meta-parameters for your original optimisation.

That's not a great plan - probably better to just choose one of the recommended algorithms, stick to that, and if things don't work out then focus on improving your formulation of the problems rather than over-tweaking the optimisation itself.


问:
login wordpress issue : Warning: mysql_connect() [function.mysql-connect]: Access denied for user
I'm trying to login to my site but I get this error

Warning: mysql_connect() [function.mysql-connect]: Access denied for user 'edwardl_wp1user'@'localhost' (using password: YES) in /home1/edwardl8/public_html/wp-includes/wp-db.php on line 1568

Here is line 1568:

```<code>$this->dbh = mysql_connect( $this->dbhost, $this->dbuser, $this
>dbpassword, $new_link, $client_flags );
 } else {
$this->dbh = @mysql_connect( $this->dbhost, $this->dbuser,
$this->dbpassword, $new_link, $client_flags );
}
</code>```

I wrote my passwords correctly, but it's still not working.

答: Check if the database prefix is correct in your wp-config.php . Sometimes that triggerss such an error.</p>

Body:
I'm trying to login to my site but I get this error

Warning: mysql_connect() [function.mysql-connect]: Access denied for user 'edwardl_wp1user'@'localhost' (using password: YES) in /home1/edwardl8/public_html/wp-includes/wp-db.php on line 1568

Here is line 1568:

$this->dbh = mysql_connect( $this->dbhost, $this->dbuser, $this
>dbpassword, $new_link, $client_flags );
 } else {
$this->dbh = @mysql_connect( $this->dbhost, $this->dbuser,
$this->dbpassword, $new_link, $client_flags );
}

I wrote my passwords correctly, but it's still not working.


问:
Swift protocol inheritance and dynamic object confusion
Trying with here is my setup:

```<code>protocol CommonFeatureProtocol { }
extension CommonFeatureProtocol { }

 protocol SpecificFeature1Protocol : CommonFeatureProtocol {
     func specificFeature1Method()
  }

 protocol SpecificFeature2Protocol : CommonFeatureProtocol {
      func specificFeature2Method()
 }

struct specificFeature1 : SpecificFeature1Protocol { }
struct specificFeature2 : SpecificFeature2Protocol { }
</code>```

Now in one of my other class (UtilFeature), Will it be possible to use feature object and specific feature methods like -

```<code>UtilFeature.feature.specificFeature1Method()
UtilFeature.feature.specificFeature2Method()
</code>```

Something like (in UtilFeature) -

```<code>var feature : CommonFeatureProtocol {
    return specificFeature1() //or specificFeature2()
}
</code>```

答:
What you are trying to achieve seems not possible as the feature is of type CommonFeatureProtocol and it does not include the method. So it's not possible to access with object(dot) method.

POSSIBLE:

```<code>var feature : SpecificFeature1Protocol {
    return specificFeature1()
}

feature.specificFeature1Method()
</code>```

Or(Not preferred way of doing)

```<code>var newFeature : CommonFeatureProtocol {
    return specificFeature1()
}

(newFeature as SpecificFeature1Protocol).specificFeature1Method()
</code>```

Got the point what you want to do is,

You need to make a composition of two protocols.

Syntax: var composition: [Protocol1 & Protocol2]

Also, you can use typealias to make it more readable.

So, In your case:

```<code>typealias SpecificFeatureProtocol = SpecificFeature1Protocol & SpecificFeature2Protocol

var feature: SpecificFeatureProtocol? {
    return nil
}
</code>```

Now, you can use the methods like below:

```<code>feature?.specificFeature1Method()
feature?.specificFeature2Method()
</code>```

Body:
Trying with here is my setup:

protocol CommonFeatureProtocol { }
extension CommonFeatureProtocol { }

 protocol SpecificFeature1Protocol : CommonFeatureProtocol {
     func specificFeature1Method()
  }

 protocol SpecificFeature2Protocol : CommonFeatureProtocol {
      func specificFeature2Method()
 }

struct specificFeature1 : SpecificFeature1Protocol { }
struct specificFeature2 : SpecificFeature2Protocol { }

Now in one of my other class (UtilFeature), Will it be possible to use feature object and specific feature methods like -

UtilFeature.feature.specificFeature1Method()
UtilFeature.feature.specificFeature2Method()

Something like (in UtilFeature) -

var feature : CommonFeatureProtocol {
    return specificFeature1() //or specificFeature2()
}

Body:
What you are trying to achieve seems not possible as the feature is of type CommonFeatureProtocol and it does not include the method. So it's not possible to access with object(dot) method.

POSSIBLE:

var feature : SpecificFeature1Protocol {
    return specificFeature1()
}

feature.specificFeature1Method()

Or(Not preferred way of doing)

var newFeature : CommonFeatureProtocol {
    return specificFeature1()
}

(newFeature as SpecificFeature1Protocol).specificFeature1Method()

Got the point what you want to do is,

You need to make a composition of two protocols.

Syntax: var composition: [Protocol1 & Protocol2]

Also, you can use typealias to make it more readable.

So, In your case:

typealias SpecificFeatureProtocol = SpecificFeature1Protocol & SpecificFeature2Protocol

var feature: SpecificFeatureProtocol? {
    return nil
}

Now, you can use the methods like below:

feature?.specificFeature1Method()
feature?.specificFeature2Method()


问:
Enum error while doing check
I have an enum like this

```<code> public enum ConnectionState : int
   {
      Unknown = 1,
      Connected = 2,
      Disconnected = 3,
   }
</code>```

I need to display value if it is connected i did this check

```<code>if(ConnectionState.Connected)
{
SubItems.Add(Data.value)
}
</code>```

But i am getting an error "Cannot implicitly convert type 'ConnectionState' to 'bool'".kindly suggest me how to proceed with this

答:
ConnectionState in this example is a type definition, you need to instantiate a ConnectionState object:

```<code>ConnectionState myState = new ConnectionState();
</code>```

Then you can set your state:

```<code>myState = ConnectionState.Connected;
</code>```

And check it with:

```<code>if(myState == ConnectionState.Connected)
</code>```

Title: Enum error while doing check

Body:
I have an enum like this

 public enum ConnectionState : int
   {
      Unknown = 1,
      Connected = 2,
      Disconnected = 3,
   }

I need to display value if it is connected i did this check

if(ConnectionState.Connected)
{
SubItems.Add(Data.value)
}

But i am getting an error "Cannot implicitly convert type 'ConnectionState' to 'bool'".kindly suggest me how to proceed with this

Body:
ConnectionState in this example is a type definition, you need to instantiate a ConnectionState object:

ConnectionState myState = new ConnectionState();

Then you can set your state:

myState = ConnectionState.Connected;

And check it with:

if(myState == ConnectionState.Connected)


问:
How should I reformat my data for sklearn.naive_bayes.GaussianNB
I have a dataset users. Each user has gender and color property (favorite color), and so on. I divided each color and sum of users of one gender which like this color to one list:

```<code>features_train = [['indigo', 2341], ['yellow', 856], ['lavender', 690], ['yellowgreen', 1208], ['indigo', 565], ['yellow', 103], ['lavender', 571], ['yellowgreen', 234] ...]
</code>```

In the second list for each element from the first list I say which gender represent this element:

```<code>labels_train = [0, 0, 0, 0, 1, 1, 1, 1, ...]
</code>```

And now I have the third list with colors: features_test = ['yellow', 'red', ...], and I need to predict a gender.

I have to use naive_bayes.GaussianNB function from sklearn and I will have more properties for users, but to explain my problem I use just color and gender. So, I found an official example but I can't understand how should I reformat my datasets to work with them. Should I convert my color to some number representation like: [[0, 2341], [1, 856]] or maybe I should use some another function from sklearn to do that?

```<code>import numpy as np
from sklearn.naive_bayes import GaussianNB
clf = GaussianNB()
clf.fit(features_train, labels_train)
print(clf.predict(features_test))
</code>```

答:
In order to perform 'machine learning' on text documents with scikit-learn, you first need to turn the text content into numerical feature vectors.

The most intuitive way to do so is the bags of words representation - you can solve that by indeed reformatting your dataset like you have mentioned.

Given that your 'X' and 'y's are both 1-D I would recommend to convert your text classes into a set of numerical feature vectors by using the LabelEnconder in scikit-learn.

See below:

```<code>import numpy as np
from sklearn import preprocessing
from sklearn.naive_bayes import GaussianNB

clf = GaussianNB()
le = preprocessing.LabelEncoder()

#Fit label encoder and return encoded features
features_train_num = le.fit_transform(features_train)
features_test_num  = le.transform(features_test)

#Fit label encoder and return encoded labels
labels_train_num   = le.fit_transform(labels_train)
labels_test_num    = le.transform(labels_test)

clf.fit(features_train_num, labels_train_num)
print(clf.predict(features_test_num))
</code>```

Body:
I have a dataset users. Each user has gender and color property (favorite color), and so on. I divided each color and sum of users of one gender which like this color to one list:

features_train = [['indigo', 2341], ['yellow', 856], ['lavender', 690], ['yellowgreen', 1208], ['indigo', 565], ['yellow', 103], ['lavender', 571], ['yellowgreen', 234] ...]

In the second list for each element from the first list I say which gender represent this element:

labels_train = [0, 0, 0, 0, 1, 1, 1, 1, ...]

And now I have the third list with colors: features_test = ['yellow', 'red', ...], and I need to predict a gender.

I have to use naive_bayes.GaussianNB function from sklearn and I will have more properties for users, but to explain my problem I use just color and gender. So, I found an official example but I can't understand how should I reformat my datasets to work with them. Should I convert my color to some number representation like: [[0, 2341], [1, 856]] or maybe I should use some another function from sklearn to do that?

import numpy as np
from sklearn.naive_bayes import GaussianNB
clf = GaussianNB()
clf.fit(features_train, labels_train)
print(clf.predict(features_test))

Body:
In order to perform 'machine learning' on text documents with scikit-learn, you first need to turn the text content into numerical feature vectors.

The most intuitive way to do so is the bags of words representation - you can solve that by indeed reformatting your dataset like you have mentioned.

Given that your 'X' and 'y's are both 1-D I would recommend to convert your text classes into a set of numerical feature vectors by using the LabelEnconder in scikit-learn.

See below:

import numpy as np
from sklearn import preprocessing
from sklearn.naive_bayes import GaussianNB

clf = GaussianNB()
le = preprocessing.LabelEncoder()

#Fit label encoder and return encoded features
features_train_num = le.fit_transform(features_train)
features_test_num  = le.transform(features_test)

#Fit label encoder and return encoded labels
labels_train_num   = le.fit_transform(labels_train)
labels_test_num    = le.transform(labels_test)

clf.fit(features_train_num, labels_train_num)
print(clf.predict(features_test_num))


问:
Adding and extracting a certificate string in yml file
I have a standard .crt string I'd like to add as a string in a YAML configuration file and I want to be able to extract it from there with its structure intact using Python. What happens now is it's being extracted flat and without line breaks I have there.

crt file example:

```<code>    -----BEGIN CERTIFICATE-----
MIIGOTCCBCGgAwIBAgIJAOE/vJd8EB24MA0GCSqGSIb3DQEBBQUAMIGyMQswCQYD
VQQGEwJGUjEPMA0GA1UECAwGQWxzYWNlMRMwEQYDVQQHDApTdHJhc2JvdXJnMRgw
FgYDVQQKDA93d3cuZnJlZWxhbi5vcmcxEDAOBgNVBAsMB2ZyZWVsYW4xLTArBgNV
BAMMJEZyZWVsYW4gU2FtcGxlIENlcnRpZmljYXRlIEF1dGhvcml0eTEiMCAGCSqG
SIb3DQEJARYTY29udGFjdEBmcmVlbGFuLm9yZzAeFw0xMjA0MjcxMDE3NDRaFw0x
MjA1MjcxMDE3NDRaMIGyMQswCQYDVQQGEwJGUjEPMA0GA1UECAwGQWxzYWNlMRMw
EQYDVQQHDApTdHJhc2JvdXJnMRgwFgYDVQQKDA93d3cuZnJlZWxhbi5vcmcxEDAO
BgNVBAsMB2ZyZWVsYW4xLTArBgNVBAMMJEZyZWVsYW4gU2FtcGxlIENlcnRpZmlj
YXRlIEF1dGhvcml0eTEiMCAGCSqGSIb3DQEJARYTY29udGFjdEBmcmVlbGFuLm9y
ZzCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAODp+8oQcK+MTuWPZVxJ
ZR75paK4zcUngupYXWSGWFXPTV7vssFk6vInePArTL+T9KwHfiZ29Pp3UbzDlysY
Kz9f9Ae50jGD6xVPwXgQ/VI979GyFXzhiEMtSYykF04tBJiDl2/FZxbHPpNxC39t
14kwuDqBin9N/ZbT5+45tbbS8ziXS+QgL5hD2q2eYCWayrGEt1Y+jDAdHDHmGnZ8
d4hbgILJAs3IInOCDjC4c1gwHFb8G4QHHTwVhjhqpkq2hQHgzWBC1l2Dku/oDYev
Zu/pfpTo3z6+NOYBrUWseQmIuG+DGMQA9KOuSQveyTywBm4G4vZKn0sCu1/v2+9T
BGv41tgS/Yf6oeeQVrbS4RFY1r9qTK6DW9wkTTesa4xoDKQrWjSJ7+aa8tvBXLGX
x2xdRNWLeRMuGBSOihwXmDr+rCJRauT7pItN5X+uWNTX1ofNksQSUMaFJ5K7L0LU
iQqU2Yyt/8UphdVZL4EFkGSA13UDWtb9mM1hY0h65LlSYwCchEphrtI9cuV+ITrS
NcN6cP/dqDx1/jWd6dqjNu7+dugwX5elQS9uUYCFmugR5s1m2eeBg3QuC7gZLE0N
NbgS7oSxKJe9KeOcw68jHWfBKsCfBfQ4fU2t/ntMybT3hCdEMQu4dgM5Tyw/UeFq
0SaJyTl+G1bTzS0FW6uUp6NLAgMBAAGjUDBOMB0GA1UdDgQWBBQjbC09PildeLhs
Pqriuy4ebIfyUzAfBgNVHSMEGDAWgBQjbC09PildeLhsPqriuy4ebIfyUzAMBgNV
HRMEBTADAQH/MA0GCSqGSIb3DQEBBQUAA4ICAQCwRJpJCgp7S+k9BT6X3kBefonE
EOYtyWXBPpuyG3Qlm1rdhc66DCGForDmTxjMmHYtNmAVnM37ILW7MoflWrAkaY19
gv88Fzwa5e6rWK4fTSpiEOc5WB2A3HPN9wJnhQXt1WWMDD7jJSLxLIwFqkzpDbDE
9122TtnIbmKNv0UQpzPV3Ygbqojy6eZHUOT05NaOT7vviv5QwMAH5WeRfiCys8CG
Sno/o830OniEHvePTYswLlX22LyfSHeoTQCCI8pocytl7IwARKCvBgeFqvPrMiqP
ch16FiU9II8KaMgpebrUSz3J1BApOOd1LBd42BeTAkNSxjRvbh8/lDWfnE7ODbKc
b6Ad3V9flFb5OBZH4aTi6QfrDnBmbLgLL8o/MLM+d3Kg94XRU9LjC2rjivQ6MC53
EnWNobcJFY+soXsJokGtFxKgIx8XrhF5GOsT2f1pmMlYL4cjlU0uWkPOOkhq8tIp
R8cBYphzXu1v6h2AaZLRq184e30ZO98omKyQoQ2KAm5AZayRrZZtjvEZPNamSuVQ
iPe3o/4tyQGq+jEMAEjLlDECu0dEa6RFntcbBPMBP3wZwE2bI9GYgvyaZd63DNdm
Xd65m0mmfOWYttfrDT3Q95YP54nHpIxKBw1eFOzrnXOqbKVmJ/1FDP2yWeooKVLf
KvbxUcDaVvXB0EU0bg==
-----END CERTIFICATE-----
</code>```

答:
When you edit your cfg file, assuming you put it after key crt make sure you specify a literal block style scalar using |2

```<code>crt: |2
      -----BEGIN CERTIFICATE-----
  MIIGOTCCBCGgAwIBAgIJAOE/vJd8EB24MA0GCSqGSIb3DQEBBQUAMIGyMQswCQYD
  VQQGEwJGUjEPMA0GA1UECAwGQWxzYWNlMRMwEQYDVQQHDApTdHJhc2JvdXJnMRgw
  FgYDVQQKDA93d3cuZnJlZWxhbi5vcmcxEDAOBgNVBAsMB2ZyZWVsYW4xLTArBgNV
  BAMMJEZyZWVsYW4gU2FtcGxlIENlcnRpZmljYXRlIEF1dGhvcml0eTEiMCAGCSqG
  SIb3DQEJARYTY29udGFjdEBmcmVlbGFuLm9yZzAeFw0xMjA0MjcxMDE3NDRaFw0x
  ....
</code>```

The 2 is necessary as your first line starts with spaces (you can of course indent the body with any positive number, as long as you specify the right amount after |).

Without the | your scalar is interpreted as a multi-line plain scalar and on loading newlines in those will be replaced by spaces

The above should be preserved when doing a round_trip_load() and round_trip_dump()

Body:
I have a standard .crt string I'd like to add as a string in a YAML configuration file and I want to be able to extract it from there with its structure intact using Python. What happens now is it's being extracted flat and without line breaks I have there.

crt file example:

    -----BEGIN CERTIFICATE-----
MIIGOTCCBCGgAwIBAgIJAOE/vJd8EB24MA0GCSqGSIb3DQEBBQUAMIGyMQswCQYD
VQQGEwJGUjEPMA0GA1UECAwGQWxzYWNlMRMwEQYDVQQHDApTdHJhc2JvdXJnMRgw
FgYDVQQKDA93d3cuZnJlZWxhbi5vcmcxEDAOBgNVBAsMB2ZyZWVsYW4xLTArBgNV
BAMMJEZyZWVsYW4gU2FtcGxlIENlcnRpZmljYXRlIEF1dGhvcml0eTEiMCAGCSqG
SIb3DQEJARYTY29udGFjdEBmcmVlbGFuLm9yZzAeFw0xMjA0MjcxMDE3NDRaFw0x
MjA1MjcxMDE3NDRaMIGyMQswCQYDVQQGEwJGUjEPMA0GA1UECAwGQWxzYWNlMRMw
EQYDVQQHDApTdHJhc2JvdXJnMRgwFgYDVQQKDA93d3cuZnJlZWxhbi5vcmcxEDAO
BgNVBAsMB2ZyZWVsYW4xLTArBgNVBAMMJEZyZWVsYW4gU2FtcGxlIENlcnRpZmlj
YXRlIEF1dGhvcml0eTEiMCAGCSqGSIb3DQEJARYTY29udGFjdEBmcmVlbGFuLm9y
ZzCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAODp+8oQcK+MTuWPZVxJ
ZR75paK4zcUngupYXWSGWFXPTV7vssFk6vInePArTL+T9KwHfiZ29Pp3UbzDlysY
Kz9f9Ae50jGD6xVPwXgQ/VI979GyFXzhiEMtSYykF04tBJiDl2/FZxbHPpNxC39t
14kwuDqBin9N/ZbT5+45tbbS8ziXS+QgL5hD2q2eYCWayrGEt1Y+jDAdHDHmGnZ8
d4hbgILJAs3IInOCDjC4c1gwHFb8G4QHHTwVhjhqpkq2hQHgzWBC1l2Dku/oDYev
Zu/pfpTo3z6+NOYBrUWseQmIuG+DGMQA9KOuSQveyTywBm4G4vZKn0sCu1/v2+9T
BGv41tgS/Yf6oeeQVrbS4RFY1r9qTK6DW9wkTTesa4xoDKQrWjSJ7+aa8tvBXLGX
x2xdRNWLeRMuGBSOihwXmDr+rCJRauT7pItN5X+uWNTX1ofNksQSUMaFJ5K7L0LU
iQqU2Yyt/8UphdVZL4EFkGSA13UDWtb9mM1hY0h65LlSYwCchEphrtI9cuV+ITrS
NcN6cP/dqDx1/jWd6dqjNu7+dugwX5elQS9uUYCFmugR5s1m2eeBg3QuC7gZLE0N
NbgS7oSxKJe9KeOcw68jHWfBKsCfBfQ4fU2t/ntMybT3hCdEMQu4dgM5Tyw/UeFq
0SaJyTl+G1bTzS0FW6uUp6NLAgMBAAGjUDBOMB0GA1UdDgQWBBQjbC09PildeLhs
Pqriuy4ebIfyUzAfBgNVHSMEGDAWgBQjbC09PildeLhsPqriuy4ebIfyUzAMBgNV
HRMEBTADAQH/MA0GCSqGSIb3DQEBBQUAA4ICAQCwRJpJCgp7S+k9BT6X3kBefonE
EOYtyWXBPpuyG3Qlm1rdhc66DCGForDmTxjMmHYtNmAVnM37ILW7MoflWrAkaY19
gv88Fzwa5e6rWK4fTSpiEOc5WB2A3HPN9wJnhQXt1WWMDD7jJSLxLIwFqkzpDbDE
9122TtnIbmKNv0UQpzPV3Ygbqojy6eZHUOT05NaOT7vviv5QwMAH5WeRfiCys8CG
Sno/o830OniEHvePTYswLlX22LyfSHeoTQCCI8pocytl7IwARKCvBgeFqvPrMiqP
ch16FiU9II8KaMgpebrUSz3J1BApOOd1LBd42BeTAkNSxjRvbh8/lDWfnE7ODbKc
b6Ad3V9flFb5OBZH4aTi6QfrDnBmbLgLL8o/MLM+d3Kg94XRU9LjC2rjivQ6MC53
EnWNobcJFY+soXsJokGtFxKgIx8XrhF5GOsT2f1pmMlYL4cjlU0uWkPOOkhq8tIp
R8cBYphzXu1v6h2AaZLRq184e30ZO98omKyQoQ2KAm5AZayRrZZtjvEZPNamSuVQ
iPe3o/4tyQGq+jEMAEjLlDECu0dEa6RFntcbBPMBP3wZwE2bI9GYgvyaZd63DNdm
Xd65m0mmfOWYttfrDT3Q95YP54nHpIxKBw1eFOzrnXOqbKVmJ/1FDP2yWeooKVLf
KvbxUcDaVvXB0EU0bg==
-----END CERTIFICATE-----

Body:
When you edit your cfg file, assuming you put it after key crt make sure you specify a literal block style scalar using |2

crt: |2
      -----BEGIN CERTIFICATE-----
  MIIGOTCCBCGgAwIBAgIJAOE/vJd8EB24MA0GCSqGSIb3DQEBBQUAMIGyMQswCQYD
  VQQGEwJGUjEPMA0GA1UECAwGQWxzYWNlMRMwEQYDVQQHDApTdHJhc2JvdXJnMRgw
  FgYDVQQKDA93d3cuZnJlZWxhbi5vcmcxEDAOBgNVBAsMB2ZyZWVsYW4xLTArBgNV
  BAMMJEZyZWVsYW4gU2FtcGxlIENlcnRpZmljYXRlIEF1dGhvcml0eTEiMCAGCSqG
  SIb3DQEJARYTY29udGFjdEBmcmVlbGFuLm9yZzAeFw0xMjA0MjcxMDE3NDRaFw0x
  ....

The 2 is necessary as your first line starts with spaces (you can of course indent the body with any positive number, as long as you specify the right amount after |).

Without the | your scalar is interpreted as a multi-line plain scalar and on loading newlines in those will be replaced by spaces

The above should be preserved when doing a round_trip_load() and round_trip_dump()


问:
how do i locate files in wordpress by inspecting element a particular element in google chrome?
I want to change some particular line on my Wordpress site which I cannot change in the customization. How do I locate a certain line with inspect element in chrome?

My website is www.Artiana.io and I want to edit this line:

"
Learn more
"```

Please, can anyone help me out?

答:
Let me show you how you can use WordPress's hints in html body class to find the php file:

WordPress gives hint in the HTML's body tag that which particular template was used to display this page.

In your case we have following classes in the body tag:

```<code><body class="home page-template page-template-page-templates page-template-page_front-page page-template-page-templatespage_front-page-php page page-id-466 custom-background wp-custom-logo blog-post">
</code>```

Now there is a specific class which ends with php, which tells that template was used by your theme to build this page. i.e. page-template-page-templatespage_front-page-php

Now it could mean that in your theme folder:

/wp-content/themes/hestia/

There could be sub folder or folders called: **page-template/page-templates** and inside it is page_front-page.php PHP file, which is being used to create this layout. See if you can locate the code you are trying to modify there.

Body:
I want to change some particular line on my Wordpress site which I cannot change in the customization. How do I locate a certain line with inspect element in chrome?

My website is www.Artiana.io and I want to edit this line:

"
Learn more
"

Please, can anyone help me out?

Body:
Let me show you how you can use WordPress's hints in html body class to find the php file:

WordPress gives hint in the HTML's body tag that which particular template was used to display this page.

In your case we have following classes in the body tag:

<body class="home page-template page-template-page-templates page-template-page_front-page page-template-page-templatespage_front-page-php page page-id-466 custom-background wp-custom-logo blog-post">

Now there is a specific class which ends with php, which tells that template was used by your theme to build this page. i.e. page-template-page-templatespage_front-page-php

Now it could mean that in your theme folder:

/wp-content/themes/hestia/

There could be sub folder or folders called: **page-template/page-templates** and inside it is page_front-page.php PHP file, which is being used to create this layout. See if you can locate the code you are trying to modify there.


问:
firebase authentication with facebook
I tried my level best before asking here.

I am trying to implement facebook authentication with ngcordova auth by following this post link

I am using Firebase Firebase v3.6.4 and angularfire in ionic 1.

```<code>$cordovaOauth.facebook("222222222222", ["email"])
              .then(function (result) {
                var credentials = firebase.auth.FacebookAuthProvider.credential(result.access_token);
                ToastFac.showMsgToUser("Authentication failed:"+result.access_token);
                return firebase.auth().signInWithCredential(credentials);
              })
              .then(function (firebaseUser) {
                  ToastFac.showMsgToUser("Signed in as:"+ firebaseUser.uid);
                console.log("Signed in as:", firebaseUser.uid);
              })
              .catch(function (error) {
                  ToastFac.showMsgToUser("Authentication failed:"+ error);
                console.error("Authentication failed:", error);
              });
</code>```

while trying with above code , I got the facebook login screen and access token but ending up with below error while running in device & emulator.

I have added package name from config xml and SHA1 certificate by generating it from

```<code>keytool -exportcert -list -v -alias androiddebugkey -keystore "PATH\.android\debug.keystore"
</code>```

I am not sure what else I am missing. Could you please advise here.

答:
Finally, I got it after a lot of search.
We have to use the API key from Google console rather than what firebase gives. I didn't come across any official advice as such from Google or firebase.</p>

Title: firebase authentication with facebook

Body:
I tried my level best before asking here.

I am trying to implement facebook authentication with ngcordova auth by following this post link

I am using Firebase Firebase v3.6.4 and angularfire in ionic 1.

$cordovaOauth.facebook("222222222222", ["email"])
              .then(function (result) {
                var credentials = firebase.auth.FacebookAuthProvider.credential(result.access_token);
                ToastFac.showMsgToUser("Authentication failed:"+result.access_token);
                return firebase.auth().signInWithCredential(credentials);
              })
              .then(function (firebaseUser) {
                  ToastFac.showMsgToUser("Signed in as:"+ firebaseUser.uid);
                console.log("Signed in as:", firebaseUser.uid);
              })
              .catch(function (error) {
                  ToastFac.showMsgToUser("Authentication failed:"+ error);
                console.error("Authentication failed:", error);
              });

while trying with above code , I got the facebook login screen and access token but ending up with below error while running in device & emulator.

I have added package name from config xml and SHA1 certificate by generating it from

keytool -exportcert -list -v -alias androiddebugkey -keystore "PATH\.android\debug.keystore"

I am not sure what else I am missing. Could you please advise here.