问:
Optimizing Knockout / TKO - Alpha3
In the process of modernizing Knockout for version 4.0 (now live at the monorepo tko), I've hit some performance issues.

Among other changes, some inner-loop things have been converted to ES6 classes, and it's causing some major performance problems.  I'd rather not undo that effort as it adds quite a bit of clarity to some key code, so I'd like to solicit some input on how to improve the ES6 code.

I've set up some simple samples for profiling here:

Knockout Alpha2 - 349ms

Knockout Alpha3 (prerelease) - 622ms

The code in the jsFiddles is as follows, and it's prototypical of the slowdowns being experienced across a number of bindings.

HTML:

```<code><div id='x'>
  <strong>{{ count }} / {{ time }} ms</strong>
  <custom-component></custom-component>
</div>

<div id='cc-template'>
   cc
   {{# unless: finished }}
      <custom-component></custom-component>
   {{ /unless }}
</div>
</code>```

Javascript:

```<code>let count = ko.observable(0)
let time = ko.observable(false)
const start = performance.now()
const ITERATIONS = 1000

class viewModel {
  constructor () {
    this.finished = count() > ITERATIONS
    count(count() + 1)
    time(performance.now() - start)
  }
}

ko.components.register("custom-component", {
  viewModel, template: {element: 'cc-template'}
})

ko.applyBindings({count, time}, document.getElementById('x'))
</code>```

If you compare the Javascript profiles, the call trees are nearly identical (notwithstanding e.g. the ES6 changes).  It looks like the extra time in Alpha3 is at the leaf calls, making them harder to identify, so I speculate based on the profile comparisons that the problem is a few fold, including:

some non-optimizing or de-optimizing happening

some loops replaced with slower, native calls e.g. Array.from

more intermediate minor garbage collections

less native optimization for ES6isms

In any case I haven't rooted out which, if any of these, is the problem yet – or where exactly they might be occurring.

I would be most grateful for insights and help identifying where we can make optimizations to get the performance back up to, or even above, par.

答:
To consolidate any answers, I've started an answer as a wiki:

Remove inappropriate & unnecessary dependency chaining with template and if/ifnot/unless/with/else and foreach bindings — 3074AA9

Title: Optimizing Knockout / TKO - Alpha3

Body:
In the process of modernizing Knockout for version 4.0 (now live at the monorepo tko), I've hit some performance issues.

Among other changes, some inner-loop things have been converted to ES6 classes, and it's causing some major performance problems.  I'd rather not undo that effort as it adds quite a bit of clarity to some key code, so I'd like to solicit some input on how to improve the ES6 code.

I've set up some simple samples for profiling here:

Knockout Alpha2 - 349ms

Knockout Alpha3 (prerelease) - 622ms

The code in the jsFiddles is as follows, and it's prototypical of the slowdowns being experienced across a number of bindings.

HTML:

  {{ count }} / {{ time }} ms
  <custom-component></custom-component>

   cc
   {{# unless: finished }}
      <custom-component></custom-component>
   {{ /unless }}

Javascript:

let count = ko.observable(0)
let time = ko.observable(false)
const start = performance.now()
const ITERATIONS = 1000

class viewModel {
  constructor () {
    this.finished = count() > ITERATIONS
    count(count() + 1)
    time(performance.now() - start)
  }
}

ko.components.register("custom-component", {
  viewModel, template: {element: 'cc-template'}
})

ko.applyBindings({count, time}, document.getElementById('x'))

If you compare the Javascript profiles, the call trees are nearly identical (notwithstanding e.g. the ES6 changes).  It looks like the extra time in Alpha3 is at the leaf calls, making them harder to identify, so I speculate based on the profile comparisons that the problem is a few fold, including:

some non-optimizing or de-optimizing happening

some loops replaced with slower, native calls e.g. Array.from

more intermediate minor garbage collections

less native optimization for ES6isms

In any case I haven't rooted out which, if any of these, is the problem yet – or where exactly they might be occurring.

I would be most grateful for insights and help identifying where we can make optimizations to get the performance back up to, or even above, par.


来源: stackexchange

问:
How to send e-mail through VBA without Outlook
I'm trying to send email through SMTP in VBA, but is returning error.

```<code>Dim CDOmsg As CDO.Message
Set CDOmsg = New CDO.Message

With CDOmsg.Configuration.Fields
    .Item("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = True
    .Item("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1
    .Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "smtp.gmail.com"
    .Item("http://schemas.microsoft.com/cdo/configuration/sendusername") = "myemail@gmail.com"
    .Item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "mypass"
    .Item("http://schemas.microsoft.com/cdo/configuration/smptserverport") = 465
    .Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2 'NTLM method
    .Item("http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout") = 60
    .Update
End With
' build email parts
With CDOmsg
    .Subject = "the email subject"
    .From = "myemail@gmail.com"
    .To = "mailto@gmail.com"
    .CC = ""
    .BCC = ""
    .TextBody = "the full message body goes here. you may want to create a variable to hold the text"
End With
CDOmsg.Send
Set CDOmsg = Nothing
</code>```

The error is on CDOmsg.Send. I've tried to send with Gmail and Yahoo Mail, but I get this same error.

Error code: -2147220973(80040213)

Error description: The transport failed to connect to the server

答:
You can try the following but don't forget to tick the checkbox for 'Microsoft CDO for Windows 2000 Library' </p>

```<code>Function email(ByVal sender_email As String, _
            ByVal email_message As String, _
            ByVal email_message2 As String, _
            ByVal reply_address As String, _
            ByVal sender_name As String)

    Dim Mail As New Message

    Dim Cfg As Configuration

    Set Cfg = Mail.Configuration

    'SETUP MAIL CONFIGURATION FIELDS
    Cfg(cdoSendUsingMethod) = cdoSendUsingPort
    Cfg(cdoSMTPServer) = 'SMTP
    Cfg(cdoSMTPServerPort) = 'SMTPport
    Cfg(cdoSMTPAuthenticate) = cdoBasic
    Cfg(cdoSMTPUseSSL) = True
    Cfg(cdoSendUserName) = 'sender_email
    Cfg(cdoSendPassword) = 'password
    Cfg.Fields.Update

    'SEND EMAIL
    With Mail
        .From = 'sender_name & sender_email
        .ReplyTo = 'reply_address
        .To = 'receiver
        .CC = 'carbonCopy
        .BCC = 'blindCopy
        .Subject = 'SubjectLine
        .HTMLBody = 'email_message & email_message2
        .Attachments.Add attFilePath
        .Send
    End With
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to send email through SMTP in VBA, but is returning error.

Dim CDOmsg As CDO.Message
Set CDOmsg = New CDO.Message

With CDOmsg.Configuration.Fields
    .Item("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = True
    .Item("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1
    .Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "smtp.gmail.com"
    .Item("http://schemas.microsoft.com/cdo/configuration/sendusername") = "myemail@gmail.com"
    .Item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "mypass"
    .Item("http://schemas.microsoft.com/cdo/configuration/smptserverport") = 465
    .Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2 'NTLM method
    .Item("http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout") = 60
    .Update
End With
' build email parts
With CDOmsg
    .Subject = "the email subject"
    .From = "myemail@gmail.com"
    .To = "mailto@gmail.com"
    .CC = ""
    .BCC = ""
    .TextBody = "the full message body goes here. you may want to create a variable to hold the text"
End With
CDOmsg.Send
Set CDOmsg = Nothing

The error is on CDOmsg.Send. I've tried to send with Gmail and Yahoo Mail, but I get this same error.

Error code: -2147220973(80040213)

Error description: The transport failed to connect to the server

Body:
You can try the following but don't forget to tick the checkbox for 'Microsoft CDO for Windows 2000 Library'

Function email(ByVal sender_email As String, _
            ByVal email_message As String, _
            ByVal email_message2 As String, _
            ByVal reply_address As String, _
            ByVal sender_name As String)

    Dim Mail As New Message

    Dim Cfg As Configuration

    Set Cfg = Mail.Configuration

    'SETUP MAIL CONFIGURATION FIELDS
    Cfg(cdoSendUsingMethod) = cdoSendUsingPort
    Cfg(cdoSMTPServer) = 'SMTP
    Cfg(cdoSMTPServerPort) = 'SMTPport
    Cfg(cdoSMTPAuthenticate) = cdoBasic
    Cfg(cdoSMTPUseSSL) = True
    Cfg(cdoSendUserName) = 'sender_email
    Cfg(cdoSendPassword) = 'password
    Cfg.Fields.Update

    'SEND EMAIL
    With Mail
        .From = 'sender_name & sender_email
        .ReplyTo = 'reply_address
        .To = 'receiver
        .CC = 'carbonCopy
        .BCC = 'blindCopy
        .Subject = 'SubjectLine
        .HTMLBody = 'email_message & email_message2
        .Attachments.Add attFilePath
        .Send
    End With


问:
sp_MSForeachdb inserting into declared virtual table issue
I am having issues getting information to insert into the @TBL2 Table. </p>

<p>what am i doing wrong? </p>

```<code>DECLARE @command varchar(1000)
DECLARE @SQLStatment varchar(1000)

DECLARE @TBL2 table (
                    Database_Name nvarchar(max),
                    SI_SITE nvarchar(max),
                    SI_DB_USER nvarchar(max)
                    )

SELECT @command = 'IF ''?'' NOT IN(''master'', ''model'', ''msdb'', ''tempdb'') BEGIN USE ? insert into @tbl2  EXEC('+ @SQLStatment +') END'

set @SQLStatment =  'select top 1 Db_Name() as Database_Name, SI_SITE, SI_DB_USER from t_site'

EXEC master.. sp_MSForeachdb @command

select * from @TBL2
</code>```

答:
Try This:
There are several issues with the approach you are taking:

I don't think the "USE" statement can be dynamic (could be wrong)

The SQL is declared after you are trying to use it.

sp_msforeachdb is undocumented and shouldn't be relied on, even though it can work in many circumstances.

My approach uses the sys.databases and string concatenation to generate the appropriate SQL string to get the data you want from each table in all databases except the system databases, then executes the results into a temp table. The approach also assumes dbo schema. Adjust if necessary.

```<code>declare @SQL nvarchar(max)
set @SQL = ''

Create Table #TBL2 (
                    Database_Name nvarchar(max),
                    SI_SITE nvarchar(max),
                    SI_DB_USER nvarchar(max)
                    )

Select @SQL = @SQL + 'INSERT INTO #TBL2 (Database_Name, SI_SITE, SI_DB_USER) select top 1 ''' + name + ''' as Database_Name, SI_SITE, SI_DB_USER from ' + name + '..t_site;' + char(13)
From sys.databases
Where name not in ('master', 'model', 'msdb', 'tempdb')

print @SQL
exec sp_executesql @SQL

Select * From #TBL2

drop table #TBL2
</code>```

Body:
I am having issues getting information to insert into the @TBL2 Table.

what am i doing wrong?

DECLARE @command varchar(1000)
DECLARE @SQLStatment varchar(1000)

DECLARE @TBL2 table (
                    Database_Name nvarchar(max),
                    SI_SITE nvarchar(max),
                    SI_DB_USER nvarchar(max)
                    )

SELECT @command = 'IF ''?'' NOT IN(''master'', ''model'', ''msdb'', ''tempdb'') BEGIN USE ? insert into @tbl2  EXEC('+ @SQLStatment +') END'

set @SQLStatment =  'select top 1 Db_Name() as Database_Name, SI_SITE, SI_DB_USER from t_site'

EXEC master.. sp_MSForeachdb @command

select * from @TBL2

Body:
Try This:
There are several issues with the approach you are taking:

I don't think the "USE" statement can be dynamic (could be wrong)

The SQL is declared after you are trying to use it.

sp_msforeachdb is undocumented and shouldn't be relied on, even though it can work in many circumstances.

My approach uses the sys.databases and string concatenation to generate the appropriate SQL string to get the data you want from each table in all databases except the system databases, then executes the results into a temp table. The approach also assumes dbo schema. Adjust if necessary.

declare @SQL nvarchar(max)
set @SQL = ''

Create Table #TBL2 (
                    Database_Name nvarchar(max),
                    SI_SITE nvarchar(max),
                    SI_DB_USER nvarchar(max)
                    )

Select @SQL = @SQL + 'INSERT INTO #TBL2 (Database_Name, SI_SITE, SI_DB_USER) select top 1 ''' + name + ''' as Database_Name, SI_SITE, SI_DB_USER from ' + name + '..t_site;' + char(13)
From sys.databases
Where name not in ('master', 'model', 'msdb', 'tempdb')

print @SQL
exec sp_executesql @SQL

Select * From #TBL2

drop table #TBL2


问:
Convert string to multiline/raw string in LUA
Is there a way to convert a quoted string to a multiline string?

Something like "This string \66 here" to [[This string \66 here]] since I would like to ignore the interpretation of escaped characters.

答:
Lua 5.3 Reference Manual 3.1: Lexical Conventions

Literal strings can also be defined using a long format enclosed by
  long brackets. We define an opening long bracket of level n as an
  opening square bracket followed by n equal signs followed by another
  opening square bracket. So, an opening long bracket of level 0 is
  written as [[, an opening long bracket of level 1 is written as [=[,
  and so on. A closing long bracket is defined similarly; for instance,
  a closing long bracket of level 4 is written as ]====]. A long literal
  starts with an opening long bracket of any level and ends at the first
  closing long bracket of the same level. It can contain any text except
  a closing bracket of the same level. Literals in this bracketed form
  can run for several lines, do not interpret any escape sequences, and
  ignore long brackets of any other level. Any kind of end-of-line
  sequence (carriage return, newline, carriage return followed by
  newline, or newline followed by carriage return) is converted to a
  simple newline.

For convenience, when the opening long bracket is immediately followed
  by a newline, the newline is not included in the string.

That's all you need to know about long strings.

It does not make much sense to convert a string that has been defined using quotes "some string" to a string like [[some string]] as both quotes and square brackets are not actually part of that string and the string itself is the same.
The only difference would be a leading newline which is ignored in square brackets or escape sequences which are not interpreted.

Quotes and square brackets are only part of the string if you have nested strings. In this case conversion also doesn't make much sense because you cannot nest strings with quotes like strings with brackets.

Maybe your whole approach is a bit off?


问:
What are the consequences of removing the header image in a WordPress theme?
I'm working on my first WordPress theme.

The client doesn't seem to want a header image on every page, so I was just going to remove the  tag for the header image, but I want to double check first, what kind of impact will that have?

For example, does it affect certain widgets?

答:
It all depends on how the theme was coded.  Generally it shouldn't have any effect but removing the  tag could shift some of the other elements.

Create a backup first and then try it.  if something goes wrong you can replace the backup.

ContentLicense: CC BY-SA 2.5


问:
How to create account linking?
I'd like to create AccountLinking to recognize users.

I tried with reference to the links below.

https://developers.google.com/actions/identity/account-linking

How to authenticate user with just a Google account on Actions on Google?

And then when i tried Accout Linking on the actions on Google simulator.

I got this result.

```<code>{
"response": "It looks like your Test account is not linked yet",
"audioResponse": "//NExAARc...",
"debugInfo": {
    "sharedDebugInfo": [
        {
            "name": "Account Linking Url",
            "debugInfo": "https://assistant.google.com/services/auth/handoffs/auth/start?provider=my_project_name_dev&scopes=email+name&return_url=https://www.google.com/"
        }
    ]
}}
</code>```

And then I did a copy & paste that link into my browser.

But i got this result.

```<code>400. That’s an error.

Error: invalid_scope

Some requested scopes were invalid. {valid=
[https://www.googleapis.com/auth/userinfo.email], invalid=[name]}
</code>```

How can I fix it?

答:
The name scope isn't a valid scope. (And the https://www.googleapis.com/auth/userinfo.email scope is valid, but deprecated.)

See https://developers.google.com/identity/protocols/googlescopes#google_sign-in for the scopes you want, but probably profile and email are the ones you're looking for.

Title: How to create account linking?

Body:
I'd like to create AccountLinking to recognize users.

I tried with reference to the links below.

https://developers.google.com/actions/identity/account-linking

How to authenticate user with just a Google account on Actions on Google?

And then when i tried Accout Linking on the actions on Google simulator.

I got this result.

{
"response": "It looks like your Test account is not linked yet",
"audioResponse": "//NExAARc...",
"debugInfo": {
    "sharedDebugInfo": [
        {
            "name": "Account Linking Url",
            "debugInfo": "https://assistant.google.com/services/auth/handoffs/auth/start?provider=my_project_name_dev&scopes=email+name&return_url=https://www.google.com/"
        }
    ]
}}

And then I did a copy & paste that link into my browser.

But i got this result.

400. That’s an error.

Error: invalid_scope

Some requested scopes were invalid. {valid=
[https://www.googleapis.com/auth/userinfo.email], invalid=[name]}

How can I fix it?


问:
Unable to load a website in iFrame
I want to register for a course using the Sign-Up option and I want to load a website in an iFrame. The website specifies the X-Frame-Options = ALLOW

But when I click on the Sign-Up button, the website is redirected to its homepage and I am not able to load it in my iFrame.

Why am I not able to load the URL in my iFrame?

答: It 's not you not being able to load the site in the iframe. The site is loading in the iframe but the sign in action is set to the top window  as target, so when you submit the credentials it force the response to be loaded in the most top window.

Title: Unable to load a website in iFrame


问:
How to create wrapping with flexbox children
I want a grid to wrap when constrained by an outer node:

So the following should have two cells  one on top of each other, but it renders them side by side:

```<code><div style="display:flex; width:100px">
    <div style="flex: 1; width: 100px;">foo</div>
    <div style="flex: 1; width: 100px;">bar</div>
</div>
</code>```

How can I achieve my desired result?

答:
Setting the parent to flex-wrap will allow it to wrap, while using flex:0 1 auto, show for flex: [flex-grow] [flex-shrink] [flex-basis], will stop the child from shrinking onto one row. This is also the default for flex children.

foo

bar

foo

bar

foo

bar

```

Body:
I want a grid to wrap when constrained by an outer node:

So the following should have two cells  one on top of each other, but it renders them side by side:

foo

bar

How can I achieve my desired result?

Body:
Setting the parent to flex-wrap will allow it to wrap, while using flex:0 1 auto, show for flex: [flex-grow] [flex-shrink] [flex-basis], will stop the child from shrinking onto one row. This is also the default for flex children.

<div style="display:flex; width:100px; flex-wrap:wrap;">
    <div style="flex:0 1 auto; width: 100px;">foo</div>
    <div style="flex:0 1 auto; width: 100px;">bar</div>
</div>

<div style="display:flex; width:100px; flex-wrap:wrap;">
    <div style="flex:0 1 auto; width: 50px;">foo</div>
    <div style="flex:0 1 auto; width: 50px;">bar</div>
    <div style="flex:0 1 auto; width: 50px;">foo</div>
    <div style="flex:0 1 auto; width: 50px;">bar</div>
</div>


问:
How to get the stereotypes defined in mdg
We have MDG file .XML which is loaded to EA from the ad-din. Now the problem is how can we read all stereotype that are present in the MDG i.e .xml file loaded in ad-din.Is there any way we can check whether the particular stereotype is present in the particular MDG file.</p>

答: Seems like the API doesn't support getting information about UML profiles yet, and the Database does not contain that information, so you will have to scan the xml file directly.</p>


问:
bootstrap token field with auto complete with ajax not working on remote
```<code>Html code:
input type="text" class="form-control" id="tokenfield-typeahead" value="red,green,blue" />

script:
var engine = new Bloodhound({
  local: [{value: 'red'}, {value: 'blue'}, {value: 'green'} , {value: 'yellow'}, {value: 'violet'}, {value: 'brown'}, {value: 'purple'}, {value: 'black'}, {value: 'white'}],
  datumTokenizer: function(d) {
    return Bloodhound.tokenizers.whitespace(d.value);
  },
  queryTokenizer: Bloodhound.tokenizers.whitespace
});

engine.initialize();

$('#tokenfield-typeahead').tokenfield({
  typeahead: [null, { source: engine.ttAdapter() }]
});
</code>```

the above bootstrap token field is working in local, but while accessing using remote its not working..

答:
I came across the same issue and got the solution for the product am working on it..

I assume You should have those css and js files added into your view file

```<code>= stylesheet_link_tag 'sales_crm/tokenfield-typeahead.css'
= stylesheet_link_tag 'sales_crm/bootstrap-tokenfield.css'

%script{:src => "//code.jquery.com/ui/1.10.3/jquery-ui.js", :type => "text/javascript"}
= javascript_include_tag  "sales_crm/bootstrap-tokenfield.js"
= javascript_include_tag  "sales_crm/typeahead.bundle.min.js"
</code>```

View File :
Since i have used Haml, added the below line into the view file where you need to add the token field functionality

```<code>%input#tokenfield-typeahead.form-control.add_locality_data{:type => "text", :value => "", :identifier=> "Locality"}/
</code>```

Step 1: Initialize the BloodHound search engine

```<code>var engine = new Bloodhound({
                remote: {
                    url: '/sales_crm/leads/get_lead_associated_info?query=%QUERY&model_class='+$('.add_locality_data').attr("identifier"),
                    filter: function (response) {
                        var tagged_user = $('#tokenfield-typeahead').tokenfield('getTokens');
                        console.log(tagged_user)
                        return $.map(response.leads, function (user) {
                            console.log(user)
                            var exists = false;
        //                    console.log("velava saranam");
                            for (i=0; i < tagged_user.length; i++) {
                                if (user.value == tagged_user[i].value) {
                                    var exists = true;
                                }
                            }
                            if (!exists) {
                                return {
                                    value: user.value,
                                    label: user.label
                                };
                            }
                        });
                    }
                },
                datumTokenizer: function (d) {
                    return Bloodhound.tokenizers.whitespace(d.value);
                },
                queryTokenizer: Bloodhound.tokenizers.whitespace
            });

engine.initialize();
</code>```

Step 2: Then Initialize tokenfield function

```<code>$('#tokenfield-typeahead').tokenfield({
    delimiter: false,
    typeahead: [
           {
            name: 'users',
            displayKey: 'label',
            source: engine.ttAdapter()
        }
    ]
})
    .on('tokenfield:createtoken', function (e) {
        var existingTokens = $(this).tokenfield('getTokens');
        if (existingTokens.length) {
            $.each(existingTokens, function(index, token) {
                console.log(token)
                if (token.value === e.attrs.value) {
                    e.preventDefault();
                }else{
                    console.log(e.attrs.value)
                }
            });
        }else{
            console.log(e.attrs.value)
        }
    });
</code>```

Body:
Html code:
input type="text" class="form-control" id="tokenfield-typeahead" value="red,green,blue" />

script:
var engine = new Bloodhound({
  local: [{value: 'red'}, {value: 'blue'}, {value: 'green'} , {value: 'yellow'}, {value: 'violet'}, {value: 'brown'}, {value: 'purple'}, {value: 'black'}, {value: 'white'}],
  datumTokenizer: function(d) {
    return Bloodhound.tokenizers.whitespace(d.value);
  },
  queryTokenizer: Bloodhound.tokenizers.whitespace
});

engine.initialize();

$('#tokenfield-typeahead').tokenfield({
  typeahead: [null, { source: engine.ttAdapter() }]
});

the above bootstrap token field is working in local, but while accessing using remote its not working..

Body:
I came across the same issue and got the solution for the product am working on it..

I assume You should have those css and js files added into your view file

= stylesheet_link_tag 'sales_crm/tokenfield-typeahead.css'
= stylesheet_link_tag 'sales_crm/bootstrap-tokenfield.css'

%script{:src => "//code.jquery.com/ui/1.10.3/jquery-ui.js", :type => "text/javascript"}
= javascript_include_tag  "sales_crm/bootstrap-tokenfield.js"
= javascript_include_tag  "sales_crm/typeahead.bundle.min.js"

View File :
Since i have used Haml, added the below line into the view file where you need to add the token field functionality

%input#tokenfield-typeahead.form-control.add_locality_data{:type => "text", :value => "", :identifier=> "Locality"}/

Step 1: Initialize the BloodHound search engine

var engine = new Bloodhound({
                remote: {
                    url: '/sales_crm/leads/get_lead_associated_info?query=%QUERY&model_class='+$('.add_locality_data').attr("identifier"),
                    filter: function (response) {
                        var tagged_user = $('#tokenfield-typeahead').tokenfield('getTokens');
                        console.log(tagged_user)
                        return $.map(response.leads, function (user) {
                            console.log(user)
                            var exists = false;
        //                    console.log("velava saranam");
                            for (i=0; i < tagged_user.length; i++) {
                                if (user.value == tagged_user[i].value) {
                                    var exists = true;
                                }
                            }
                            if (!exists) {
                                return {
                                    value: user.value,
                                    label: user.label
                                };
                            }
                        });
                    }
                },
                datumTokenizer: function (d) {
                    return Bloodhound.tokenizers.whitespace(d.value);
                },
                queryTokenizer: Bloodhound.tokenizers.whitespace
            });

engine.initialize();

Step 2: Then Initialize tokenfield function

$('#tokenfield-typeahead').tokenfield({
    delimiter: false,
    typeahead: [
           {
            name: 'users',
            displayKey: 'label',
            source: engine.ttAdapter()
        }
    ]
})
    .on('tokenfield:createtoken', function (e) {
        var existingTokens = $(this).tokenfield('getTokens');
        if (existingTokens.length) {
            $.each(existingTokens, function(index, token) {
                console.log(token)
                if (token.value === e.attrs.value) {
                    e.preventDefault();
                }else{
                    console.log(e.attrs.value)
                }
            });
        }else{
            console.log(e.attrs.value)
        }
    });


问:
Angular bootstrap pagination force-ellipses
This plnkr I created shows the problem: http://plnkr.co/edit/YQAUCg5vjcgS1BEGB4nY?p=preview
shortly, I've got many pages and i set this attribute: force-ellipses = true to show the dots instead 200 pages. But doesn't work. I use angular bootstrap 2.3.1 and I think this is the problem. But I can't use another version so, is there any way to fix it?

```<code><pagination
    num-pages="noOfPages"
    current-page="currentPage"
    max-size="maxSize"
    boundary-link-numbers="true"
    rotate="true"
    force-ellipses="true">
</pagination>
</code>```

答:
Actually, implementation of uib-pagination is not correct. In the recent version, the syntax is

```<code><div uib-pagination total-items="total_items" max-size="maxSize" class="pagination-sm" boundary-link-numbers="true" rotate="false"></div>
</code>```

Check this plunker for implementation

Apart from this. I use dir-pagination i feel that more convenient and easy.

Check this angularUtils repo

and Plunker for dir-pagination

ContentLicense: CC BY-SA 4.0

Body:
This plnkr I created shows the problem: http://plnkr.co/edit/YQAUCg5vjcgS1BEGB4nY?p=preview
shortly, I've got many pages and i set this attribute: force-ellipses = true to show the dots instead 200 pages. But doesn't work. I use angular bootstrap 2.3.1 and I think this is the problem. But I can't use another version so, is there any way to fix it?

<pagination
    num-pages="noOfPages"
    current-page="currentPage"
    max-size="maxSize"
    boundary-link-numbers="true"
    rotate="true"
    force-ellipses="true">
</pagination>

Body:
Actually, implementation of uib-pagination is not correct. In the recent version, the syntax is

<div uib-pagination total-items="total_items" max-size="maxSize" class="pagination-sm" boundary-link-numbers="true" rotate="false"></div>

Check this plunker for implementation

Apart from this. I use dir-pagination i feel that more convenient and easy.

Check this angularUtils repo

and Plunker for dir-pagination


问:
How in graphql get last 3 element
How in graphql.js get last 3 created_at element from mysql db table?
I use sequelize.js

Like this:

```<code>query: '{
    elements(last:3){
        id
    }
}'
</code>```

This is my file db.js

```<code>const Conn = new Sequelize(/*connection config*/);
Conn.define('elements', {
    id: {
        type: Sequelize.STRING(36),
        primaryKey: true,
        allowNull: false
    }
});
export default Conn;
</code>```

This is my file schema.js

```<code>const Query = new GraphQLObjectType({
    name: 'Query',
    description: 'Root query object',
    fields() {
        return {
            elements: {
                type: new GraphQLList(Element),
                args: {
                    id: {
                        type: GraphQLString
                    }
                },
                resolve (root, args) {
                    return Db.models.elements.findAll({ where: args });
                }
            }
        }
    }
});
</code>```

答:
it must be like this;

```<code>...
return Db.models.elements.findAll({
  limit: 3,
  where: args,
  order: [['created_at', 'DESC']]
});
</code>```

http://docs.sequelizejs.com/manual/tutorial/querying.html#pagination-limiting
http://docs.sequelizejs.com/manual/tutorial/querying.html#ordering

Title: How in graphql get last 3 element

Body:
How in graphql.js get last 3 created_at element from mysql db table?
I use sequelize.js

Like this:

query: '{
    elements(last:3){
        id
    }
}'

This is my file db.js

const Conn = new Sequelize(/*connection config*/);
Conn.define('elements', {
    id: {
        type: Sequelize.STRING(36),
        primaryKey: true,
        allowNull: false
    }
});
export default Conn;

This is my file schema.js

const Query = new GraphQLObjectType({
    name: 'Query',
    description: 'Root query object',
    fields() {
        return {
            elements: {
                type: new GraphQLList(Element),
                args: {
                    id: {
                        type: GraphQLString
                    }
                },
                resolve (root, args) {
                    return Db.models.elements.findAll({ where: args });
                }
            }
        }
    }
});

Body:
it must be like this;

...
return Db.models.elements.findAll({
  limit: 3,
  where: args,
  order: [['created_at', 'DESC']]
});

http://docs.sequelizejs.com/manual/tutorial/querying.html#pagination-limiting
http://docs.sequelizejs.com/manual/tutorial/querying.html#ordering


问:
undefined method `first_name' for #<Profile id: nil>
Trace: https://i.gyazo.com/6487f4eee162e8c2207d7fdb5fc4ef3b.png
I can't get what's happening, I did the same process with the contact page and everything worked fine. Any ideas?

profile/new.html.erb

```<code><div class="row">
  <div class="col-md-6 col-md-offset-3">
    <h1 class="text-center">Create Your Profile</h1>
    <p class="text-center">Be a part of the DevMatch community and fill out your profile!</p>
    <div class="well">
      <%= render 'form' %>
    </div>
  </div>
</div>
</code>```

profile/_form.html.erb

```<code><%= form_for @profile, url: user_profile_path do |f| %>
  <div class="form-group">
    <%= f.label :first_name %>
    <%= f.text_field :first_name, class: 'form-control' %>
  </div>
  <div class="form-group">
    <%= f.label :last_name %>
    <%= f.text_field :last_name, class: 'form-control' %>
  </div>
  <div class="form-group">
    <%= f.label :job_title %>
    <%= f.select :job_title, ['Developer', 'Entrepreneur', 'Investor'], {}, class: 'form-control' %>
  </div>
  <div class="form-group">
    <%= f.label :phone_number %>
    <%= f.text_field :phone_number, class: 'form-control' %>
  </div>
  <div class="form-group">
    <%= f.label :contact_email %>
    <%= f.text_field :contact_email, class: 'form-control' %>
  </div>
  <div class="form-group">
    <%= f.label :description %>
    <%= f.text_area :description, class: 'form-control' %>
  </div>
  <div class="form-group">
    <%= f.submit "Update Profile", class: 'btn btn-primary' %>
  </div>
<% end %>
</code>```

schema

```<code>create_table "profiles", force: :cascade do |t|
    t.integer  "user_id"
    t.string   "first_name"
    t.string   "last_name"
    t.string   "job_title"
    t.string   "phone_number"
    t.string   "contact_email"
    t.text     "description"
    t.datetime "created_at",    null: false
    t.datetime "updated_at",    null: false
  end
</code>```

Profiles controller

```<code>class ProfilesController < ApplicationController
  # GET to /users/:user_id/profile/new
  def new
    # Render blank profile details form
    @profile = Profile.new
  end
end
</code>```

I get the rror in the profile creator page. It says the firstname is undefined but I tried deleting it and then it says that the laast name is undefined and so on

If I delete the "<%= render 'form' %>" form the other html, the page loads perfectly, but I need a form and I am trying to learn Ruby. Sorry

答:
undefined method `first_name' for Profile id: nil

It says the firstname is undefined but I tried deleting it and then it
  says that the last name is undefined and so on

You didn't have columns in the profiles table. You should run rake db:migrate to migrate the columns which should resolve your problem.

Additionally always make sure your migrations are run properly without any errors You check the status of the pending migrations with rake db:migrate:status

Body:
Trace: https://i.gyazo.com/6487f4eee162e8c2207d7fdb5fc4ef3b.png
I can't get what's happening, I did the same process with the contact page and everything worked fine. Any ideas?

profile/new.html.erb

Create Your Profile

Be a part of the DevMatch community and fill out your profile!

      <%= render 'form' %>

profile/_form.html.erb

<%= form_for @profile, url: user_profile_path do |f| %>

    <%= f.label :first_name %>
    <%= f.text_field :first_name, class: 'form-control' %>

    <%= f.label :last_name %>
    <%= f.text_field :last_name, class: 'form-control' %>

    <%= f.label :job_title %>
    <%= f.select :job_title, ['Developer', 'Entrepreneur', 'Investor'], {}, class: 'form-control' %>

    <%= f.label :phone_number %>
    <%= f.text_field :phone_number, class: 'form-control' %>

    <%= f.label :contact_email %>
    <%= f.text_field :contact_email, class: 'form-control' %>

    <%= f.label :description %>
    <%= f.text_area :description, class: 'form-control' %>

    <%= f.submit "Update Profile", class: 'btn btn-primary' %>

<% end %>

schema

create_table "profiles", force: :cascade do |t|
    t.integer  "user_id"
    t.string   "first_name"
    t.string   "last_name"
    t.string   "job_title"
    t.string   "phone_number"
    t.string   "contact_email"
    t.text     "description"
    t.datetime "created_at",    null: false
    t.datetime "updated_at",    null: false
  end

Profiles controller

class ProfilesController < ApplicationController
  # GET to /users/:user_id/profile/new
  def new
    # Render blank profile details form
    @profile = Profile.new
  end
end

I get the rror in the profile creator page. It says the firstname is undefined but I tried deleting it and then it says that the laast name is undefined and so on

If I delete the "<%= render 'form' %>" form the other html, the page loads perfectly, but I need a form and I am trying to learn Ruby. Sorry


问:
How to prevent Sql-Injection on User-Generated Sql Queries
I have a project (private, ASP.net website, password protected with https) where one of the requirements is that the user be able to enter Sql queries that will directly query the database. I need to be able to allow these queries, while preventing them from doing damage to the database itself, and from accessing or updating data that they shouldn't be able to access/update.

I have come up with the following rules for implementation:

Use a db user that only has permission for Select Table/View and Update Table (thus any other commands like drop/alter/truncate/insert/delete will just not run).

Verify that the statement begins with the words "Select" or "Update"

Verify (using Regex) that there are no instances of semi-colons in the statement that are not surrounded by single-quotes, white space and letters. (The thought here is that the only way that they could include a second query would be to end the first with a semi-colon that is not part of an input string).

Verify (using Regex) that the user has permission to access the tables being queried/updated, included in joins, etc. This includes any subqueries. (Part of the way that this will be accomplished is that the user will be using a set of table names that do not actually exist in the database, part of the query parsing will be to substitute in the correct corresponding table names into the query).

Am I missing anything?

The goal is that the users be able to query/update tables to which they have access in any way that they see fit, and to prevent any accidental or malicious attempts to damage the db. (And since a requirement is that the user generate the sql, I have no way to parametrize the query or sanitize it using any built-in tools that I know of).

答:
What you're missing is the ingenuity of an attacker finding holes in your application.

I can virtually guarantee you that you won't be able to close all the holes if you allow this. There might even be bugs in the database engine you don't know about but they do that allows an SQL statement you deem safe to wreck havoc in your system.

In short: This is a monumentally bad idea!

OwnerDisplayName: Yaakov Ellis

LastEditorDisplayName: Yaakov Ellis

OwnerDisplayName: lassevk


问:
Why is std::min_element and company not specialized for std::vector<bool>
I have a std::vector<bool> instance (foo, say), and I need to write a function that returns true if all the elements are true.

I use

```<code>return *std::min_element(foo.begin(), foo.end());
</code>```

to achieve that, but this has got me thinking: you know the minimum element is false, if the container contains at least one false value. In other words, you don't need to traverse the whole container to end(), which means that a specialisation of std::min_element is appropriate, just like a specialisation of std::vector<bool> has been deemed appropriate.

Am I missing anything? Or would this be viewed as a premature optimization? Perhaps a good compiler would sort it out anyway.

答:
Suggestion: use std::any_of, which:

Returns true if pred returns true for any of the elements in the range [first,last), and false otherwise.

meaning that it will return as soon as it finds false.

Example:

```<code>// any_of example
#include <iostream>
#include <algorithm>    // std::any_of
#include <vector>

int main () {
  std::vector<bool> foo = {true, true, true};

  if ( !std::any_of(foo.begin(), foo.end(), [](bool i){return i == false;}) )
      std::cout << "All elements are true\n";

  return 0;
}
</code>```

Output:

```<code>All elements are true.
</code>```

Live demo

Since you don't have a designated data-structure in place, then std::min_element should iterate through the whole vector, since it's a general method.

A specialization could do what you say, where you could take advantage of the compare functionality it provides.

Body:
I have a std::vector<bool> instance (foo, say), and I need to write a function that returns true if all the elements are true.

I use

return *std::min_element(foo.begin(), foo.end());

to achieve that, but this has got me thinking: you know the minimum element is false, if the container contains at least one false value. In other words, you don't need to traverse the whole container to end(), which means that a specialisation of std::min_element is appropriate, just like a specialisation of std::vector<bool> has been deemed appropriate.

Am I missing anything? Or would this be viewed as a premature optimization? Perhaps a good compiler would sort it out anyway.

Body:
Suggestion: use std::any_of, which:

Returns true if pred returns true for any of the elements in the range [first,last), and false otherwise.

meaning that it will return as soon as it finds false.

Example:

// any_of example
#include <iostream>
#include <algorithm>    // std::any_of
#include <vector>

int main () {
  std::vector<bool> foo = {true, true, true};

  if ( !std::any_of(foo.begin(), foo.end(), [](bool i){return i == false;}) )
      std::cout << "All elements are true\n";

  return 0;
}

Output:

All elements are true.

Live demo

Since you don't have a designated data-structure in place, then std::min_element should iterate through the whole vector, since it's a general method.

A specialization could do what you say, where you could take advantage of the compare functionality it provides.


问:
Get Inner Text Value for Second Child
I have the following code within a portal product I'm using

    Classification
     (Required)```

I need to somehow get the text content of the second child (i.e. the  (Required) in this case.
I can select the parent element without an issue
var req = $('label[for="Classification"') but can't work out how to select the required child and get it's content as I only need certain code to run if the second child is empty ()

答:
You can do this with the eq method which is zero-based:

var $secondSpan = $('label[for="Classification"] > span').eq(1);
$secondSpan.css('background-color','green')```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class ="control-label" for="Classification">
    <span>Classification</span>
    <span> (Required)</span>
</label></code>```

Or with the :eq selector if you prefer

var $secondSpan = $('label[for="Classification"] > span:eq(1)');
$secondSpan.css('background-color','green')```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class ="control-label" for="Classification">
    <span>Classification</span>
    <span> (Required)</span>
</label></code>```

It's worth noting there is an :empty selector too:

var $secondSpan = $('label[for="Classification"] > span:eq(1)');
var isEmpty = $secondSpan.is(":empty");
console.log(isEmpty)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class ="control-label" for="Classification">
    <span>Classification</span>
    <span> (Required)</span>
</label></code>```

Title: Get Inner Text Value for Second Child

Body:
I have the following code within a portal product I'm using

    Classification
     (Required)

I need to somehow get the text content of the second child (i.e. the  (Required) in this case.
I can select the parent element without an issue
var req = $('label[for="Classification"') but can't work out how to select the required child and get it's content as I only need certain code to run if the second child is empty ()

Body:
You can do this with the eq method which is zero-based:

var $secondSpan = $('label[for="Classification"] > span').eq(1);
$secondSpan.css('background-color','green')

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class ="control-label" for="Classification">
    <span>Classification</span>
    <span> (Required)</span>
</label>

Or with the :eq selector if you prefer

var $secondSpan = $('label[for="Classification"] > span:eq(1)');
$secondSpan.css('background-color','green')

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class ="control-label" for="Classification">
    <span>Classification</span>
    <span> (Required)</span>
</label>

It's worth noting there is an :empty selector too:

var $secondSpan = $('label[for="Classification"] > span:eq(1)');
var isEmpty = $secondSpan.is(":empty");
console.log(isEmpty)

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class ="control-label" for="Classification">
    <span>Classification</span>
    <span> (Required)</span>
</label>


问:
Node JS serving HTML pages Express
I have a multiplayer game where a server connects two clients to play against each other. It works well. However, now I want to add a welcome page where they add their username. I need to send this username to the server. However, the problem is, when loading the welcome page it makes a connection to the server (which is good). But, when i want to load the next page using

```<code>location.href = "index.html"
</code>```

it is not working. In fact, it disconnects from the server and does not reconnect. How do I load multiple files after a player hits a button? And how do I keep these files under the same "client" instance? (without disconnecting). Thank you.

答: Did you public your index.html file in Node js, to make sure your browser can access the file?

Title: Node JS serving HTML pages Express

Body:
I have a multiplayer game where a server connects two clients to play against each other. It works well. However, now I want to add a welcome page where they add their username. I need to send this username to the server. However, the problem is, when loading the welcome page it makes a connection to the server (which is good). But, when i want to load the next page using

location.href = "index.html"

it is not working. In fact, it disconnects from the server and does not reconnect. How do I load multiple files after a player hits a button? And how do I keep these files under the same "client" instance? (without disconnecting). Thank you.


答:
You have two possibilities.

You can set flex-direction to column. This will set a vertical main-axis, laying out your items vertically.

You can also set flex-wrap to wrap. This tells your flex container that it's OK to wrap elements when they would exceed their parent's width. In your case, it would wrap your second element to the next "row."

If your items are the same width as their parent container as in your example, both methods will work the same way. If the items have a different width than their parent (or, really, in any other case where you'll want elements side-by-side in a grid like the case you mention in your comment), you'll want to use flex-wrap so things layout correctly side-by-side before wrapping to another row.

Title: How to create wrapping with flexbox children


问:
Webmethod called but not entering success/error response in javascript
I have a WebForms project and I have 1 page with a Datatable inside.
The relevant things are organized in this way:

Site.master:

```<code><body>
  <form runat="server">
    <asp:ScriptManager runat="server" EnablePageMethods="true" ID="ScriptManager1">
      <Scripts>
          <asp:ScriptReference Path="~/Scripts/custom-datatable.js" />
</code>```

The WebMethod in  Default.aspx.cs:

```<code>    [System.Web.Services.WebMethod]
    public static object GetAllCONTEGGI(Nullable<DateTime> dateFrom, Nullable<DateTime> dateTo, Nullable<int> idUtente, Nullable<int> eventType, Nullable<int> logType)
    {
...
        var result = LogReader.SearchLogEvento(dateFrom, dateTo, idUtente, string_eventType, string_logType);
        return result;
    }
</code>```

The javascript custom-datatable.js:

```<code>$(document).ready(function () {
...
PageMethods.GetAllCONTEGGI(null, null, null, null, null, SuccessOnLoadingLoadUtentiFunzioni, OnError);
function SuccessOnLoadingLoadUtentiFunzioni(dataset){...}
function OnError(data) { }
}
</code>```

The Default.aspx page:

```<code><%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
    ...
    <table id="tblConteggi" class="display">
    ...
    <button id="btnClick" <%-- onclick="LoadDataTable();"--%> >Cerca log</button>
    ...
</code>```

This way works fine, i.e. calling all the javascript code inside $(document).ready(function () { ...

I noted that, when clicking the button id="btnClick", the page does a postback, as I see when i set a breakpoint in

 protected void Page_Load(object sender, EventArgs e)
    { ...
of Default.aspx.cs

Anyways, the PageMethod call is passed to SuccessOnLoadingLoadUtentiFunzioni when I create/load the Datatable.

What is strange for me, is that, when I add the onclick event handler in the button <button id="btnClick" onclick="LoadDataTable();" >Cerca log</button>,
and insert all the javascript code inside that event, and not in document.ready:

```<code>LoadDataTable()
{
...
PageMethods.GetAllCONTEGGI(null, null, null, null, null, SuccessOnLoadingLoadUtentiFunzioni, OnError);
function SuccessOnLoadingLoadUtentiFunzioni(dataset){...}
function OnError(data) { }
}
</code>```

, the WebMethod is called (as I see in debug), but then it doesn't pass neither through OnSuccess (SuccessOnLoadingLoadUtentiFunzioni), nor through OnError.

My questions are:
1. Aren't WebMethods supposed not to make postbacks ?
2. What causes the WebMethod not to return the response in the second case (the case when I insert the javascript code in a function and not directly in document.ready)

Thanks

答:
Riplace with this:

```<code><button id="btnClick" type="button" onclick="LoadDataTable();" >Cerca log</button>
</code>```

You are missing type="button", this will prevent the page to postback, and will allow the response to pass to OnSuccess

Body:
I have a WebForms project and I have 1 page with a Datatable inside.
The relevant things are organized in this way:

Site.master:

  <form runat="server">
    <asp:ScriptManager runat="server" EnablePageMethods="true" ID="ScriptManager1">

Body:
Riplace with this:

<button id="btnClick" type="button" onclick="LoadDataTable();" >Cerca log</button>

You are missing type="button", this will prevent the page to postback, and will allow the response to pass to OnSuccess


问:
how to add static method in TableAdapter
i'm working with .net 2 and visual studio 2005

I want to know how to add/create a static method in a TabelAdapter

thanks

答: Here's a blog post about implementing static "extension methods" in plain old .NET 2.0 (for those who are unable to upgrade a particular project for whatever reason).  It references Scott Hanselman's post on the subject, as well as another example post.</p>


问:
How to convert QList<T> to QVariant?
I can't find a way to convert my QList<T> to a QVariant.

There's a constructor QVariant(const QList<QVariant> &val), but no constructor for QList<T> , is it possible to convert directly a QList<T> ?

答:
Example</p>

```<code>QList<int> ints{1,2,3};
QVariant var = QVariant::fromValue<QList<int>>(ints);
</code>```

Title: How to convert QList<T> to QVariant?

Body:
Example

QList<int> ints{1,2,3};
QVariant var = QVariant::fromValue<QList<int>>(ints);


问:
JSON.parse is not parsing complete JSON String
I had this problem in which json.parse is behaving weirdly.
I am reading json from local storage and then saving it to the localstorage in cordova, but when I try to parse it and display its content in console it just shows only one element.

Below is my code.

```<code>console.log("about to display news:
" +localStorage.getItem("getNewsLastUpdated"));

var cacheData = JSON.parse(JSON.stringify(eval("(" +
localStorage.getItem(NewsCacheLocalStorage) + ")")));

console.log("CacheData: " + JSON.stringify(cacheData));
</code>```

below is the screen shot of the same:

I am reading the file as show in the code below:

```<code>readCache = function (fs,filename,NewsCacheLocalStorage) {

fs.root.getFile(filename, {}, function(fileEntry) {

    fileEntry.file(function(file) {

        var reader = new FileReader();
        console.log("inside file read");
        reader.onloadend = function(e) {

            localStorage.setItem(NewsCacheLocalStorage, this.result);
            console.log("read onloadend: " +
            localStorage.getItem(NewsCacheLocalStorage) );
        }

        reader.readAsText(file);

    }, errorReadCache);

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

}

Can any one tell me what is the problem here.

thank you in advance.

答:
It's hard to tell because you've only presented the data in the form of a screenshot and not a [mcve], but it looks like your data consists of:

An object literal

A comma operator

Another object literal

The comma operator:

evaluates each of its operands (from left to right) and returns the value of the last operand.

So it is only natural that you would end up with a single item.

If you want more than one item, put them in an array.

Body:
I had this problem in which json.parse is behaving weirdly.
I am reading json from local storage and then saving it to the localstorage in cordova, but when I try to parse it and display its content in console it just shows only one element.

Below is my code.

console.log("about to display news:
" +localStorage.getItem("getNewsLastUpdated"));

var cacheData = JSON.parse(JSON.stringify(eval("(" +
localStorage.getItem(NewsCacheLocalStorage) + ")")));

console.log("CacheData: " + JSON.stringify(cacheData));

below is the screen shot of the same:

I am reading the file as show in the code below:

readCache = function (fs,filename,NewsCacheLocalStorage) {

fs.root.getFile(filename, {}, function(fileEntry) {

    fileEntry.file(function(file) {

        var reader = new FileReader();
        console.log("inside file read");
        reader.onloadend = function(e) {

            localStorage.setItem(NewsCacheLocalStorage, this.result);
            console.log("read onloadend: " +
            localStorage.getItem(NewsCacheLocalStorage) );
        }

        reader.readAsText(file);

    }, errorReadCache);

}, errorReadCache);

}

Can any one tell me what is the problem here.

thank you in advance.


问:
Xamarin Forms Button TextColor behaves differently on Android than an iOS
I want a button's text color to be the same on both iOS and Android. So I thought I'd just set the TextColor property in code to the color I wanted. On iOS, the disabled text color is still grey (which is what I want), however, on Android, the disabled text color is the same as the enabled text color. How do I make the disabled text color on Android grey (or whatever its default is for a disabled button)?
Thanks</p>

答: If above does not work for you, you could try to check this workaround. It uses a custom renderer and NSAttributedString for setting the title in disabled state


问:
How to get instance of InstancePerRequest object inside a Singleton
I am new to Autofac, I really like its lifetime scope features, but I am having an issue.

I need to use an instance of an object created on a InstancePerRequest basis from a singleton in an assembly that doesn't have a refence to .Net MVC Web

I tried what this post suggests but it doesn't work. I get this exception:

No scope with a tag matching 'AutofacWebRequest' is visible from the
  scope in which the instance was requested.

What is the correct way to get/use an InstancePerRequest object in a Singleton?

Update
I would like to clarify, considering Travis answer, we don't want to hold a captive dependency of the InstancePerRequest item in the singleton. We want to request the item each time we use it. We've analyzed and it would be more expensive to make the singleton an InstancePerRequest than request the InstancePerRequest item to the container each time we use it.
Is this considered a bad practice? It is rather common to have certain things you need to access at the Request level and have a Singleton use them.

答:
Given the update from Dzyann

For me it sounds like you you need a Factory of the Instance per request instance. this way the Factory Func can be a singleton and the Captive Dependency is avoided.
Code would look something like this.

```<code>public class MySingleton
{
    private readonly Func<IMyInstancePerRequestType> _instanceFactory;
    public MySingleton(Func<IMyInstancePerRequestType> instanceFactory)
    {
        _instanceFactory = instanceFactory;
    }

    public void DoStuff()
    {
       var myService = _instanceFactory();
       myService.DoStuff();
    }
}
</code>```

Autofac will implicitly create the factory method for you.
So extra registration should not be needed.

Make sure you take a look at http://docs.autofac.org/en/latest/resolve/relationships.html

Regarding the 'AutofacWebRequest' error you need to use the AutofacMvc or AutoFacWebAPI nuget packages and use the Owin extension methods during startup (given your using owin) registering this will create the 'AutofacWebRequest' lifetimscope.

in startup.cs it would be something like

```<code>   app.UseAutofacMiddleware( iocContainer );
   app.UseAutofacWebApi( configuration );
</code>```

you refer to a post. in there  we have

```<code>builder.Register<Func<IDataStore>>(c =>
      {
         var context = c.Resolve<IComponentContext>();
         return context.Resolve<IDataStore>;
      });
</code>```

.InstancePerHttpRequest() could be added there.

Body:
Given the update from Dzyann

For me it sounds like you you need a Factory of the Instance per request instance. this way the Factory Func can be a singleton and the Captive Dependency is avoided.
Code would look something like this.

public class MySingleton
{
    private readonly Func<IMyInstancePerRequestType> _instanceFactory;
    public MySingleton(Func<IMyInstancePerRequestType> instanceFactory)
    {
        _instanceFactory = instanceFactory;
    }

    public void DoStuff()
    {
       var myService = _instanceFactory();
       myService.DoStuff();
    }
}

Autofac will implicitly create the factory method for you.
So extra registration should not be needed.

Make sure you take a look at http://docs.autofac.org/en/latest/resolve/relationships.html

Regarding the 'AutofacWebRequest' error you need to use the AutofacMvc or AutoFacWebAPI nuget packages and use the Owin extension methods during startup (given your using owin) registering this will create the 'AutofacWebRequest' lifetimscope.

in startup.cs it would be something like

   app.UseAutofacMiddleware( iocContainer );
   app.UseAutofacWebApi( configuration );

you refer to a post. in there  we have

builder.Register<Func<IDataStore>>(c =>
      {
         var context = c.Resolve<IComponentContext>();
         return context.Resolve<IDataStore>;
      });

.InstancePerHttpRequest() could be added there.


问:
Angular 2 + .Net Core Web Application (.Net Framework 4.5.2) node_modules scripts not found
I have prject on Core(.Net Framework 4.5.2) template and angular 2 app.
When i used Core 1.0 there were no problems, but i need Core(.Net Framework 4.5.2).

Template

When i try use npm scripts in .cshtml i get error, that files not foud.
Please Help!!!
script with node_modules

If i use MVC usual .NET 452 template such problems were not

If you can please contact with me for more details...
llotall7@gmail.com

答:
Your MVC app is likely not configured to expose that folder publicly, you typically would use a build step to bundle the needed code from your node_modules folder out into your dist folder.

In the case of using SystemJS (which seems to be outdated, by the way) you might add a task in your build process to copy those folders over to your dist folder.

If you're interested in moving away from SystemJS, I'd highly recommend that you take a look at the Angular CLI. It makes setup a breeze, and is supported by the Angular core team.


问:
Exception at removing Row Datagrid view
My grid view has some items I can remove each sucessfully by just writing

```<code>ViewActiveJobs.Rows.RemoveAt(SelectedRow);
</code>```

but this dosent help when deleting last(only one row remaning) item in grid view .I have used drop down list for this job that has many options from which i can select delete item to delete row but an exception is encountered Deleting last entery

Exceptions occurs at program.cs my form dost not returns any value to program .cs and  program .cs has

```<code>Application.Run(new MainView(LoggedUserName,LoggedUserType));
</code>```

to run a MDI parent and its child has datagrid view that should be able to delete items

Exception is
Index -1 does not have a value.

But if i remove removeAt line its fine what happens is record gets deleted at database but not frontend

答: The GridView control is very quirky, and you're better off using a third-party grid control.  But, if you're encountering a problem similar to what I've encountered in the past, simply setting the grid view to invisible while performing the final record deletion might do the trick, since the control runs into trouble when it tries to refresh its display when its data becomes "lost."  But, it depends really on what the exception is.</p>

Title: Exception at removing Row Datagrid view

Body:
My grid view has some items I can remove each sucessfully by just writing

ViewActiveJobs.Rows.RemoveAt(SelectedRow);

but this dosent help when deleting last(only one row remaning) item in grid view .I have used drop down list for this job that has many options from which i can select delete item to delete row but an exception is encountered Deleting last entery

Exceptions occurs at program.cs my form dost not returns any value to program .cs and  program .cs has

Application.Run(new MainView(LoggedUserName,LoggedUserType));

to run a MDI parent and its child has datagrid view that should be able to delete items

Exception is
Index -1 does not have a value.

But if i remove removeAt line its fine what happens is record gets deleted at database but not frontend


问:
in 'for loops and range', although same range, two result differs. wanna know why
I'm currently learning python, and I found my self encountered some issue.

```<code>a={}
for i in range(0,10):
    for j in str(i):
        a[i]='%sth number'%(j)
b={}
for i in range(0,10):
    for j in range(0,10):
        b[i]='%sth number'%(j)

print(a)
print(b)
</code>```

anyone could tell why does this two are different?

答:
Why are these two different?

well str and range have completely different functionality.

str()

str(any_value) will simple convert any_value to a string "any_value"

eg: str(1) = "1", str(23.5) = "23.5"

range()

range(integer_value) will create a list from 0 to intger_value - 1

eg: range(5) = [0, 1, 2, 3, 4]

coming back to your question, in the first scenario your second loop won't go through a list of number, rather than an string representation of the number. Your inner loop is executed only 1 time on every outer loop iteration.

However in the second scenario you are actually traversing through a list of numbers generated by range(). Your inner loop is executed 9 times on every iteration of the outer loop.

Hope this helps :)
You can read more about str and range here.

Body:
I'm currently learning python, and I found my self encountered some issue.

a={}
for i in range(0,10):
    for j in str(i):
        a[i]='%sth number'%(j)
b={}
for i in range(0,10):
    for j in range(0,10):
        b[i]='%sth number'%(j)

print(a)
print(b)

anyone could tell why does this two are different?


问:
How to auto paste a value if checkbox is checked
I want a functionality, i have a list with checkbox i if checkbox is selected i want to paste the selected value in a text field.

Something like appeared in above image.

edited:

```<code><table id="userTable" class="display" cellspacing="0" width="100%">
        <thead>
            <tr>
                <th>Order Id</th>
                <th>Order Proposed Id</th>
                <th>Order Proposed Date</th>
                <th>Store Id</th>
                <th>Select</th>
            </tr>
        </thead>
        <tbody>
        <%for(Order orderSList:orderList){ %>
            <tr>
                <td><%=orderSList.getOrderId()%></td>
                 <td><%=orderSList.getOrderProposedId()%></td>
                 <td><%=orderSList.getOrderProposedDate()%></td>
                 <td><%=orderSList.getStoreId()%></td>
                 <td><input type="checkbox" name="<portlet:namespace/>notSubmitList" value="<%=orderSList.getOrderId()%>" class="case" /></td>
            </tr>
          <%} %>
        </tbody>
    </table>
 <script>
</code>```

答:
You can detect the checkbox checked or not with onchange function of Jquery. After that you just select the its Order Proposal Id using by parent and find functions.

I added Jquery 2.1.1 to the below snippet.

$("input").on("change",function(){
  var thiz = $(this);

  if(thiz.is(':checked')){
    var value = thiz.parent().parent().find("td:nth-child(2)").text();

    $(".selected_values span").text(value);
  }
  else{
    $(".selected_values span").text("");
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border='1'>
  <tr>
    <th>Order Id</th>
    <th>Order Proposal Id</th>
    <th>Order Proposal Date</th>
    <th>Store Id</th>
    <th>Store Id</th>
  </tr>
  <tr>
    <td>2</td>
    <td>1001</td>
    <td>2016-10-21</td>
    <td>1709</td>
    <td>
      <input type='checkbox'/>
    </td>
  </tr>
  <tr>
    <td>10</td>
    <td>82715421</td>
    <td>2017-05-22</td>
    <td>525</td>
    <td>
      <input type='checkbox'/>
    </td>
  </tr>
  <tr>
    <td>11</td>
    <td>82715422</td>
    <td>2016-12-31</td>
    <td>525</td>
    <td>
      <input type='checkbox'/>
    </td>
  </tr>
</table>
<div class='selected_values'>
  <strong>Selected Value: <span></span></strong>
</div></code>```

Pure Javascript Solution

var value_span = document.getElementById("selected_value");

function printSelectedValue(e, selected_value){
  if (e.checked) {
      value_span.textContent = selected_value;
    }
    else{
      value_span.textContent = "";
    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table border='1'>
  <tr>
    <th>Order Id</th>
    <th>Order Proposal Id</th>
    <th>Order Proposal Date</th>
    <th>Store Id</th>
    <th>Store Id</th>
  </tr>
  <tr>
    <td>2</td>
    <td>1001</td>
    <td>2016-10-21</td>
    <td>1709</td>
    <td>
      <input type='checkbox' onChange="printSelectedValue(this,'1001')"/>
    </td>
  </tr>
  <tr>
    <td>10</td>
    <td>82715421</td>
    <td>2017-05-22</td>
    <td>525</td>
    <td>
      <input type='checkbox' onChange="printSelectedValue(this,'82715421')"/>
    </td>
  </tr>
  <tr>
    <td>11</td>
    <td>82715422</td>
    <td>2016-12-31</td>
    <td>525</td>
    <td>
      <input type='checkbox' onChange="printSelectedValue(this,'82715422')"/>
    </td>
  </tr>
</table>
<div>
  <strong>Selected Value: <span id='selected_value'></span></strong>
</div></code>```

Body:
I want a functionality, i have a list with checkbox i if checkbox is selected i want to paste the selected value in a text field.

Something like appeared in above image.

edited:

                Order Id
                Order Proposed Id
                Order Proposed Date
                Store Id
                Select

        <%for(Order orderSList:orderList){ %>

                <%=orderSList.getOrderId()%>
                 <%=orderSList.getOrderProposedId()%>
                 <%=orderSList.getOrderProposedDate()%>
                 <%=orderSList.getStoreId()%>
                 <input type="checkbox" name="<portlet:namespace/>notSubmitList" value="<%=orderSList.getOrderId()%>" class="case" />

          <%} %>

Body:
You can detect the checkbox checked or not with onchange function of Jquery. After that you just select the its Order Proposal Id using by parent and find functions.

I added Jquery 2.1.1 to the below snippet.

$("input").on("change",function(){
  var thiz = $(this);

  if(thiz.is(':checked')){
    var value = thiz.parent().parent().find("td:nth-child(2)").text();

    $(".selected_values span").text(value);
  }
  else{
    $(".selected_values span").text("");
  }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border='1'>
  <tr>
    <th>Order Id</th>
    <th>Order Proposal Id</th>
    <th>Order Proposal Date</th>
    <th>Store Id</th>
    <th>Store Id</th>
  </tr>
  <tr>
    <td>2</td>
    <td>1001</td>
    <td>2016-10-21</td>
    <td>1709</td>
    <td>
      <input type='checkbox'/>
    </td>
  </tr>
  <tr>
    <td>10</td>
    <td>82715421</td>
    <td>2017-05-22</td>
    <td>525</td>
    <td>
      <input type='checkbox'/>
    </td>
  </tr>
  <tr>
    <td>11</td>
    <td>82715422</td>
    <td>2016-12-31</td>
    <td>525</td>
    <td>
      <input type='checkbox'/>
    </td>
  </tr>
</table>
<div class='selected_values'>
  <strong>Selected Value: <span></span></strong>
</div>

Pure Javascript Solution

var value_span = document.getElementById("selected_value");

function printSelectedValue(e, selected_value){
  if (e.checked) {
      value_span.textContent = selected_value;
    }
    else{
      value_span.textContent = "";
    }
}

<table border='1'>
  <tr>
    <th>Order Id</th>
    <th>Order Proposal Id</th>
    <th>Order Proposal Date</th>
    <th>Store Id</th>
    <th>Store Id</th>
  </tr>
  <tr>
    <td>2</td>
    <td>1001</td>
    <td>2016-10-21</td>
    <td>1709</td>
    <td>
      <input type='checkbox' onChange="printSelectedValue(this,'1001')"/>
    </td>
  </tr>
  <tr>
    <td>10</td>
    <td>82715421</td>
    <td>2017-05-22</td>
    <td>525</td>
    <td>
      <input type='checkbox' onChange="printSelectedValue(this,'82715421')"/>
    </td>
  </tr>
  <tr>
    <td>11</td>
    <td>82715422</td>
    <td>2016-12-31</td>
    <td>525</td>
    <td>
      <input type='checkbox' onChange="printSelectedValue(this,'82715422')"/>
    </td>
  </tr>
</table>
<div>
  <strong>Selected Value: <span id='selected_value'></span></strong>
</div>


问:
Is there a way to find whether authentication followed MSA or Azure AD in MSAL.js
I tried using the code provided here: https://github.com/Azure-Samples/active-directory-javascript-singlepageapp-dotnet-webapi-v2

It works for both MSA and Azure AD authentication. I need to know whether the email address entered was MSA or Azure AD. Is there a way to find that out from the response?

答:
In the id_token you get back, there's a iss (issuer) claim.
This claim contains the user's tenant.

If the user used a Microsoft Account (MSA), their issuer claims will contain the following GUID for the MSA tenant: 9188040d-6c67-4c5b-b112-36a304b66dad

The full value of the issuer will be:

```<code>https://login.microsoftonline.com/9188040d-6c67-4c5b-b112-36a304b66dad/v2.0
</code>```

Any other GUID indicates that the user signed in using Azure AD and the GUID value will represent their Azure AD tenant.

For more information check out the id_token section of the Token Reference documentation.

Body:
In the id_token you get back, there's a iss (issuer) claim.
This claim contains the user's tenant.

If the user used a Microsoft Account (MSA), their issuer claims will contain the following GUID for the MSA tenant: 9188040d-6c67-4c5b-b112-36a304b66dad

The full value of the issuer will be:

https://login.microsoftonline.com/9188040d-6c67-4c5b-b112-36a304b66dad/v2.0

Any other GUID indicates that the user signed in using Azure AD and the GUID value will represent their Azure AD tenant.

For more information check out the id_token section of the Token Reference documentation.


问:
How to get XYPlot axis with OnTouchListener
I'm trying to get the axis of an XYPlot using a custom OnTouchListener:

```<code>mPlot.setOnTouchListener(new View.OnTouchListener(){
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                float touchX = event.getX();
                float touchY = event.getY();
                Log.d(TAG, touchX+":"+touchY);
                return false;
            }
        });
</code>```

The problem is that I'm getting the pixel values.

Is there any method or workaround to get the exact axis of the plot?

答:
I checked some androidplot doc and apaprently XYPlot object has these methods, maybe they're what you need

```<code>public Number screenToSeriesX(float x)

public Number screenToSeriesY(float y)
</code>```

Body:
I'm trying to get the axis of an XYPlot using a custom OnTouchListener:

mPlot.setOnTouchListener(new View.OnTouchListener(){
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                float touchX = event.getX();
                float touchY = event.getY();
                Log.d(TAG, touchX+":"+touchY);
                return false;
            }
        });

The problem is that I'm getting the pixel values.

Is there any method or workaround to get the exact axis of the plot?

Body:
I checked some androidplot doc and apaprently XYPlot object has these methods, maybe they're what you need

public Number screenToSeriesX(float x)

public Number screenToSeriesY(float y)


问:
Using Hunspell with Unity (.net 2.0)
Hi is there somewhere solution for Hunspell for Unity(.net 2.0). I'm working on android platform.
I tried to implement WeCantSpell.HuntSpell

But i get problem with encoding : "Encoding name 'ISO8859-1' not supported"
I researched a bit, and i saw it's using:  "Encoding.RegisterProvider" which is introduced in net 4.5.

When i tried to implement nhunspell i got problem with initialisation. Actually problem with loading dll's.

```<code>ArgumentNullException: Argument cannot be null. Parameter name: path1 System.IO.Path.Combine (System.String path1, System.String path2) (at /Users/builduser/buildslave/monoAndRuntimeClassLibs/build/mcs/class/corlib/System.IO/Path.cs:138) NHunspell.MarshalHunspellDll.get_NativeDLLPath () NHunspell.MarshalHunspellDll.ReferenceNativeHunspellDll ()
</code>```

Probably Hunspell is working only for windows platform? And only with net 4.5?

Are there any alternatives that use .dic and .aff files. I need this kind of solution, beacuse if i convert dic+aff to words list, for come countries files are 100MB+. From functionalities i only need to check if word exists in dict.

SOLUTION:
Unity 2017 support .NET 4.5, i tried today beta version and it is working with Hunspell C# Port.

答:
Answer to my own question, for other guys who might get stuck like me:
Unity 2017 have .NET 4.5, i tried today beta version and it is working with Hunspell C# Port.</p>

Title: Using Hunspell with Unity (.net 2.0)

Body:
Hi is there somewhere solution for Hunspell for Unity(.net 2.0). I'm working on android platform.
I tried to implement WeCantSpell.HuntSpell

But i get problem with encoding : "Encoding name 'ISO8859-1' not supported"
I researched a bit, and i saw it's using:  "Encoding.RegisterProvider" which is introduced in net 4.5.

When i tried to implement nhunspell i got problem with initialisation. Actually problem with loading dll's.

ArgumentNullException: Argument cannot be null. Parameter name: path1 System.IO.Path.Combine (System.String path1, System.String path2) (at /Users/builduser/buildslave/monoAndRuntimeClassLibs/build/mcs/class/corlib/System.IO/Path.cs:138) NHunspell.MarshalHunspellDll.get_NativeDLLPath () NHunspell.MarshalHunspellDll.ReferenceNativeHunspellDll ()

Probably Hunspell is working only for windows platform? And only with net 4.5?

Are there any alternatives that use .dic and .aff files. I need this kind of solution, beacuse if i convert dic+aff to words list, for come countries files are 100MB+. From functionalities i only need to check if word exists in dict.

SOLUTION:
Unity 2017 support .NET 4.5, i tried today beta version and it is working with Hunspell C# Port.


问:
How to force jenkins to reload a jenkinsfile?
My jenkinsfile has several paremeters, every time I make an update in the parameters (e.g. remove or add a new input) and commit the change to my SCM, I do not see the job input screen updated accordingly in jenkins, I have to run an execution, cancel it and then see my updated fields in

```<code>properties([
  parameters([
    string(name: 'a',       defaultValue: 'aa',     description: '*', ),
    string(name: 'b',   description: '*', ),
    string(name: 'c',       description: '*', ),
   ])
])
</code>```

any clues?

答: The Jenkinsfile needs to be executed in order to update the job properties, so you need to start a build with the new file.</p>

Body:
My jenkinsfile has several paremeters, every time I make an update in the parameters (e.g. remove or add a new input) and commit the change to my SCM, I do not see the job input screen updated accordingly in jenkins, I have to run an execution, cancel it and then see my updated fields in

properties([
  parameters([
    string(name: 'a',       defaultValue: 'aa',     description: '*', ),
    string(name: 'b',   description: '*', ),
    string(name: 'c',       description: '*', ),
   ])
])

any clues?


问:
C# DataGridView - Table is not populating
I'm trying to display data that I pull from text files within my program.cs  to a DataGridView, but the table remains blank when I run the code.

Another problem I have is that when the form opens it stops running through the code.

Basically what the code does is it downloads .zip files from an sftp server, unzips a text file, reads through the file adding each line to an array and splits a certain line into an array. I'm trying to get the variables from that array to appear on a DataGridView in my form.

Here is my code:

```<code>class Machine
{
    public string MacNum { get; set; }
    public string CashCount { get; set; }
    public string VendCount { get; set; }
}

static class Program
{
    [STAThread]
    static void Main()
    {
        string zipTemp = (@"C:\Users\mark\Desktop\Project Dex\zipTemp\");

        string machineCashCount = ("");
        string hostIP = ("0.0.0.0");
        string userName = ("UN");
        string passWord = ("PW");
        string remotePath = (@"/home/dex/RESPONSE/PROCESSED");
        string localPath = (@"C:\Users\mark\Desktop\Project Dex\Temp\PROCESSED\");

        Application.Run(new Form1());
        DataGridView dataGridView = new DataGridView();
        IList<Machine> machines = new BindingList<Machine>();
        dataGridView.DataSource = machines;

        SessionOptions sessionOptions = new SessionOptions
        {
            Protocol = Protocol.Sftp,
            HostName = hostIP,
            UserName = userName,
            Password = passWord,
            PortNumber = 22,
            SshHostKeyFingerprint = "ssh-rsa 2048 96:48:96:52:8c:e7:de:c6:e1:00:08:7e:db:ad:e4:06"
        };

        using (Session session = new Session())
        {
            session.Open(sessionOptions);

            TransferOptions transferOptions = new TransferOptions();
            transferOptions.TransferMode = TransferMode.Binary;

            session.GetFiles(remotePath, @"C:\Users\mark\Desktop\Project Dex\Temp\").Check();
        }

        DirectoryInfo directorySelected = new DirectoryInfo(@"C:\Users\mark\Desktop\Project Dex\Temp\PROCESSED\");
        List<string> fileNames = new List<string>();

        foreach (FileInfo fileInfo in directorySelected.GetFiles("*.zip"))
        {
            fileNames.Add(fileInfo.Name);
        }

        foreach (string fileName in fileNames)
        {
            string zipFilePath = localPath + fileName;

            using (ZipFile zip1 = ZipFile.Read(zipFilePath))
            {
                var selection = (from e in zip1.Entries
                                 where (e.FileName).StartsWith("01e")
                                 select e);

                Directory.CreateDirectory(zipTemp);

                foreach (var e in selection)
                {
                    e.Extract(zipTemp, ExtractExistingFileAction.OverwriteSilently);
                }
            }

            DirectoryInfo dexDirect = new DirectoryInfo(@"C:\Users\mark\Desktop\Project Dex\zipTemp\");
            List<string> dexName = new List<string>();

            foreach (FileInfo dexInfo in dexDirect.GetFiles("*.dex"))
            {
                dexName.Add(dexInfo.Name);
            }

            foreach (string dexNames in dexName)
            {
                string dexFilePath = zipTemp + dexNames;

                string[] lines = System.IO.File.ReadAllLines(dexFilePath);

                foreach (string line in lines)
                {
                    machineCashCount = Array.Find(lines,
                        element => element.StartsWith("VA1", StringComparison.Ordinal));
                }
                string[] MCC1 = machineCashCount.Split('*');
                string[] nm = dexNames.Split('.');

                int nam = int.Parse(nm[0], System.Globalization.NumberStyles.HexNumber);

                // Console.WriteLine((nam + (":") + "Total cash count: ") + MCC1[1]);
                // Console.WriteLine((nam + (":") + "Number of paid vends: ") + MCC1[2]);

                Machine m = new Machine();

                m.MacNum = nm[0];
                m.CashCount = MCC1[1];
                m.VendCount = MCC1[2];
                machines.Add(m);
            }
        }

        Application.Run(new Form1());
    }
}
</code>```

Form1:

```<code>public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    public void Form1_Load(object sender, EventArgs e)
    {

    }

    private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {

    }

    private void button1_Click(object sender, EventArgs e)
    {

    }
}
</code>```

答:
What your program is basically doing is it runs the Form, downloads the zip file, processes the zip file and that's it.

You will need to do all this in the form's form_load event or a button click event instead of the Main().

remove the Application.Run(new form1) from the beginning of the code. Not required.

Move everything before the last Application.Run(new Form1) [Note this is with 'F' which is the correct one] to the a private function inside the form. Let's call it processFile()

Call this processFile() in the Form1_Load() event.

Assign m to the DataGridView's data property and call DataGridView.Bind() to bind the data to the datagrid control.

UPDATE:
Since you have a button and a Button_Click event, put the processFile() in the Button's click event. When the form is displayed, click the button to get the whole process running

Body:
I'm trying to display data that I pull from text files within my program.cs  to a DataGridView, but the table remains blank when I run the code.

Another problem I have is that when the form opens it stops running through the code.

Basically what the code does is it downloads .zip files from an sftp server, unzips a text file, reads through the file adding each line to an array and splits a certain line into an array. I'm trying to get the variables from that array to appear on a DataGridView in my form.

Here is my code:

class Machine
{
    public string MacNum { get; set; }
    public string CashCount { get; set; }
    public string VendCount { get; set; }
}

static class Program
{
    [STAThread]
    static void Main()
    {
        string zipTemp = (@"C:\Users\mark\Desktop\Project Dex\zipTemp\");

        string machineCashCount = ("");
        string hostIP = ("0.0.0.0");
        string userName = ("UN");
        string passWord = ("PW");
        string remotePath = (@"/home/dex/RESPONSE/PROCESSED");
        string localPath = (@"C:\Users\mark\Desktop\Project Dex\Temp\PROCESSED\");

        Application.Run(new Form1());
        DataGridView dataGridView = new DataGridView();
        IList<Machine> machines = new BindingList<Machine>();
        dataGridView.DataSource = machines;

        SessionOptions sessionOptions = new SessionOptions
        {
            Protocol = Protocol.Sftp,
            HostName = hostIP,
            UserName = userName,
            Password = passWord,
            PortNumber = 22,
            SshHostKeyFingerprint = "ssh-rsa 2048 96:48:96:52:8c:e7:de:c6:e1:00:08:7e:db:ad:e4:06"
        };

        using (Session session = new Session())
        {
            session.Open(sessionOptions);

            TransferOptions transferOptions = new TransferOptions();
            transferOptions.TransferMode = TransferMode.Binary;

            session.GetFiles(remotePath, @"C:\Users\mark\Desktop\Project Dex\Temp\").Check();
        }

        DirectoryInfo directorySelected = new DirectoryInfo(@"C:\Users\mark\Desktop\Project Dex\Temp\PROCESSED\");
        List<string> fileNames = new List<string>();

        foreach (FileInfo fileInfo in directorySelected.GetFiles("*.zip"))
        {
            fileNames.Add(fileInfo.Name);
        }

        foreach (string fileName in fileNames)
        {
            string zipFilePath = localPath + fileName;

            using (ZipFile zip1 = ZipFile.Read(zipFilePath))
            {
                var selection = (from e in zip1.Entries
                                 where (e.FileName).StartsWith("01e")
                                 select e);

                Directory.CreateDirectory(zipTemp);

                foreach (var e in selection)
                {
                    e.Extract(zipTemp, ExtractExistingFileAction.OverwriteSilently);
                }
            }

            DirectoryInfo dexDirect = new DirectoryInfo(@"C:\Users\mark\Desktop\Project Dex\zipTemp\");
            List<string> dexName = new List<string>();

            foreach (FileInfo dexInfo in dexDirect.GetFiles("*.dex"))
            {
                dexName.Add(dexInfo.Name);
            }

            foreach (string dexNames in dexName)
            {
                string dexFilePath = zipTemp + dexNames;

                string[] lines = System.IO.File.ReadAllLines(dexFilePath);

                foreach (string line in lines)
                {
                    machineCashCount = Array.Find(lines,
                        element => element.StartsWith("VA1", StringComparison.Ordinal));
                }
                string[] MCC1 = machineCashCount.Split('*');
                string[] nm = dexNames.Split('.');

                int nam = int.Parse(nm[0], System.Globalization.NumberStyles.HexNumber);

                // Console.WriteLine((nam + (":") + "Total cash count: ") + MCC1[1]);
                // Console.WriteLine((nam + (":") + "Number of paid vends: ") + MCC1[2]);

                Machine m = new Machine();

                m.MacNum = nm[0];
                m.CashCount = MCC1[1];
                m.VendCount = MCC1[2];
                machines.Add(m);
            }
        }

        Application.Run(new Form1());
    }
}

Form1:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    public void Form1_Load(object sender, EventArgs e)
    {

    }

    private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {

    }

    private void button1_Click(object sender, EventArgs e)
    {

    }
}


问:
Keeping track of the page that the user entered through
I'm trying to figure out how keep track of the incoming page a visitor initially entered through and show that as a link throughout the site so that they can return to that initial page if they are navigating around the site.  Essentially the client's model is that they they're going to email links to a potential customer to a specific product page.  They didn't build a navigation on the site with all their products (bad idea I know).  But should the user leave that initial product page after entering through the email link and navigate to the contact page, homepage or wherever else, there's really no way unless they continually click back to find that initial product page they entered through.

So I'm using a PHP CMS (MODx specifically) and using Foxy Cart ecommerce.  As such, I've got jquery and JSON at my disposal to work with.  Unfortunately I have no idea where to start.

Here would be what I assume I need to do:

Have an empty div that's waiting in a sense to receive the incoming link.

Upon entering the product page, the jquery would "grab" the value in the h1 tag and grab the URL as well, store that info the empty div mentioned above.

Here's what I would envision it to be (please feel free to correct me if I'm wrong or if you have a better idea):

```<code><h1>Product Name Here</h1>
<div class="records_first_page_entry_name"><a href="[+first_page_URL+]">[+product_name_here+]</a></div>
</code>```

I would assume that these placeholders (namely [+first_page_URL+] and [+product_name_here+]) would be replaced by their respective values.  Then I would need this div's values to be carried throughout all the pages of my site.

I hope I'm explaining myself correctly.  Thanks!

答: Do you really need to get the specified url? You can navigate back with window.history.back(). An other option is to retrieve the site server side but I don't know if it is possible with jQuery.

Body:
I'm trying to figure out how keep track of the incoming page a visitor initially entered through and show that as a link throughout the site so that they can return to that initial page if they are navigating around the site.  Essentially the client's model is that they they're going to email links to a potential customer to a specific product page.  They didn't build a navigation on the site with all their products (bad idea I know).  But should the user leave that initial product page after entering through the email link and navigate to the contact page, homepage or wherever else, there's really no way unless they continually click back to find that initial product page they entered through.

So I'm using a PHP CMS (MODx specifically) and using Foxy Cart ecommerce.  As such, I've got jquery and JSON at my disposal to work with.  Unfortunately I have no idea where to start.

Here would be what I assume I need to do:

Have an empty div that's waiting in a sense to receive the incoming link.

Upon entering the product page, the jquery would "grab" the value in the h1 tag and grab the URL as well, store that info the empty div mentioned above.

Here's what I would envision it to be (please feel free to correct me if I'm wrong or if you have a better idea):

Product Name Here

[+product_name_here+]

I would assume that these placeholders (namely [+first_page_URL+] and [+product_name_here+]) would be replaced by their respective values.  Then I would need this div's values to be carried throughout all the pages of my site.

I hope I'm explaining myself correctly.  Thanks!


问:
How to create wrapping with flexbox children
I want a grid to wrap when constrained by an outer node:

So the following should have two cells  one on top of each other, but it renders them side by side:

```<code><div style="display:flex; width:100px">
    <div style="flex: 1; width: 100px;">foo</div>
    <div style="flex: 1; width: 100px;">bar</div>
</div>
</code>```

How can I achieve my desired result?

答:
Just add flex-wrap: wrap; (the second example below wraps, the first one not since the container's width is wide enough to accomodate both children in one line)

foo

bar

foo

bar

```

Body:
I want a grid to wrap when constrained by an outer node:

So the following should have two cells  one on top of each other, but it renders them side by side:

foo

bar

How can I achieve my desired result?

Body:
Just add flex-wrap: wrap; (the second example below wraps, the first one not since the container's width is wide enough to accomodate both children in one line)

<div style="display:flex; flex-wrap: wrap; width:200px; margin-bottom: 50px; border: 1px solid blue;">
    <div style="width: 100px;">foo</div>
    <div style="width: 100px;">bar</div>
</div>

<div style="display:flex; flex-wrap: wrap; width:100px; border: 1px solid red;">
    <div style="width: 100px;">foo</div>
    <div style="width: 100px;">bar</div>
</div>