问:
signalR asp.net set username and connectionID
i am new in signalR(and JQuery :D) ..... i want to set some usernames and map it to connectionId... after checking some samples this is my code.how ever it does not work ..... the page is running without error but the div id="msg" remains unchanged.

for now all i want is to write the list of usernames and connectionids on the client page.

SERVER

```<code>namespace SERVXZ
{
    class UserConn
    {
        public string Usrname { set; get; }
        public string ConnectionID { set; get; }
    }

    public class XZHUB : Hub
    {
        //public static ConcurrentDictionary<string, string> MyUsers = new ConcurrentDictionary<string, string>();
        List<UserConn> ulist = new List<UserConn>();
        public override Task OnConnected()
        {
            var us = new UserConn();
            us.Usrname = Context.QueryString["username"];
            us.ConnectionID = Context.ConnectionId;
            ulist.Add(us);

           // var username = Context.QueryString["username"];
           // MyUsers.TryAdd(Context.ConnectionId,username);

            return base.OnConnected();
        }

        public void Send()
        {
            Clients.All.broadcastMessage(ulist[0]);

        }
    }
}
</code>```

CLIENT

```<code><%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Main.aspx.cs" Inherits="SERVXZ.Main" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:Label ID="USR" runat="server" Text="UserName"></asp:Label>

            <br />
            <asp:Button ID="SUB" runat="server" OnClick="SUB_Click" Text="Submit" />

            <div id="msg">HERE</div>

            <script src="Scripts/jquery-3.1.1.js"></script>

            <script src="Scripts/jquery.signalR-2.2.2.js"></script>

            <script src="/signalr/hubs"></script>

            <script type="text/javascript">

                $(function () {
                    var con = $.connection.XZHUB;
                    $('#msg').text("test");
                    $.connection.hub.qs = { 'username': 'rooz' };

                    con.client.broadcastMessage = function (msg) {
                        var enmsg = $('<dive />').text(msg).html();
                        $('#msg').append('<div>'+enmsg+'</div>');
                    };

                    $.connection.hub.start().done(function () {
                        $('#SUB').click(function () {
                            con.server.send();
                        });
                    });

                });

            </script>

        </div>
    </form>
</body>
</html>
</code>```

Thank you in advance .......................:)

答:
The problem is the hub name. If you don't set the hub name it'll be generated with the name xZHUB.

So you could do 2 things:

Use the default name:

```<code>var con = $.connection.xZHUB;
</code>```

Or change the hub name

```<code>[HubName("XZHUB")]
public class XZHUB : Hub
</code>```

There are also another things you need to check:

The hubs are not static, so ulist will be recreated in each call. You should consider making it static or change that logic.

The "SUB" button will make a post so it won't work. I replaced it with a normal button:

```<code><button ID="SUB">Submit</button>
</code>```

Body:
i am new in signalR(and JQuery :D) ..... i want to set some usernames and map it to connectionId... after checking some samples this is my code.how ever it does not work ..... the page is running without error but the div id="msg" remains unchanged.

for now all i want is to write the list of usernames and connectionids on the client page.

SERVER

namespace SERVXZ
{
    class UserConn
    {
        public string Usrname { set; get; }
        public string ConnectionID { set; get; }
    }

    public class XZHUB : Hub
    {
        //public static ConcurrentDictionary<string, string> MyUsers = new ConcurrentDictionary<string, string>();
        List<UserConn> ulist = new List<UserConn>();
        public override Task OnConnected()
        {
            var us = new UserConn();
            us.Usrname = Context.QueryString["username"];
            us.ConnectionID = Context.ConnectionId;
            ulist.Add(us);

           // var username = Context.QueryString["username"];
           // MyUsers.TryAdd(Context.ConnectionId,username);

            return base.OnConnected();
        }

        public void Send()
        {
            Clients.All.broadcastMessage(ulist[0]);

        }
    }
}

CLIENT

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Main.aspx.cs" Inherits="SERVXZ.Main" %>

<!DOCTYPE html>

    <title></title>

    <form id="form1" runat="server">

            <asp:Label ID="USR" runat="server" Text="UserName"></asp:Label>

            <asp:Button ID="SUB" runat="server" OnClick="SUB_Click" Text="Submit" />

HERE

    </form>

Thank you in advance .......................:)

Body:
The problem is the hub name. If you don't set the hub name it'll be generated with the name xZHUB.

So you could do 2 things:

Use the default name:

var con = $.connection.xZHUB;

Or change the hub name

[HubName("XZHUB")]
public class XZHUB : Hub

There are also another things you need to check:

The hubs are not static, so ulist will be recreated in each call. You should consider making it static or change that logic.

The "SUB" button will make a post so it won't work. I replaced it with a normal button:

<button ID="SUB">Submit</button>


来源: stackexchange

问:
Dispatching C++ generated files into srcs and hdrs
In the Bazel official documentation there is an example explaining how to create a Java library built from regular java files and files generated by a :gen_java_srcs rule. I rewrite this code here for ease of reading:

```<code>java_library(
    name = "mylib",
    srcs = glob(["*.java"]) + [":gen_java_srcs"],
    deps = "...",
)

genrule(
    name = "gen_java_srcs",
    outs = [
        "Foo.java",
        "Bar.java",
    ],
    ...
)
</code>```

Now in a C++ perspective, I am in a scenario where the genrule generates two kind of files: .hpp and .cpp:

```<code>genrule(
    name = "gen_cpp_srcs",
    outs = [
        "myFile_1.hpp","myFile_2.hpp",...,"myFile_N.hpp",
        "myFile.cpp","myFile_2.cpp",...,"myFile_N.cpp",
    ],
    ...
)
</code>```

where N is some tens.

My problem/question is: how to write the cc_library rule, with an automatic dispatching of the hpp and cpp files into hdrs and srcs field?

I want something like:

```<code>cc_library(
    name = "mylib",
    srcs = glob(["*.cpp"]) + (howto: .cpp files of [":gen_cpp_srcs"]),
    hdrs = glob(["*.hpp"]) + (howto: .hpp files of [":gen_cpp_srcs"]),
    ...
)
</code>```

Some magic like:

```<code>output_filter(":gen_cpp_srcs","*.cpp")
</code>```

would be perfect, but I do not know enough of Bazel to make it real.

答:
Depending on the genrule by name (:gen_cpp_srcs) will give you all of the outputs of the genrule, as you have noted. Instead, you can depend on the individual outputs of the genrule (e.g. hdrs = [:myFile.hpp] and srcs = [:myFile.cpp]).

See also the answer to Bazel & automatically generated cpp / hpp files.

ContentLicense: CC BY-SA 3.0

Body:
In the Bazel official documentation there is an example explaining how to create a Java library built from regular java files and files generated by a :gen_java_srcs rule. I rewrite this code here for ease of reading:

java_library(
    name = "mylib",
    srcs = glob(["*.java"]) + [":gen_java_srcs"],
    deps = "...",
)

genrule(
    name = "gen_java_srcs",
    outs = [
        "Foo.java",
        "Bar.java",
    ],
    ...
)

Now in a C++ perspective, I am in a scenario where the genrule generates two kind of files: .hpp and .cpp:

genrule(
    name = "gen_cpp_srcs",
    outs = [
        "myFile_1.hpp","myFile_2.hpp",...,"myFile_N.hpp",
        "myFile.cpp","myFile_2.cpp",...,"myFile_N.cpp",
    ],
    ...
)

where N is some tens.

My problem/question is: how to write the cc_library rule, with an automatic dispatching of the hpp and cpp files into hdrs and srcs field?

I want something like:

cc_library(
    name = "mylib",
    srcs = glob(["*.cpp"]) + (howto: .cpp files of [":gen_cpp_srcs"]),
    hdrs = glob(["*.hpp"]) + (howto: .hpp files of [":gen_cpp_srcs"]),
    ...
)

Some magic like:

output_filter(":gen_cpp_srcs","*.cpp")

would be perfect, but I do not know enough of Bazel to make it real.


问:
Lisp, Remove sublist with two common elements
i am programming in Common lisp, and i need an algorithm that delete sublist with (at least) two common elements.

i don't have any idea to how i can solve the problem. I thought to use this:

(defun remove-duplicates-list (list) (remove-duplicates list :test 'equal :key 'cdr))

but the cdr between the sublists is different, and i just can't figure out how i can count two elements and remove the sublist.
Also i need to don't remove the "original" sublist (in the example '(1 2 3 4)), bot only (2 3 4) and (1 3 4)

Example :

input: '( (1 2 3 4) (2 3 4) (5 6 7 8) (1 3 4) (9 9 9 9) )

output: '( (1 2 3 4) (5 6 7 8) (9 9 9 9) )

input: '( ((1 . 1) (2 . 2) (3 . 3) (4 . 4)) ((1 . 1) (2 . 2) (4 . 4)))

output : '((1 . 1) (2 . 2) (3 . 3) (4 . 4))

Thank you!

P.s sorry if, at first, i have not explained well my problem, i correct many mistake in the post. this is my first question on this community, so forgive please

答:
Actually you could do it with remove-duplicates. You need to make a test function that returns true when at least two elements are similar. eg.

```<code>(defun two-similar-p (lst1 lst2)
  ...)

(two-similar-p '(1 2 3) '(1 4 5)) ; ==> nil
(two-similar-p '(1 2 5) '(1 4 5)) ; ==> t
</code>```

Using a hash is the fastest and best time complexity while iterating one list (length other-list) times is possibly the easiest. Then you can solve your problem this way:

```<code>(defun remove-duplicates-list (list)
  (remove-duplicates list :test #'two-similar-p :from-end t))

(remove-duplicates-list '((1 2 3 4) (2 3 4) (5 6 7 8) (1 3 4) (9 9 9 9)))
; ==> ((1 2 3 4) (5 6 7 8) (9 9 9 9))
</code>```

Body:
Actually you could do it with remove-duplicates. You need to make a test function that returns true when at least two elements are similar. eg.

(defun two-similar-p (lst1 lst2)
  ...)

(two-similar-p '(1 2 3) '(1 4 5)) ; ==> nil
(two-similar-p '(1 2 5) '(1 4 5)) ; ==> t

Using a hash is the fastest and best time complexity while iterating one list (length other-list) times is possibly the easiest. Then you can solve your problem this way:

(defun remove-duplicates-list (list)
  (remove-duplicates list :test #'two-similar-p :from-end t))

(remove-duplicates-list '((1 2 3 4) (2 3 4) (5 6 7 8) (1 3 4) (9 9 9 9)))
; ==> ((1 2 3 4) (5 6 7 8) (9 9 9 9))


问:
Retrofit 2.0 how to get deserialised error response.body
I'm using Retrofit 2.0.0-beta1.

In tests i have an alternate scenario and expect error HTTP 400

I would like to have retrofit.Response<MyError> response
but response.body() == null

MyError is not deserialised - i see it only here

```<code>response.errorBody().string()
</code>```

but it doesn't give me MyError as object

答:
In Kotlin:</p>

```<code>val call = APIClient.getInstance().signIn(AuthRequestWrapper(AuthRequest("1234567890z", "12341234", "nonce")))
call.enqueue(object : Callback<AuthResponse> {
    override fun onResponse(call: Call<AuthResponse>, response: Response<AuthResponse>) {
        if (response.isSuccessful) {

        } else {
            val a = object : Annotation{}
            val errorConverter = RentalGeekClient.getRetrofitInstance().responseBodyConverter<AuthFailureResponse>(AuthFailureResponse::class.java, arrayOf(a))
            val authFailureResponse = errorConverter.convert(response.errorBody())
        }
    }

    override fun onFailure(call: Call<AuthResponse>, t: Throwable) {
    }
})
</code>```

Body:
I'm using Retrofit 2.0.0-beta1.

In tests i have an alternate scenario and expect error HTTP 400

I would like to have retrofit.Response<MyError> response
but response.body() == null

MyError is not deserialised - i see it only here

response.errorBody().string()

but it doesn't give me MyError as object

Body:
In Kotlin:

val call = APIClient.getInstance().signIn(AuthRequestWrapper(AuthRequest("1234567890z", "12341234", "nonce")))
call.enqueue(object : Callback<AuthResponse> {
    override fun onResponse(call: Call<AuthResponse>, response: Response<AuthResponse>) {
        if (response.isSuccessful) {

        } else {
            val a = object : Annotation{}
            val errorConverter = RentalGeekClient.getRetrofitInstance().responseBodyConverter<AuthFailureResponse>(AuthFailureResponse::class.java, arrayOf(a))
            val authFailureResponse = errorConverter.convert(response.errorBody())
        }
    }

    override fun onFailure(call: Call<AuthResponse>, t: Throwable) {
    }
})


问:
Finding a substring that is comprised of both letters and numbers in excel
I'm currently dealing with a mess of a data set that needs analysis. It was uploaded from a legacy database that just concatenated all the fields together, but different fields were empty for different data points, so there is no easy way to split them.

I have determined that I can extract useful information out of it if I can split the string on the first occurrence of a word containing both letters and numbers (eg. abc123). Unfortunately, I'm unable to use a macro enabled workbook for this, so no VBA or regex to make it easy.

Is there anyway to determine if a string or substring has a combination of letters and numbers?

Example data:

2283-332-44543 CAP DDT@ PPL445 HEEN PAX 77820

44372-33-3223 TYYTE CAP BOX 1550 244 BOX PPSSA223 PAX

PRECISE 77 CLEAR BLUE 99WIE BOX 4403 PAX SSKA

答:
I managed an awful solution that seemed to work:

First, split the data using text to columns. Then, for each cell, use:

```<code>=AND(COUNT(FIND({0,1,2,3,4,5,6,7,8,9},A2))>0, NOT(ISNUMBER(A2)) )
</code>```

After that, it was easy to concatenate all the ones proceeding the first true together, giving me actual useful data.

Thanks everyone for the help.

Body:
I managed an awful solution that seemed to work:

First, split the data using text to columns. Then, for each cell, use:

=AND(COUNT(FIND({0,1,2,3,4,5,6,7,8,9},A2))>0, NOT(ISNUMBER(A2)) )

After that, it was easy to concatenate all the ones proceeding the first true together, giving me actual useful data.

Thanks everyone for the help.


问:
Issue with .prop("checked", true)?
I have the following:

```<code>116   $.each(data.entries, function(id, item) {
117       console.log($("input[type=checkbox][value=" + item + "]").is(":checked"));
118       $("input[type=checkbox][value=" + item + "]").prop("checked", true);
119       console.log($("input[type=checkbox][value=" + item + "]").is(":checked"));
120   })
</code>```

For the life of me I can't get my checkbox to check:

```<code>swot-nav.js:117 false
swot-nav.js:119 false
</code>```

This doesn't work either:

```<code>116    $.each(data.entries, function(id, item) {
117        console.log($(":checkbox[value=" + item + "]").is(":checked"));
118        $(":checkbox[value=" + item + "]").prop("checked", "true");
119        console.log($(":checkbox[value=" + item + "]").is(":checked"));
120    })
</code>```

(same result)

What could I be missing?

Edit:

This is taking place in the success function of an Ajax Call.

This is what the data looks like:

data = {'label': 'D1- DC Test 1', 'details': '', 'type': 'D', 'entries': [20, 21, 22]

Here's a fiddle where it's working: https://jsfiddle.net/e3arwp7q/

There must be something wrong deeper in my code. If this looks to everyone like it is supposed to work, then maybe I should look elsewhere.

答:
you should use :checked selector.

add colon before checked

change is("checked") to is(":checked")

Title: Issue with .prop("checked", true)?

Body:
I have the following:

116   $.each(data.entries, function(id, item) {
117       console.log($("input[type=checkbox][value=" + item + "]").is(":checked"));
118       $("input[type=checkbox][value=" + item + "]").prop("checked", true);
119       console.log($("input[type=checkbox][value=" + item + "]").is(":checked"));
120   })

For the life of me I can't get my checkbox to check:

swot-nav.js:117 false
swot-nav.js:119 false

This doesn't work either:

116    $.each(data.entries, function(id, item) {
117        console.log($(":checkbox[value=" + item + "]").is(":checked"));
118        $(":checkbox[value=" + item + "]").prop("checked", "true");
119        console.log($(":checkbox[value=" + item + "]").is(":checked"));
120    })

(same result)

What could I be missing?

Edit:

This is taking place in the success function of an Ajax Call.

This is what the data looks like:

data = {'label': 'D1- DC Test 1', 'details': '', 'type': 'D', 'entries': [20, 21, 22]

Here's a fiddle where it's working: https://jsfiddle.net/e3arwp7q/

There must be something wrong deeper in my code. If this looks to everyone like it is supposed to work, then maybe I should look elsewhere.


问:
Genetic algorithms: How to do crossover in "subset" problems?
I have a problem which I am trying to solve with genetic algorithms. The problem is selecting some subset (say 4) of 100 integers (these integers are just ids that represent something else). Order does not matter, the solution to the problem is a SET of integers not an ordered list. I have a good fitness function but am having trouble with the crossover function.

I want to be able to mate the following two chromosomes:

[1 2 3 4] and
[3 4 5 6] into something useful. Clearly I cannot use the typical crossover function because I could end up with duplicates in my children which would represent invalid solutions. What is the best crossover method in this case.

答: Sometimes it is beneficial to let your solution go "out of bounds" so that your search will converge more quickly.  Rather than making a set of 4 unique integers a requirement for your chromosome, make the number of integers (and their uniqueness) part of the fitness function.</p>

ContentLicense: CC BY-SA 2.5


问:
Set nil string pointer to empty string
How do I set the referenced value of a string pointer in a type to the empty string?
Consider this example:

```<code>package main

import (
    "fmt"
)

type Test struct {
    value *string
}

func main() {
    t := Test{nil}
    if t.value == nil {
        // I want to set the pointer's value to the empty string here
    }

    fmt.Println(t.value)
}
</code>```

I've tried all combinations of the & and * operators to no avail:

```<code>t.value = &""
t.value = *""
&t.value = ""
*t.value = ""
</code>```

Obviously some of those are silly, but I didn't see the harm in trying.
I also tried using reflect and SetString:

```<code>reflect.ValueOf(t.value).SetString("")
</code>```

and this gives a compilation error

panic: reflect: reflect.Value.SetString using unaddressable value

I'm assuming that's because strings in Go are immutable?

答:
String literals are not addressable.

Take the address of variable containing the empty string:

```<code>s := ""
t.value = &s
</code>```

or use new:

```<code>t.value = new(string)
</code>```

ContentLicense: CC BY-SA 4.0

Title: Set nil string pointer to empty string

Body:
How do I set the referenced value of a string pointer in a type to the empty string?
Consider this example:

package main

import (
    "fmt"
)

type Test struct {
    value *string
}

func main() {
    t := Test{nil}
    if t.value == nil {
        // I want to set the pointer's value to the empty string here
    }

    fmt.Println(t.value)
}

I've tried all combinations of the & and * operators to no avail:

t.value = &""
t.value = *""
&t.value = ""
*t.value = ""

Obviously some of those are silly, but I didn't see the harm in trying.
I also tried using reflect and SetString:

reflect.ValueOf(t.value).SetString("")

and this gives a compilation error

panic: reflect: reflect.Value.SetString using unaddressable value

I'm assuming that's because strings in Go are immutable?

Body:
String literals are not addressable.

Take the address of variable containing the empty string:

s := ""
t.value = &s

or use new:

t.value = new(string)


问:
VBA to Select variable rows across columns
current code is

```<code>lngLastRowDPWK = ActiveSheet.Cells(Activesheet.Rows.Count,"DX".End(xlUP).Row+3

Range("DP" & lngLastRowDPWK:"DV" & lngLastRowDPWK +2).select
</code>```

I'm wanting it to highlight a few rows of in columns DP-DV but the row number is a variable.
Any help is appreciated. Thank you

答:
```<code>Sub test()
    'You were missing a ")"
    lngLastRowDPWK = ActiveSheet.Cells(ActiveSheet.Rows.Count, "DX").End(xlUp).Row + 3
    'You weren't creating the string correctly
    Range("DP" & lngLastRowDPWK & ":DV" & lngLastRowDPWK + 2).Select
End Sub
</code>```

Body:
current code is

lngLastRowDPWK = ActiveSheet.Cells(Activesheet.Rows.Count,"DX".End(xlUP).Row+3

Range("DP" & lngLastRowDPWK:"DV" & lngLastRowDPWK +2).select

I'm wanting it to highlight a few rows of in columns DP-DV but the row number is a variable.
Any help is appreciated. Thank you


问:
trigger to delete a record before insert
i have a table with 4 columns

```<code>1.msisdn
2.accountnumber
3.cardnumber
4.subscriptiondate
</code>```

I want to add a trigger to this table. If the data i am inserting is

```<code>1.99999999
2.2
3.3298572857239
4.(this can be blank)
</code>```

and the data that is currently in the table is

```<code>1.99999999
2.1
3.3298572857239
4.(this can be blank)
</code>```

Trigger should check if there is this msisdn 99999999 is already having a record with this cardnumber 3298572857239. If there is a record already existing in the table, the trigger should delete the existing entry and insert the new one. The final result should look like this

```<code>1.99999999
2.1
3.3298572857239
4.(this can be blank)
</code>```

I want to keep the value of accountnumber same before and after the trigger. This is what i have tried so far but for this trigger, i am not getting any data in accountnumber column. Please someone help

```<code>DROP TRIGGER TRIG_TABLEA;

CREATE OR REPLACE TRIGGER TRIG_TABLEA
BEFORE INSERT ON TABLEA
REFERENCING OLD AS Old NEW AS New
FOR EACH ROW
BEGIN
 :new.accountnumber := :old.accountnumber;
 DELETE FROM TABLEA WHERE MSISDN = :new.MSISDN AND CARDNUMBER = :new.CARDNUMBER;
 :new.MSISDN := :new.MSISDN;
 :new.CARDNUMBER := :new.CARDNUMBER;
 :new.accountnumber := :old.accountnumber;
END;
/
</code>```

答:
Don't do a delete-and-insert. You want MERGE. The only thing that can change in your statement is accountnumber and subscriptiondate. You don't say where the data is coming from, so I assume this is a PL/SQL procedure with p_* as the parameters. So you want something like this:

```<code>MERGE INTO mytable trg
USING ( SELECT p_accountnumber, p_subscriptiondate FROM dual ) src
   ON ( trg.msisdn = p_msisdn AND trg.cardnumber )
 WHEN NOT MATCHED INSERT ( msisdn, accountnumber, cardnumber, subscriptiondate )
      VALUES ( p_msisdn, p_accountnumber, p_cardnumber, p_subscriptiondate )
 WHEN MATCHED SET ( cardnumber = p_cardnumber, subscriptiondate = p_subscriptiondate)
</code>```

This will do an insert if the row doesn't exist or update an existing row if it does.

Body:
i have a table with 4 columns

1.msisdn
2.accountnumber
3.cardnumber
4.subscriptiondate

I want to add a trigger to this table. If the data i am inserting is

1.99999999
2.2
3.3298572857239
4.(this can be blank)

and the data that is currently in the table is

1.99999999
2.1
3.3298572857239
4.(this can be blank)

Trigger should check if there is this msisdn 99999999 is already having a record with this cardnumber 3298572857239. If there is a record already existing in the table, the trigger should delete the existing entry and insert the new one. The final result should look like this

1.99999999
2.1
3.3298572857239
4.(this can be blank)

I want to keep the value of accountnumber same before and after the trigger. This is what i have tried so far but for this trigger, i am not getting any data in accountnumber column. Please someone help

DROP TRIGGER TRIG_TABLEA;

CREATE OR REPLACE TRIGGER TRIG_TABLEA
BEFORE INSERT ON TABLEA
REFERENCING OLD AS Old NEW AS New
FOR EACH ROW
BEGIN
 :new.accountnumber := :old.accountnumber;
 DELETE FROM TABLEA WHERE MSISDN = :new.MSISDN AND CARDNUMBER = :new.CARDNUMBER;
 :new.MSISDN := :new.MSISDN;
 :new.CARDNUMBER := :new.CARDNUMBER;
 :new.accountnumber := :old.accountnumber;
END;
/

Body:
Don't do a delete-and-insert. You want MERGE. The only thing that can change in your statement is accountnumber and subscriptiondate. You don't say where the data is coming from, so I assume this is a PL/SQL procedure with p_* as the parameters. So you want something like this:

MERGE INTO mytable trg
USING ( SELECT p_accountnumber, p_subscriptiondate FROM dual ) src
   ON ( trg.msisdn = p_msisdn AND trg.cardnumber )
 WHEN NOT MATCHED INSERT ( msisdn, accountnumber, cardnumber, subscriptiondate )
      VALUES ( p_msisdn, p_accountnumber, p_cardnumber, p_subscriptiondate )
 WHEN MATCHED SET ( cardnumber = p_cardnumber, subscriptiondate = p_subscriptiondate)

This will do an insert if the row doesn't exist or update an existing row if it does.


问:
Displaying a to a List from a private void method
I just started developing in Winforms and I'm developing a simple recipe app that allows the user to create a recipe, submit all the details about the recipe, those details will be passed back to a ListBox on the Main form so the user can access that recipe again later. My problem is right now is when I'm finished setting up the recipe to submit, I don't know how to transfer the information back to the ListBox to be stored. I know this has to be a simple answer and I appreciate the help.

Main form code:

```<code>public partial class Main : Form
{
    // Creat the recipeList here and make it public
    public static List<Recipe> recipeList = new List<Recipe>();

    public Main()
    {
        InitializeComponent();
    }

    private void newRecipeButton_Click(object sender, EventArgs e)
    {
        // When the new recipe button is clicked, create a new AddNewRecipeForm object that passed the recipeList.
        var newForm = new AddNewRecipeForm(recipeList);
        newForm.Show();
    }

    private void recipeListBox_SelectedIndexChanged(object sender, EventArgs e)
    {
        // List the New Recipe in the listbox.
    }
}
</code>```

Second form code:

```<code>public partial class AddNewRecipeForm : Form
{
    // Create a private recipeList
    private List<Recipe> recipeList = new List<Recipe>();

    // Once AddNewRecipe is create, it uses the recipeList as the parameters.
    public AddNewRecipeForm(List<Recipe> recipeList)
    {
        InitializeComponent();
    }

    private void submitRecipeButton_Click(object sender, EventArgs e)
    {
        // Create a newRecipe object.
        Recipe newRecipe = new Recipe();

        // Add each entry made in the textboxes to newRecipe object.
        newRecipe.Name = nameTextBox.Text;
        newRecipe.Time = Convert.ToInt32(timeTextBox.Text);
        newRecipe.Servings = Convert.ToInt32(servingsTextBox.Text);
        newRecipe.Directions = directionsTextBox.Text;
        newRecipe.Ingredients = ingredientsTextBox.Text;

        // Add the newRecipe object to the recipeList.
        recipeList.Add(newRecipe);

        // Close the window.
        this.Close();
    }
}
</code>```

答:
```<code>            Main Form:
                  public partial class Main : Form
                {
                    // Creat the recipeList here and make it public
                    public List<Recipe> recipeList = new List<Recipe>();

                    public Main()
                    {
                        InitializeComponent();
                    }

                    private void newRecipeButton_Click(object sender, EventArgs e)
                    {
                        // When the new recipe button is clicked, create a new AddNewRecipeForm object that passed the recipeList.
                        var newForm = new AddNewRecipeForm(recipeList);
                        newForm.Show();
         **recipeList =newForm.ReceiptList;**
    //assign recipeList  values to list box
                    }

                    private void recipeListBox_SelectedIndexChanged(object sender, EventArgs e)
                    {
                        // List the New Recipe in the listbox.
                    }
                }

Second Form:

public partial class AddNewRecipeForm : Form
{
    // Create a private recipeList
    **private List<Recipe> recipeList = new List<Recipe>();
public List<Recipe> RecipeList
{
 get { return recipeList; }
 set { recipeList = value; }
}**

    // Once AddNewRecipe is create, it uses the recipeList as the parameters.
    public AddNewRecipeForm(List<Recipe> recipeList)
    {
        InitializeComponent();
    }

    private void submitRecipeButton_Click(object sender, EventArgs e)
    {
        // Create a newRecipe object.
        Recipe newRecipe = new Recipe();

        // Add each entry made in the textboxes to newRecipe object.
        newRecipe.Name = nameTextBox.Text;
        newRecipe.Time = Convert.ToInt32(timeTextBox.Text);
        newRecipe.Servings = Convert.ToInt32(servingsTextBox.Text);
        newRecipe.Directions = directionsTextBox.Text;
        newRecipe.Ingredients = ingredientsTextBox.Text;

        // Add the newRecipe object to the recipeList.
        recipeList.Add(newRecipe);

        // Close the window.
        this.Close();
    }
}
</code>```

Body:
I just started developing in Winforms and I'm developing a simple recipe app that allows the user to create a recipe, submit all the details about the recipe, those details will be passed back to a ListBox on the Main form so the user can access that recipe again later. My problem is right now is when I'm finished setting up the recipe to submit, I don't know how to transfer the information back to the ListBox to be stored. I know this has to be a simple answer and I appreciate the help.

Main form code:

public partial class Main : Form
{
    // Creat the recipeList here and make it public
    public static List<Recipe> recipeList = new List<Recipe>();

    public Main()
    {
        InitializeComponent();
    }

    private void newRecipeButton_Click(object sender, EventArgs e)
    {
        // When the new recipe button is clicked, create a new AddNewRecipeForm object that passed the recipeList.
        var newForm = new AddNewRecipeForm(recipeList);
        newForm.Show();
    }

    private void recipeListBox_SelectedIndexChanged(object sender, EventArgs e)
    {
        // List the New Recipe in the listbox.
    }
}

Second form code:

public partial class AddNewRecipeForm : Form
{
    // Create a private recipeList
    private List<Recipe> recipeList = new List<Recipe>();

    // Once AddNewRecipe is create, it uses the recipeList as the parameters.
    public AddNewRecipeForm(List<Recipe> recipeList)
    {
        InitializeComponent();
    }

    private void submitRecipeButton_Click(object sender, EventArgs e)
    {
        // Create a newRecipe object.
        Recipe newRecipe = new Recipe();

        // Add each entry made in the textboxes to newRecipe object.
        newRecipe.Name = nameTextBox.Text;
        newRecipe.Time = Convert.ToInt32(timeTextBox.Text);
        newRecipe.Servings = Convert.ToInt32(servingsTextBox.Text);
        newRecipe.Directions = directionsTextBox.Text;
        newRecipe.Ingredients = ingredientsTextBox.Text;

        // Add the newRecipe object to the recipeList.
        recipeList.Add(newRecipe);

        // Close the window.
        this.Close();
    }
}


问:
MySQL: Querying values in relational tables
I have a table called "Music Charts", which is based on a YouTube video and has some general information about the uploader, the duration time, the URL etc. in its structure.

Now I want to save the contained songs. So I create another table named "Song placement" with the "URL" from the "Music Charts" table (as foreign key) and rows with the name "#1", "#2", [...], "#30" with the URL of the single songs.

Eventually, I create a third table called "song_information" to store some values about the producer, the singer and the music company, after defining "URL" from "song placement" as foreign key.

Currently, I don't know if this concept has any mistakes in it. Also I am confused about how to query values using MySQL when using three relational tables.

答:
I think it's better if you keep the song placement as a column in the table where you store the uploader, song duration, URL etc. Lets say you call it songs_table.

Then you create a table for example producers_table. In this table you store only inforamtions about producers, and the songs they produced.

For example this table can have this colums:

ProducerID,ProducerName,ProducerBio,ProducerDob,SongID.

SongID is the foreign key of the table Songs.

Hope this helps.


问:
Making text appear over time with javascript
I am trying to create a simple web page when I ran into a problem that I might need everyone to help me solve. Say I was writing some text in font, and I want
text to appear right under it under 10 seconds. Is this possible? I've tried Google already. It's results weren't so decent.</p>

答:
This can be achieved using CSS animations:

.more {
  animation: fadein 10s steps(1, end);
}

@keyframes fadein {
    from { opacity: 0; }
    to   { opacity: 1; }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>Some text</div>
<div class="more">Some more</div></code>```

Body:
This can be achieved using CSS animations:

.more {
  animation: fadein 10s steps(1, end);
}

@keyframes fadein {
    from { opacity: 0; }
    to   { opacity: 1; }
}

<div>Some text</div>
<div class="more">Some more</div>


问:
How to statically link to TBB?
How can I statically link the intel's TBB libraries to my application?
I know all the caveats such as unfair load distribution of the scheduler, but I don't need the scheduler, just the containers, so it's ok.

Anyways I know this can be done, although its undocumented, however I just can't seem to find the way to do it right now (although I've seen it before somewhere).

So does anyone know or have any clues?

thanks

答:
Although not officially endorsed by the TBB team, it is possible to build your own statically linked version of TBB with make extra_inc=big_iron.inc.

I have not tested it on Windows or MacOS, but on Linux, it worked (source):

```<code>wget https://github.com/01org/tbb/archive/2017_U6.tar.gz
tar xzfv 2017_U6.tar.gz
cd tbb-2017_U6
make extra_inc=big_iron.inc
</code>```

The generated files are in tbb-2017_U6/build/linux*release.

When you link your application to the static TBB version:

Call g++ with the -static switch

Link against tbb (-ltbb) and pthread (-lpthread)

In my test, I also needed to explicitely reference all .o files from the manually build TBB version. Depending on your project, you might also need to pass -pthread to gcc.

I have created a toy example to document all the steps in this Github repository:

tbb-static-linking-tutorial

It also contains test code to make sure that the generated binary is portable on other Linux distributions.

OwnerDisplayName: Robert Gould

Title: How to statically link to TBB?

Body:
Although not officially endorsed by the TBB team, it is possible to build your own statically linked version of TBB with make extra_inc=big_iron.inc.

I have not tested it on Windows or MacOS, but on Linux, it worked (source):

wget https://github.com/01org/tbb/archive/2017_U6.tar.gz
tar xzfv 2017_U6.tar.gz
cd tbb-2017_U6
make extra_inc=big_iron.inc

The generated files are in tbb-2017_U6/build/linux*release.

When you link your application to the static TBB version:

Call g++ with the -static switch

Link against tbb (-ltbb) and pthread (-lpthread)

In my test, I also needed to explicitely reference all .o files from the manually build TBB version. Depending on your project, you might also need to pass -pthread to gcc.

I have created a toy example to document all the steps in this Github repository:

tbb-static-linking-tutorial

It also contains test code to make sure that the generated binary is portable on other Linux distributions.


问:
Single line of || character in Javascript?
I am trying to understand _drawControl function of Fabric.js javascript library, but couldn't figure it out 2 lines of this, because they don't look like functions and not conditional if, so what's the purpose here?

Line 1:

```<code>isVML() || this.transparentCorners || ctx.clearRect(left, top, size, size);
</code>```

Line 2:

```<code>ctx[methodName + 'Rect'](left, top, size, size);
</code>```

Full function:

```<code>_drawControl: function(control, ctx, methodName, left, top) {
  if (!this.isControlVisible(control)) {
    return;
  }
  var size = this.cornerSize, stroke = !this.transparentCorners && this.cornerStrokeColor;
  switch (this.cornerStyle) {
    case 'circle':
      ctx.beginPath();
      ctx.arc(left + size / 2, top + size / 2, size / 2, 0, 2 * Math.PI, false);
      ctx[methodName]();
      if (stroke) {
        ctx.stroke();
      }
      break;
    default:
      isVML() || this.transparentCorners || ctx.clearRect(left, top, size, size);
      ctx[methodName + 'Rect'](left, top, size, size);
      if (stroke) {
        ctx.strokeRect(left, top, size, size);
      }
  }
}
</code>```

答: The || operator is in this case used for short-circuit evaluation. It starts with executing isVML(), and if that returns a falsy value, it will continue to the next statement (this.transparentCorners) and check the same. When a truthy value is reached, then that value will be returned. In this case the return value is not used.

Body:
I am trying to understand _drawControl function of Fabric.js javascript library, but couldn't figure it out 2 lines of this, because they don't look like functions and not conditional if, so what's the purpose here?

Line 1:

isVML() || this.transparentCorners || ctx.clearRect(left, top, size, size);

Line 2:

ctx[methodName + 'Rect'](left, top, size, size);

Full function:

_drawControl: function(control, ctx, methodName, left, top) {
  if (!this.isControlVisible(control)) {
    return;
  }
  var size = this.cornerSize, stroke = !this.transparentCorners && this.cornerStrokeColor;
  switch (this.cornerStyle) {
    case 'circle':
      ctx.beginPath();
      ctx.arc(left + size / 2, top + size / 2, size / 2, 0, 2 * Math.PI, false);
      ctx[methodName]();
      if (stroke) {
        ctx.stroke();
      }
      break;
    default:
      isVML() || this.transparentCorners || ctx.clearRect(left, top, size, size);
      ctx[methodName + 'Rect'](left, top, size, size);
      if (stroke) {
        ctx.strokeRect(left, top, size, size);
      }
  }
}


问:
How can I pretty-print JSON using Go?
Does anyone know of a simple way to pretty-print JSON output in Go?

I'd like to pretty-print the result of json.Marshal, as well as formatting an existing string of JSON so it's easier to read.

答:
Here is my solution:</p>

```<code>import (
    "bytes"
    "encoding/json"
)

const (
    empty = ""
    tab   = "\t"
)

func PrettyJson(data interface{}) (string, error) {
    buffer := new(bytes.Buffer)
    encoder := json.NewEncoder(buffer)
    encoder.SetIndent(empty, tab)

    err := encoder.Encode(data)
    if err != nil {
       return empty, err
    }
    return buffer.String(), nil
}
</code>```

Title: How can I pretty-print JSON using Go?

Body:
Here is my solution:

import (
    "bytes"
    "encoding/json"
)

const (
    empty = ""
    tab   = "\t"
)

func PrettyJson(data interface{}) (string, error) {
    buffer := new(bytes.Buffer)
    encoder := json.NewEncoder(buffer)
    encoder.SetIndent(empty, tab)

    err := encoder.Encode(data)
    if err != nil {
       return empty, err
    }
    return buffer.String(), nil
}


问:
Golang pointer definition
Guys I have Student struct and I am trying to create Student item as *Student. I get invalid memory address or nil pointer dereference error.

```<code>var newStudent *Student
newStudent.Name = "John"
</code>```

I m creating like that. When I try to set any variable, I am getting same error. What did I wrong?

答:
You need to allocate memory for the Student struct. For example,

```<code>package main

import "fmt"

type Student struct {
    Name string
}

func main() {
    var newStudent *Student

    newStudent = new(Student)
    newStudent.Name = "John"
    fmt.Println(*newStudent)

    newStudent = &Student{}
    newStudent.Name = "Jane"
    fmt.Println(*newStudent)

    newStudent = &Student{Name: "Jill"}
    fmt.Println(*newStudent)
}
</code>```

Output:

```<code>{John}
{Jane}
{Jill}
</code>```

Title: Golang pointer definition

Body:
Guys I have Student struct and I am trying to create Student item as *Student. I get invalid memory address or nil pointer dereference error.

var newStudent *Student
newStudent.Name = "John"

I m creating like that. When I try to set any variable, I am getting same error. What did I wrong?

Body:
You need to allocate memory for the Student struct. For example,

package main

import "fmt"

type Student struct {
    Name string
}

func main() {
    var newStudent *Student

    newStudent = new(Student)
    newStudent.Name = "John"
    fmt.Println(*newStudent)

    newStudent = &Student{}
    newStudent.Name = "Jane"
    fmt.Println(*newStudent)

    newStudent = &Student{Name: "Jill"}
    fmt.Println(*newStudent)
}

Output:

{John}
{Jane}
{Jill}


问:
Center image in a square column
I need to make a few boxes with logo images that are centered. And I tried doing it with padding, just placing an image inside a column, centering it and adding top and bottom padding. But the thing is, I'll have a few of those boxes inside the grid with different size images and that'll end up looking messy. Is there another way for me to do this?

Here's an image of the box I'm trying to make:

And here's the rough outline of my code:

.col-lg-6 {
  background-color: #8dc63f;
  text-align: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
<div class="col-lg-6">
  <img src="http://via.placeholder.com/200x100">
</div></code>```

答:
You can use a relative/absolute position pairing with transition settings as shown in this snippet:

.col-lg-6 {
  background-color: #8dc63f;
  position: relative;
  height: 200px;
}

img {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
<div class="col-lg-6">
  <img src="http://via.placeholder.com/200x100">
</div></code>```

Title: Center image in a square column

Body:
I need to make a few boxes with logo images that are centered. And I tried doing it with padding, just placing an image inside a column, centering it and adding top and bottom padding. But the thing is, I'll have a few of those boxes inside the grid with different size images and that'll end up looking messy. Is there another way for me to do this?

Here's an image of the box I'm trying to make:

And here's the rough outline of my code:

.col-lg-6 {
  background-color: #8dc63f;
  text-align: center;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">

Body:
You can use a relative/absolute position pairing with transition settings as shown in this snippet:

.col-lg-6 {
  background-color: #8dc63f;
  position: relative;
  height: 200px;
}

img {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
<div class="col-lg-6">
  <img src="http://via.placeholder.com/200x100">
</div>


问:
Having a hash map to keep track of elements in another data structure
So sometimes I have a certain ds with certain functionalities which have a get time complexity of O(N)  like a queue, stack, heap, etc..  I use one of these ds in a program which just needs to check whether a certain element is in one of theses ds, but because they have a get complexity of O(N), it is the pitfall in my algorithm.

If memory isn't much of my worries, would it be poor design to have a hashmap which keeps track of the elements in the restricted data structure? Doing this would essentially remove the O(N) restriction and allow it to be O(1).

答:
Having a supplemental hash table is warranted in many situations. However, maintaining a "parallel hash" could become a liability.

The situation that you describe, when you need to check membership quickly, is often modeled with a hash-based set (HashSet<T>, std::unordered_set<T>, and so on, depending on the language). The disadvantage of these structures is that the order of elements is not specified, and that they cannot have duplicates.

Depending on the library, you may have access to data structures that fix these shortcomings. For example, Java offers LinkedHashSet<T> which provides a predictable order of enumeration, and C++ provides std::unordered_multiset<T>, which allows duplicates.


问:
VBA PivotTable Filter when existing
Hi I'm working on VBA in Excel to get my filter worked in the Pivot Table. I put a field in filter section and want to only tick "Account Invoice" and "Manual Match". Here's my code:

```<code>With wsPvtTbl.PivotTables("PivotTable1").PivotFields("Type")
        .PivotItems("Approve").Visible = False
        .PivotItems("Error").Visible = False
        .PivotItems("Interface Validation").Visible = False
        .PivotItems("Invoice Validation").Visible = False
        .PivotItems("Account Invoice").Visible = True
        .PivotItems("Manual Match").Visible = False
    End With
</code>```

The problem comes up because sometimes the source data doesn't contain any "Error" item therefore there will be a bug when goes to ".PivotItems("Error").Visible = False"

Is there a way to fix it? many thanks.

答:
Will this work?

```<code>....
On Error Resume Next
.PivotItems("Error").Visible = False
On Error Goto 0
....
</code>```

On Error Resume Next will tolerate the non-existence of the Pivot Items "Error". So it is hidden if it exists. Afterwards, On Error Goto 0 will re-establish normal error handling so that further errors in the code are not skipped.

Alternatively, you can put those two statements at the beginning and the end of the code snippet, so that any non-existing pivot item wont break the code.

Title: VBA PivotTable Filter when existing

Body:
Hi I'm working on VBA in Excel to get my filter worked in the Pivot Table. I put a field in filter section and want to only tick "Account Invoice" and "Manual Match". Here's my code:

With wsPvtTbl.PivotTables("PivotTable1").PivotFields("Type")
        .PivotItems("Approve").Visible = False
        .PivotItems("Error").Visible = False
        .PivotItems("Interface Validation").Visible = False
        .PivotItems("Invoice Validation").Visible = False
        .PivotItems("Account Invoice").Visible = True
        .PivotItems("Manual Match").Visible = False
    End With

The problem comes up because sometimes the source data doesn't contain any "Error" item therefore there will be a bug when goes to ".PivotItems("Error").Visible = False"

Is there a way to fix it? many thanks.

Body:
Will this work?

....
On Error Resume Next
.PivotItems("Error").Visible = False
On Error Goto 0
....

On Error Resume Next will tolerate the non-existence of the Pivot Items "Error". So it is hidden if it exists. Afterwards, On Error Goto 0 will re-establish normal error handling so that further errors in the code are not skipped.

Alternatively, you can put those two statements at the beginning and the end of the code snippet, so that any non-existing pivot item wont break the code.


问:
How to select an item in a ListView programmatically?
I'm trying to select the first item in a ListView programmatically, but it doesn't appear to have been selected. I am using the following code:

```<code>if (listView1.Items.Count > 0)
    listView1.Items[0].Selected = true;
</code>```

Actually I've had this problem before but I can't remember how I managed to solve it!

答:
```<code>ListViewItem.IsSelected = true;
ListViewItem.Focus();
</code>```

Body:
I'm trying to select the first item in a ListView programmatically, but it doesn't appear to have been selected. I am using the following code:

if (listView1.Items.Count > 0)
    listView1.Items[0].Selected = true;

Actually I've had this problem before but I can't remember how I managed to solve it!


答:
It's quite simple. The first short-circuits and takes the first true argument:

let foo = false || "foo" || "never reached";
console.log(foo); // foo

let bar = "bar" || "never reached" || false;
console.log(bar); // bar```
</div>
</div>
</p>

<p>The second one calls an object's method via bracket notation (using 4 arguments) - it's used to dynamically call a method:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function Foo() {

}

Foo.prototype.bar = function() {
    console.log('bar');
  }

let foo = new Foo();
let variable = 'bar';
foo[variable]();

// same as

foo.bar();</code>```

Title: Single line of || character in Javascript?

Body:
It's quite simple. The first short-circuits and takes the first true argument:

let foo = false || "foo" || "never reached";
console.log(foo); // foo

let bar = "bar" || "never reached" || false;
console.log(bar); // bar

The second one calls an object's method via bracket notation (using 4 arguments) - it's used to dynamically call a method:

function Foo() {

}

Foo.prototype.bar = function() {
    console.log('bar');
  }

let foo = new Foo();
let variable = 'bar';
foo[variable]();

// same as

foo.bar();


问:
Biopython won't run
So I've been trying to work with Biopython and I'm fairly new. My code:

```<code>fasta_string = open("C:\\Users\\saeed\\Desktop\\dna2.fasta").read()
print('1')
result_handle = NCBIWWW.qblast("blastn", "nt", fasta_string)
print('2')

blast_record = NCBIXML.read(result_handle)

len(blast_record.alignments)

E_VALUE_THRESH = 0.01
for alignment in blast_record.alignments:
    for hsp in alignment.hsps:
        if hsp.expect < E_VALUE_THRESH:
            print('*Alignment*')
            print('sequence', alignment.title)
            print('length', alignment.length)
            print(' e value', hsp.expect)
            print(hsp.query)
            print(hsp.match)
            print(hsp.sbjct)
</code>```

Whenever I run this code, It prints 1 and just stops. Not stops as in exits, but keeps running and doesn't print anything else. I tried replacing the dna2.fasta file with just "myseq.fa", but that didn't seem to work either. It just said file does not exist. I want to know what I am doing wrong, and how to fix it. Any help?

答:
Here is my example with multiple queries in one request.

```<code>import timeit # Not necessary; just for timing the blast request.

from Bio.Blast import NCBIWWW
from Bio.Blast import NCBIXML

fasta_string = open("dna2.fasta").read()
# In "dna2.fasta":
# >test1
# CGCTCATGCTAAAACCACGGAGGAATGTTTGGCCTATTTTGGGGTGAGTG
# >test2
# GCCAAGTCTGCAGGAAGCTTTGAGTTCTGACATCCTTAATGACATGGAGT
#
# Or you can make a string for this simple example.
# fasta_string = ">test1\nCGCTCATGCTAAAACCACGGAGGAATGTTTGGCCTATTTTGGGGTGAGTG\n>test2\nGCCAAGTCTGCAGGAAGCTTTGAGTTCTGACATCCTTAATGACATGGAGT\n"
print(fasta_string)

a = timeit.default_timer() # Not necessary; just for timing the blast request.
result_handle = NCBIWWW.qblast("blastn", "nt", fasta_string)
print(timeit.default_timer() - a) # Not necessary; just for timing the blast request.
# This takes me ~ 40 sec in one test.

# Use "parse" instead of "read" because you have lots of results (i.e., multiple query sequences)
blast_records = NCBIXML.parse(result_handle)
for blast_record in blast_records:
    print(blast_record.alignments[0].hsps[0])
</code>```

"cdlane" was correct. You might also want to use the Bio.SeqIO module to read in FASTA file. I'm sure you've read it but just in case, the relevant document is here: http://biopython.org/DIST/docs/tutorial/Tutorial.html#htoc87

Title: Biopython won't run

Body:
So I've been trying to work with Biopython and I'm fairly new. My code:

fasta_string = open("C:\\Users\\saeed\\Desktop\\dna2.fasta").read()
print('1')
result_handle = NCBIWWW.qblast("blastn", "nt", fasta_string)
print('2')

blast_record = NCBIXML.read(result_handle)

len(blast_record.alignments)

E_VALUE_THRESH = 0.01
for alignment in blast_record.alignments:
    for hsp in alignment.hsps:
        if hsp.expect < E_VALUE_THRESH:
            print('*Alignment*')
            print('sequence', alignment.title)
            print('length', alignment.length)
            print(' e value', hsp.expect)
            print(hsp.query)
            print(hsp.match)
            print(hsp.sbjct)

Whenever I run this code, It prints 1 and just stops. Not stops as in exits, but keeps running and doesn't print anything else. I tried replacing the dna2.fasta file with just "myseq.fa", but that didn't seem to work either. It just said file does not exist. I want to know what I am doing wrong, and how to fix it. Any help?

Body:
Here is my example with multiple queries in one request.

import timeit # Not necessary; just for timing the blast request.

from Bio.Blast import NCBIWWW
from Bio.Blast import NCBIXML

fasta_string = open("dna2.fasta").read()
# In "dna2.fasta":
# >test1
# CGCTCATGCTAAAACCACGGAGGAATGTTTGGCCTATTTTGGGGTGAGTG
# >test2
# GCCAAGTCTGCAGGAAGCTTTGAGTTCTGACATCCTTAATGACATGGAGT
#
# Or you can make a string for this simple example.
# fasta_string = ">test1\nCGCTCATGCTAAAACCACGGAGGAATGTTTGGCCTATTTTGGGGTGAGTG\n>test2\nGCCAAGTCTGCAGGAAGCTTTGAGTTCTGACATCCTTAATGACATGGAGT\n"
print(fasta_string)

a = timeit.default_timer() # Not necessary; just for timing the blast request.
result_handle = NCBIWWW.qblast("blastn", "nt", fasta_string)
print(timeit.default_timer() - a) # Not necessary; just for timing the blast request.
# This takes me ~ 40 sec in one test.

# Use "parse" instead of "read" because you have lots of results (i.e., multiple query sequences)
blast_records = NCBIXML.parse(result_handle)
for blast_record in blast_records:
    print(blast_record.alignments[0].hsps[0])

"cdlane" was correct. You might also want to use the Bio.SeqIO module to read in FASTA file. I'm sure you've read it but just in case, the relevant document is here: http://biopython.org/DIST/docs/tutorial/Tutorial.html#htoc87


问:
ASP.NET MVC "System.IndexOutOfRangeException: There is no row at position 0." when trying to get data from the table
```<code>namespace PayrollSystem.Models
{
    public class FormAddEmployee
    {
        public string FirstName { set; get; }
        public string LastName { set; get; }
        public decimal PayRate { set; get; }
        public DateTime StartDate { set; get; }
        public DateTime EndDate { set; get; }

        private string m_connectionString;

        public void Connect(string server, string database)
        {
            m_connectionString = string.Format("Data Source ='{0}'; Initial Catalog = {1}; Integrated Security=SSPI", server, database);
        }

        public void SaveEmployee()
        {
            var commandText = string.Format("INSERT INTO Personnel (FirstName, LastName, PayRate, StartDate, EndDate) VALUES ('{0}', '{1}', {2}, '{3}', '{4}')", FirstName, LastName, PayRate, StartDate, EndDate);

            SQLDataWriter(commandText);
        }

        public void GetEmployeeByLastName(string lastName)
        {
            var commandText = string.Format("SELECT FirstName, LastName, PayRate, StartDate, EndDate FROM Personnel WHERE LastName = '{0}'", LastName);

            var retValue = SQLDataReader(commandText);
            var rec = retValue.Rows[0];
            FirstName = rec.ItemArray[0].ToString();
            LastName = rec.ItemArray[1].ToString();
            PayRate = Convert.ToDecimal(rec.ItemArray[2].ToString());
            StartDate = Convert.ToDateTime(rec.ItemArray[3].ToString());
            EndDate = Convert.ToDateTime(rec.ItemArray[4].ToString());

        }

        public DataTable SQLDataReader(string sqlCmd)
        {
            var dataTable = new DataTable();
            using (var con = new SqlConnection(m_connectionString))
            {
                using (var cmd = new SqlCommand(sqlCmd, con) { CommandTimeout = 500 })
                {
                    var sqlAdapter = new SqlDataAdapter(cmd);
                    sqlAdapter.Fill(dataTable);
                }
            }

            return dataTable;

        }

        public void SQLDataWriter(string sqlCmd)
        {
            using (var con = new SqlConnection(m_connectionString))
            {
                con.Open();
                try
                {
                    using (var command = new SqlCommand(sqlCmd, con))
                    {
                        command.ExecuteNonQuery();
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }
            }
        }

    }

}
</code>```

答:
The query probably doesn't return any data. Might be better to check before accessing it.</p>

```<code>var retValue = SQLDataReader(commandText);

if(retValue.Rows.Count > 0)
{
            var rec = retValue.Rows[0];
            FirstName = rec.ItemArray[0].ToString();
            LastName = rec.ItemArray[1].ToString();
            PayRate = Convert.ToDecimal(rec.ItemArray[2].ToString());
            StartDate = Convert.ToDateTime(rec.ItemArray[3].ToString());
            EndDate = Convert.ToDateTime(rec.ItemArray[4].ToString());
}
</code>```

Body:
The query probably doesn't return any data. Might be better to check before accessing it.

var retValue = SQLDataReader(commandText);

if(retValue.Rows.Count > 0)
{
            var rec = retValue.Rows[0];
            FirstName = rec.ItemArray[0].ToString();
            LastName = rec.ItemArray[1].ToString();
            PayRate = Convert.ToDecimal(rec.ItemArray[2].ToString());
            StartDate = Convert.ToDateTime(rec.ItemArray[3].ToString());
            EndDate = Convert.ToDateTime(rec.ItemArray[4].ToString());
}


问:
I have a h1, and a h3 that I can't vertically center in Foundation 6
I've tried to everything to vertically center my h1 and h3 tag in Foundation 6. I've tried the transform translate, flexbox, and tried multiple examples here on stack over flow, and nothing works. When I use absolute positioning to center the content the, the headings get in the way of the top-bar nav on smaller screens, id there anyway to fix this issue, and Could some give me a hand with this? The h1 tag, and the h3 tag are located in line 48, and 49 of my codepen.
Codepen link</p>

```<code><!doctype html>
<html class="no-js" lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Foundation for Sites</title>
    <link rel="stylesheet" href="css/foundation.css">
    <link rel="stylesheet" href="css/app.css">
  </head>
  <body>
    <div class="off-canvas-wrapper">
            <div class="off-canvas position-left" id="offCanvas" data-off-canvas data-transition="overlap">
                <!-- Close button -->
            <button class="close-button" aria-label="Close menu" type="button" data-close>
        <span aria-hidden="true">×</span>
            </button>
            <ul class="vertical menu">
              <li><a href="#">Home</a></li>
              <li><a href="#">About</a></li>
              <li><a href="#">References</a></li>
              <li><a href="#">Contact</a></li>
            </ul>
            </div><!-- off-canvas menu -->
            <div class="off-canvas-content" data-off-canvas-content>
            <!-- Your page content lives here -->
            <div class="hero-image">
                <div class="expanded header-intro row">
              <button type="button" class="button float-right show-for-medium" data-toggle="offCanvas">Menu</button><!-- Button to open off-canvas menu -->
              <div class="title-bar" data-responsive-toggle="menu" data-hide-for="medium"><!--top bar navigation -->
              <button class="menu-icon" type="button" data-toggle></button>
              <div class="title-bar-title">Menu</div>
              </div>
              <div class="top-bar show-for-small-only" id="menu">
                <div class="top-bar-left">
                <ul class="dropdown vertical menu" data-dropdown-menu>
                    <li class="menu-text">Foundation Framework</li>
                    <li><a href="#">Home</a></li>
                    <li><a href="#">About</a></li>
                    <li><a href="#">Reference</a></li>
                    <li><a href="#">About</a></li>
                </ul>
                </div>
              </div>
                </div>
                <div class="row">
            <div class="small-12 text-center columns">
              <h1>Foundation</h1> <!-- CAN'T VERTICALLY CENTER THIS TAG -->
              <h3>Foundation For Sites</h3> <!-- CAN'T VERTICALLY CENTER THIS TAG -->
            </div>
                </div>
            </div><!-- Eno of hero-image section -->
            </div><!-- off-canvas-content-->
        </div><!-- off-canvas wrapper-->
    <script src="js/vendor/jquery.js"></script>
    <script src="js/vendor/what-input.js"></script>
    <script src="js/vendor/foundation.js"></script>
    <script src="js/app.js"></script>
  </body>
</html>
</code>```

答:
you can use flexbox; you need to set a height to your flexbox container to see the centered title

here an example : https://codepen.io/anon/pen/YQPPaM

$(document).foundation();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.hero-image {
 background: url(https://www.freewebheaders.com/wordpress/wp-content/gallery/mountains-snow/mountains-snow-header-7050.jpg);
 background-position: center center;
 background-repeat: no-repeat;
 background-size: cover;
 padding-bottom: 25%;

}
.container{
  height : 100vh;
  display: flex;
  flex-direction : column;
  justify-content : center;
  align-items : center;

}</code>```

    <meta charset="utf-8">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Foundation for Sites</title>
    <link rel="stylesheet" href="css/foundation.css">
    <link rel="stylesheet" href="css/app.css">

      <button class="close-button" aria-label="Close menu" type="button" data-close>
       ×
      </button>

Home

About

References

Contact

           <button type="button" class="button float-right show-for-medium" data-toggle="offCanvas">Menu</button>

              <button class="menu-icon" type="button" data-toggle></button>

Menu

Foundation Framework

Home

About

Reference

About

Foundation

Foundation For Sites

```

Body:
I've tried to everything to vertically center my h1 and h3 tag in Foundation 6. I've tried the transform translate, flexbox, and tried multiple examples here on stack over flow, and nothing works. When I use absolute positioning to center the content the, the headings get in the way of the top-bar nav on smaller screens, id there anyway to fix this issue, and Could some give me a hand with this? The h1 tag, and the h3 tag are located in line 48, and 49 of my codepen.
Codepen link

<!doctype html>

    <meta charset="utf-8">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Foundation for Sites</title>
    <link rel="stylesheet" href="css/foundation.css">
    <link rel="stylesheet" href="css/app.css">

            <button class="close-button" aria-label="Close menu" type="button" data-close>
        ×
            </button>

Home

About

References

Contact

              <button type="button" class="button float-right show-for-medium" data-toggle="offCanvas">Menu</button>

              <button class="menu-icon" type="button" data-toggle></button>

Menu

Foundation Framework

Home

About

Reference

About

Foundation

Foundation For Sites

Body:
you can use flexbox; you need to set a height to your flexbox container to see the centered title

here an example : https://codepen.io/anon/pen/YQPPaM

$(document).foundation();

.hero-image {
 background: url(https://www.freewebheaders.com/wordpress/wp-content/gallery/mountains-snow/mountains-snow-header-7050.jpg);
 background-position: center center;
 background-repeat: no-repeat;
 background-size: cover;
 padding-bottom: 25%;

}
.container{
  height : 100vh;
  display: flex;
  flex-direction : column;
  justify-content : center;
  align-items : center;

}

<html class="no-js" lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Foundation for Sites</title>
    <link rel="stylesheet" href="css/foundation.css">
    <link rel="stylesheet" href="css/app.css">
  </head>
  <body>
    <div class="off-canvas-wrapper">
   <div class="off-canvas position-left" id="offCanvas" data-off-canvas data-transition="overlap">
    <!-- Close button -->
      <button class="close-button" aria-label="Close menu" type="button" data-close>
       <span aria-hidden="true">&times;</span>
      </button>
     <ul class="vertical menu">
       <li><a href="#">Home</a></li>
       <li><a href="#">About</a></li>
       <li><a href="#">References</a></li>
       <li><a href="#">Contact</a></li>
     </ul>
   </div><!-- off-canvas menu -->
   <div class="off-canvas-content" data-off-canvas-content>
     <!-- Your page content lives here -->
     <div class="hero-image">
      <div class="expanded header-intro row">
           <button type="button" class="button float-right show-for-medium" data-toggle="offCanvas">Menu</button><!-- Button to open off-canvas menu -->
           <div class="title-bar" data-responsive-toggle="menu" data-hide-for="medium"><!--top bar navigation -->
              <button class="menu-icon" type="button" data-toggle></button>
              <div class="title-bar-title">Menu</div>
           </div>
           <div class="top-bar show-for-small-only" id="menu">
             <div class="top-bar-left">
                <ul class="dropdown vertical menu" data-dropdown-menu>
                 <li class="menu-text">Foundation Framework</li>
                 <li><a href="#">Home</a></li>
                 <li><a href="#">About</a></li>
                 <li><a href="#">Reference</a></li>
                 <li><a href="#">About</a></li>
                </ul>
             </div>
           </div>
      </div>
      <div class="row">
            <div class="small-12 text-center columns container">
              <h1>Foundation</h1> <!-- like the h1 centered vertically -->
              <h3>Foundation For Sites</h3> <!-- like to have the h3 centered vertically -->
            </div>
      </div>
     </div><!-- Eno of hero-image section -->
   </div><!-- off-canvas-content-->
  </div><!-- off-canvas wrapper-->
    <script src="js/vendor/jquery.js"></script>
    <script src="js/vendor/what-input.js"></script>
    <script src="js/vendor/foundation.js"></script>
    <script src="js/app.js"></script>
  </body>
</html>


问:
How do you get the "images" from a twitter feed to show in an iOS app
I have a code that accesses a Twitter feed and puts the text into a table. I then edited the code so I could display the text in my custom fashion in separate views, but I wanted to grab images from the tweets as well, and despite over an hour searching could not find a single reference. I have seen how to "Post" images, but to be clear, I need to get and "display" the images from the tweet in question.

Here are the highlights from my code that handles the Twitter Access:

```<code>-(void)twitterTimeLine
{
    ACAccountStore *account = [[ACAccountStore alloc] init];

    ACAccountType *accountType = [account accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];

    [account requestAccessToAccountsWithType:accountType options:nil completion:^(BOOL granted, NSError *error) {
        if (granted == YES)
        {
            NSArray *arrayOfAccounts = [account accountsWithAccountType:accountType];

            if ([arrayOfAccounts count] > 0)
            {
                ACAccount *twitterAccount = [arrayOfAccounts lastObject];   // last account on list of accounts
                NSURL *requestAPI = [NSURL URLWithString:@"https://api.twitter.com/1.1/statuses/user_timeline.json"];

                NSMutableDictionary *parameters = [[NSMutableDictionary alloc] init];

                [parameters setObject:@"30" forKey:@"count"];

                [parameters setObject:@"1" forKey:@"incude_entities"];

                SLRequest *posts = [SLRequest requestForServiceType:SLServiceTypeTwitter requestMethod:SLRequestMethodGET URL:requestAPI parameters:parameters];

                posts.account = twitterAccount;

                [posts performRequestWithHandler:^(NSData *response, NSHTTPURLResponse *urlResponse, NSError *error) {
                    if (response)
                    {
                        // TODO: might want to check urlResponse.statusCode to stop early
                        NSError *jsonError;  // use new instance here, you don't want to overwrite the error you got from the SLRequest
                        NSArray *array =[NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&jsonError];
                        if (array) {
                            if ([array isKindOfClass:[NSArray class]]) {
                                self.array = array;
                                NSLog(@"resulted array: %@",self.array);
                            }
                            else {
                                // This should never happen
                                NSLog(@"Not an array! %@ - %@", NSStringFromClass([array class]), array);
                            }
                        }
                        else {
                            // TODO: Handle error in release version, don't just dump out this information
                            NSLog(@"JSON Error %@", jsonError);
                            NSString *dataString = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
                            NSLog(@"Received data: %@", dataString ? dataString : response);    // print string representation if response is a string, or print the raw data object
                        }
                    }
                    else {
                        // TODO: show error information to user if request failed
                        NSLog(@"request failed %@", error);
                    }

                    self.array = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&error];

                    if (self.array.count != 0)
                    {
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [self.tableView reloadData];    // this part loads into table - important!
                        });

                    }
                }];
            }
        }
        else
        {
            NSLog(@"%@", [error localizedDescription]);
        }

    }];
}
</code>```

and here is how I display the Tweet

```<code>-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellID = @"cellID";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];

    if (cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
    }

    NSDictionary *tweet = _array[indexPath.row];

    cell.textLabel.text = tweet[@"text"];
    //NSString *element = [myArray objectAtIndex:2];
    //NSString *element = myArray[2];

// I created some custom views to show the text, but kept the table for testing purposes
    TemplateView *tempView = [viewArray objectAtIndex:testCounter];
    tempView.TweetView.text = tweet[@"text"];
    // -> this was what I was hoping for // tempView.ContentView.image = tweet[@"image"];
    testCounter++;
    if (testCounter >= 30)
    {
        testCounter = 0;
    }

    return cell;
}
</code>```

I took out the key lines that I think is where I need to look:

```<code>tempView.TweetView.text = tweet[@"text"];
tempView.ContentView.image = tweet[@"image"];
</code>```

// hoping that the latter would work as the first one does, but clearly it's not that simple

This might not be possible, if so, how would I get the images from the "link" (url) and make sure it is an image and not a video or other website?

I could set up a "word search" to grab text starting with http from the tweet and hopefully generate a URL from the string

答:
TwitterKit doesn't seem to support images publicly.. I'm having the same stupid issue. The API internally holds images when using the built in tableview and datasource.. It requires a listID and a Slug.. However, when you want the images via JSON, you are out of luck! Even TWTRTweet object doesn't have entities or media properties!

Not sure how anyone can develop such an awful API.. In any case, I reversed the server calls made internally and found that it sends other "undocumented" parameters..

Example:

```<code>TWTRAPIClient *client = [[TWTRAPIClient alloc] init];

NSString *endpoint = @"https://api.twitter.com/1.1/statuses/user_timeline.json";

NSDictionary *params = @{@"screen_name":@"SCREEN_NAME_HERE",
                             @"count": @"30"};
</code>```

will return NO MEDIA.. even if you have @"include_entities" : @"true".

Solution:

```<code>TWTRAPIClient *client = [[TWTRAPIClient alloc] init];

NSString *endpoint = @"https://api.twitter.com/1.1/statuses/user_timeline.json";

NSDictionary *params = @{@"screen_name":@"SCREEN_NAME_HERE",
                         @"count": @"30",
                         @"tweet_mode": @"extended"};
</code>```

With tweet_mode set to extended (tweet_mode is an undocumented parameter), it will now return the media as part of the response.. This includes the "type" which is "photo" for images.

Body:
I have a code that accesses a Twitter feed and puts the text into a table. I then edited the code so I could display the text in my custom fashion in separate views, but I wanted to grab images from the tweets as well, and despite over an hour searching could not find a single reference. I have seen how to "Post" images, but to be clear, I need to get and "display" the images from the tweet in question.

Here are the highlights from my code that handles the Twitter Access:

-(void)twitterTimeLine
{
    ACAccountStore *account = [[ACAccountStore alloc] init];

    ACAccountType *accountType = [account accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];

    [account requestAccessToAccountsWithType:accountType options:nil completion:^(BOOL granted, NSError *error) {
        if (granted == YES)
        {
            NSArray *arrayOfAccounts = [account accountsWithAccountType:accountType];

            if ([arrayOfAccounts count] > 0)
            {
                ACAccount *twitterAccount = [arrayOfAccounts lastObject];   // last account on list of accounts
                NSURL *requestAPI = [NSURL URLWithString:@"https://api.twitter.com/1.1/statuses/user_timeline.json"];

                NSMutableDictionary *parameters = [[NSMutableDictionary alloc] init];

                [parameters setObject:@"30" forKey:@"count"];

                [parameters setObject:@"1" forKey:@"incude_entities"];

                SLRequest *posts = [SLRequest requestForServiceType:SLServiceTypeTwitter requestMethod:SLRequestMethodGET URL:requestAPI parameters:parameters];

                posts.account = twitterAccount;

                [posts performRequestWithHandler:^(NSData *response, NSHTTPURLResponse *urlResponse, NSError *error) {
                    if (response)
                    {
                        // TODO: might want to check urlResponse.statusCode to stop early
                        NSError *jsonError;  // use new instance here, you don't want to overwrite the error you got from the SLRequest
                        NSArray *array =[NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&jsonError];
                        if (array) {
                            if ([array isKindOfClass:[NSArray class]]) {
                                self.array = array;
                                NSLog(@"resulted array: %@",self.array);
                            }
                            else {
                                // This should never happen
                                NSLog(@"Not an array! %@ - %@", NSStringFromClass([array class]), array);
                            }
                        }
                        else {
                            // TODO: Handle error in release version, don't just dump out this information
                            NSLog(@"JSON Error %@", jsonError);
                            NSString *dataString = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
                            NSLog(@"Received data: %@", dataString ? dataString : response);    // print string representation if response is a string, or print the raw data object
                        }
                    }
                    else {
                        // TODO: show error information to user if request failed
                        NSLog(@"request failed %@", error);
                    }

                    self.array = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&error];

                    if (self.array.count != 0)
                    {
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [self.tableView reloadData];    // this part loads into table - important!
                        });

                    }
                }];
            }
        }
        else
        {
            NSLog(@"%@", [error localizedDescription]);
        }

    }];
}

and here is how I display the Tweet

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellID = @"cellID";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];

    if (cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
    }

    NSDictionary *tweet = _array[indexPath.row];

    cell.textLabel.text = tweet[@"text"];
    //NSString *element = [myArray objectAtIndex:2];
    //NSString *element = myArray[2];

// I created some custom views to show the text, but kept the table for testing purposes
    TemplateView *tempView = [viewArray objectAtIndex:testCounter];
    tempView.TweetView.text = tweet[@"text"];
    // -> this was what I was hoping for // tempView.ContentView.image = tweet[@"image"];
    testCounter++;
    if (testCounter >= 30)
    {
        testCounter = 0;
    }

    return cell;
}

I took out the key lines that I think is where I need to look:

tempView.TweetView.text = tweet[@"text"];
tempView.ContentView.image = tweet[@"image"];

// hoping that the latter would work as the first one does, but clearly it's not that simple

This might not be possible, if so, how would I get the images from the "link" (url) and make sure it is an image and not a video or other website?

I could set up a "word search" to grab text starting with http from the tweet and hopefully generate a URL from the string

Body:
TwitterKit doesn't seem to support images publicly.. I'm having the same stupid issue. The API internally holds images when using the built in tableview and datasource.. It requires a listID and a Slug.. However, when you want the images via JSON, you are out of luck! Even TWTRTweet object doesn't have entities or media properties!

Not sure how anyone can develop such an awful API.. In any case, I reversed the server calls made internally and found that it sends other "undocumented" parameters..

Example:

TWTRAPIClient *client = [[TWTRAPIClient alloc] init];

NSString *endpoint = @"https://api.twitter.com/1.1/statuses/user_timeline.json";

NSDictionary *params = @{@"screen_name":@"SCREEN_NAME_HERE",
                             @"count": @"30"};

will return NO MEDIA.. even if you have @"include_entities" : @"true".

Solution:

TWTRAPIClient *client = [[TWTRAPIClient alloc] init];

NSString *endpoint = @"https://api.twitter.com/1.1/statuses/user_timeline.json";

NSDictionary *params = @{@"screen_name":@"SCREEN_NAME_HERE",
                         @"count": @"30",
                         @"tweet_mode": @"extended"};

With tweet_mode set to extended (tweet_mode is an undocumented parameter), it will now return the media as part of the response.. This includes the "type" which is "photo" for images.


问:
Why does pressing CTRL+C or CTRL+X capitalize the letter instead of exit or their normal EXIT in Raspbian Jessie Lite
I am using the most recent version of Raspbian Jessie.

I'm in the terminal but the CTRL+X to exit a PING command for example doesn't work.

Is it because I changed my locale to en_US.UTF-8? Just a guess.

CTRL + SHIFT + X doesn't work

CTRL + ALT + SHIFT doesn't work either

答:
I've never known ping on GNU/Linux distros to respond to CTRL+X.

Maybe you are thinking of one of the following typical signal generating CTRL inputs:

CTRL+C = SIGINT (terminates ping and prints final statistics)

CTRL+Z
= SIGSTP (stops the ping and allows it to be resumed)

CTRL+\ = SIGQUIT (this one makes ping print out the running statistics)

If you really think something is off, you could check out your keyboard configuration. The config is in /etc/default/keyboard.


问:
Reset printer cache to force Chrome browser to select OS default printer
Initially i changed default printer to some other, then opened the chrome in Kiosk printing when i hit ctrl+P chrome is still sending print request to previously selected default printer.

Is there any way to force the chrome to use system default printer rather from recent destination?

答:
I've been looking in to this issue too.  It's unfortunate and a bit strange that Google has not been giving it much attention... I would think that it would affect a large number of users.

The best workaround I've seen after reading on it some is to use the system print dialog instead of Chrome's print dialog.  From Chrome, you can do this either by hitting Shift-Ctrl-P (in Windows), or by selecting the system print dialog at the bottom of Chrome's print dialog.

A better solution (i.e. a bug fix) would be nice, but, ...

I just sent the following bug report to the Chrome folks using the Chrome Help -> Report an Issue dialog.  (Of course it tells you not to expect any response...)

Print uses the last used printer as the default, instead of the system default printer.

Windows 10
Chrome 58.0.3029.110 (64-bit)

Normal behavior should be to always revert to the system default printer instead of the last used printer.  There are several forum threads (even on the google chrome forum!) of folks lamenting the current behavior, planning to switch to Firefox where the default printer is actually the default printer.  Interesting threads:

https://bugs.chromium.org/p/chromium/issues/detail?id=431098 (merged into the following issue)

https://bugs.chromium.org/p/chromium/issues/detail?id=254428 (last user marked this as resolved but it actually persists)

https://bugs.chromium.org/p/chromium/issues/detail?id=454258 (not sure what the outcome is here; it has been idle for almost a year)

https://productforums.google.com/forum/#!topic/chrome/qCFCE3xi7SA (see the next to last entry from Terry@LanZone, 11/19/12)


问:
Unexpected Thrust error in simple program
Using Visual Studio 2017 and the Thrust library, I compiled the following program:

```<code>#include <thrust/iterator/counting_iterator.h>
#include <thrust/iterator/transform_iterator.h>

template<int c>
struct computes_mod
{
    auto operator()(int i) const
    {
        return i % c;
    }
};

int main()
{
    auto ti = thrust::make_transform_iterator(thrust::make_counting_iterator(0), computes_mod<3>{});

    return 0;
}
</code>```

However, I get the following compiler errors:

C2027 use of undefined type 'thrust::detail::result_of_adaptable_function'

  C3646 'type': unknown override specifier

  C4430 missing type specifier - int assumed. Note: C++ does not support default-int

whose details are given as

```<code>1>main.cpp
1>c:\program files\nvidia gpu computing toolkit\cuda\v8.0\include\thrust\detail\type_traits.h(440): error C2027: use of undefined type 'thrust::detail::result_of_adaptable_function<UnaryFunc (int),void>'
1>        with
1>        [
1>            UnaryFunc=computes_mod<3>
1>        ]
1>c:\program files\nvidia gpu computing toolkit\cuda\v8.0\include\thrust\iterator\detail\transform_iterator.inl(40): note: see declaration of 'thrust::detail::result_of_adaptable_function<UnaryFunc (int),void>'
1>        with
1>        [
1>            UnaryFunc=computes_mod<3>
1>        ]
1>c:\program files\nvidia gpu computing toolkit\cuda\v8.0\include\thrust\iterator\detail\iterator_adaptor_base.h(53): note: see reference to class template instantiation 'thrust::detail::eval_if<true,DefaultNullaryFn,thrust::detail::identity_<System>>' being compiled
1>        with
1>        [
1>            DefaultNullaryFn=thrust::detail::result_of_adaptable_function<computes_mod<3> (int),void>,
1>            System=thrust::use_default
1>        ]
1>c:\program files\nvidia gpu computing toolkit\cuda\v8.0\include\thrust\iterator\detail\transform_iterator.inl(41): note: see reference to class template instantiation 'thrust::detail::ia_dflt_help<Reference,thrust::detail::result_of_adaptable_function<UnaryFunc (int),void>>' being compiled
1>        with
1>        [
1>            Reference=thrust::use_default,
1>            UnaryFunc=computes_mod<3>
1>        ]
1>c:\program files\nvidia gpu computing toolkit\cuda\v8.0\include\thrust\iterator\transform_iterator.h(191): note: see reference to class template instantiation 'thrust::detail::transform_iterator_base<AdaptableUnaryFunction,Iterator,Reference,Value>' being compiled
1>        with
1>        [
1>            AdaptableUnaryFunction=computes_mod<3>,
1>            Iterator=thrust::counting_iterator<int,thrust::use_default,thrust::use_default,thrust::use_default>,
1>            Reference=thrust::use_default,
1>            Value=thrust::use_default
1>        ]
1>[my_project]\main.cpp(32): note: see reference to class template instantiation 'thrust::transform_iterator<computes_mod<3>,thrust::counting_iterator<int,thrust::use_default,thrust::use_default,thrust::use_default>,thrust::use_default,thrust::use_default>' being compiled
1>c:\program files\nvidia gpu computing toolkit\cuda\v8.0\include\thrust\detail\type_traits.h(440): error C3646: 'type': unknown override specifier
1>c:\program files\nvidia gpu computing toolkit\cuda\v8.0\include\thrust\detail\type_traits.h(440): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
</code>```

I am not sure why the compiler would report that the Thrust type is undefined or why my code causes an error to begin with. This looks to me like a standard usage of thrust::make_transform_iterator.

Why is this error produced and how can I fix it?

Also, in case it is important, I compiled with the flags

```<code>/DTHRUST_DEVICE_SYSTEM=THRUST_DEVICE_SYSTEM_CPP /std:c++latest
</code>```

Thank you for the help!

Update: the test program above compiles successfully using Clang. The problem thus appears to be related to VC++ specifically.

答:
You have to include an header that defines the type result_of_adaptable_function

A line like

```<code>#include <thrust/detail/type_traits/result_of_adaptable_function.h>
</code>```

should make the trick.

You are missing the proper includes to make it work.

Body:
Using Visual Studio 2017 and the Thrust library, I compiled the following program:

#include <thrust/iterator/counting_iterator.h>
#include <thrust/iterator/transform_iterator.h>

template<int c>
struct computes_mod
{
    auto operator()(int i) const
    {
        return i % c;
    }
};

int main()
{
    auto ti = thrust::make_transform_iterator(thrust::make_counting_iterator(0), computes_mod<3>{});

    return 0;
}

However, I get the following compiler errors:

C2027 use of undefined type 'thrust::detail::result_of_adaptable_function'

  C3646 'type': unknown override specifier

  C4430 missing type specifier - int assumed. Note: C++ does not support default-int

whose details are given as

1>main.cpp
1>c:\program files\nvidia gpu computing toolkit\cuda\v8.0\include\thrust\detail\type_traits.h(440): error C2027: use of undefined type 'thrust::detail::result_of_adaptable_function<UnaryFunc (int),void>'
1>        with
1>        [
1>            UnaryFunc=computes_mod<3>
1>        ]
1>c:\program files\nvidia gpu computing toolkit\cuda\v8.0\include\thrust\iterator\detail\transform_iterator.inl(40): note: see declaration of 'thrust::detail::result_of_adaptable_function<UnaryFunc (int),void>'
1>        with
1>        [
1>            UnaryFunc=computes_mod<3>
1>        ]
1>c:\program files\nvidia gpu computing toolkit\cuda\v8.0\include\thrust\iterator\detail\iterator_adaptor_base.h(53): note: see reference to class template instantiation 'thrust::detail::eval_if<true,DefaultNullaryFn,thrust::detail::identity_<System>>' being compiled
1>        with
1>        [
1>            DefaultNullaryFn=thrust::detail::result_of_adaptable_function<computes_mod<3> (int),void>,
1>            System=thrust::use_default
1>        ]
1>c:\program files\nvidia gpu computing toolkit\cuda\v8.0\include\thrust\iterator\detail\transform_iterator.inl(41): note: see reference to class template instantiation 'thrust::detail::ia_dflt_help<Reference,thrust::detail::result_of_adaptable_function<UnaryFunc (int),void>>' being compiled
1>        with
1>        [
1>            Reference=thrust::use_default,
1>            UnaryFunc=computes_mod<3>
1>        ]
1>c:\program files\nvidia gpu computing toolkit\cuda\v8.0\include\thrust\iterator\transform_iterator.h(191): note: see reference to class template instantiation 'thrust::detail::transform_iterator_base<AdaptableUnaryFunction,Iterator,Reference,Value>' being compiled
1>        with
1>        [
1>            AdaptableUnaryFunction=computes_mod<3>,
1>            Iterator=thrust::counting_iterator<int,thrust::use_default,thrust::use_default,thrust::use_default>,
1>            Reference=thrust::use_default,
1>            Value=thrust::use_default
1>        ]
1>[my_project]\main.cpp(32): note: see reference to class template instantiation 'thrust::transform_iterator<computes_mod<3>,thrust::counting_iterator<int,thrust::use_default,thrust::use_default,thrust::use_default>,thrust::use_default,thrust::use_default>' being compiled
1>c:\program files\nvidia gpu computing toolkit\cuda\v8.0\include\thrust\detail\type_traits.h(440): error C3646: 'type': unknown override specifier
1>c:\program files\nvidia gpu computing toolkit\cuda\v8.0\include\thrust\detail\type_traits.h(440): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int

I am not sure why the compiler would report that the Thrust type is undefined or why my code causes an error to begin with. This looks to me like a standard usage of thrust::make_transform_iterator.

Why is this error produced and how can I fix it?

Also, in case it is important, I compiled with the flags

/DTHRUST_DEVICE_SYSTEM=THRUST_DEVICE_SYSTEM_CPP /std:c++latest

Thank you for the help!

Update: the test program above compiles successfully using Clang. The problem thus appears to be related to VC++ specifically.

Body:
You have to include an header that defines the type result_of_adaptable_function

A line like

#include <thrust/detail/type_traits/result_of_adaptable_function.h>

should make the trick.

You are missing the proper includes to make it work.


问:
Item count should be 10 but is 0
the items.count should be atlease 10. I have 10 subfolders (Release 1 ..... Release 10) with in this documnent library "Auto Cad" and each subfolder has a file called license.txt. hmmm
Why this is not returning any file(s)?</p>

```<code>private void btnGetFileGuid_Click(object sender, EventArgs e)
{

using (SPSite site = new SPSite("https://www.abc.com/sites/Software"))
 {
 using (SPWeb web = site.OpenWeb())
 {
  SPList spList = web.Lists["Auto Cad"];
  string fileName = "license.txt";
  SPQuery query = new SPQuery();
  query.Query="<Where><Eq><FieldRef Name='FileLeafRef' /><Value Type='Text'>" + fileName + "</Value></Eq></Where>";
  SPListItemCollection items = spList.GetItems(query);
  if (items.Count > 0)
   {
    Guid id = items[0].UniqueId;
    lblGuid.Text = id.ToString();
   }
  }
 }
}
</code>```

答:
```<code>query.Query="" + fileName + "";
</code>```

This line is wrong. This should be CAML query and not name of filename.

Title: Item count should be 10 but is 0

Body:
the items.count should be atlease 10. I have 10 subfolders (Release 1 ..... Release 10) with in this documnent library "Auto Cad" and each subfolder has a file called license.txt. hmmm
Why this is not returning any file(s)?

private void btnGetFileGuid_Click(object sender, EventArgs e)
{

using (SPSite site = new SPSite("https://www.abc.com/sites/Software"))
 {
 using (SPWeb web = site.OpenWeb())
 {
  SPList spList = web.Lists["Auto Cad"];
  string fileName = "license.txt";
  SPQuery query = new SPQuery();
  query.Query="<Where><Eq><FieldRef Name='FileLeafRef' /><Value Type='Text'>" + fileName + "</Value></Eq></Where>";
  SPListItemCollection items = spList.GetItems(query);
  if (items.Count > 0)
   {
    Guid id = items[0].UniqueId;
    lblGuid.Text = id.ToString();
   }
  }
 }
}

Body:
query.Query="" + fileName + "";

This line is wrong. This should be CAML query and not name of filename.


答:
First off, you should be using parameterized commands to protect yourself from sql injection... In this instance you are indexing into the Rows collection without checking if there are any values in Rows.

Do this instead:

```<code>if(retValue.Rows.Count > 0)
{
    var rec = retValue.Rows[0];
}
</code>```

Title: ASP.NET MVC "System.IndexOutOfRangeException: There is no row at position 0." when trying to get data from the table

Body:
namespace PayrollSystem.Models
{
    public class FormAddEmployee
    {
        public string FirstName { set; get; }
        public string LastName { set; get; }
        public decimal PayRate { set; get; }
        public DateTime StartDate { set; get; }
        public DateTime EndDate { set; get; }

        private string m_connectionString;

        public void Connect(string server, string database)
        {
            m_connectionString = string.Format("Data Source ='{0}'; Initial Catalog = {1}; Integrated Security=SSPI", server, database);
        }

        public void SaveEmployee()
        {
            var commandText = string.Format("INSERT INTO Personnel (FirstName, LastName, PayRate, StartDate, EndDate) VALUES ('{0}', '{1}', {2}, '{3}', '{4}')", FirstName, LastName, PayRate, StartDate, EndDate);

            SQLDataWriter(commandText);
        }

        public void GetEmployeeByLastName(string lastName)
        {
            var commandText = string.Format("SELECT FirstName, LastName, PayRate, StartDate, EndDate FROM Personnel WHERE LastName = '{0}'", LastName);

            var retValue = SQLDataReader(commandText);
            var rec = retValue.Rows[0];
            FirstName = rec.ItemArray[0].ToString();
            LastName = rec.ItemArray[1].ToString();
            PayRate = Convert.ToDecimal(rec.ItemArray[2].ToString());
            StartDate = Convert.ToDateTime(rec.ItemArray[3].ToString());
            EndDate = Convert.ToDateTime(rec.ItemArray[4].ToString());

        }

        public DataTable SQLDataReader(string sqlCmd)
        {
            var dataTable = new DataTable();
            using (var con = new SqlConnection(m_connectionString))
            {
                using (var cmd = new SqlCommand(sqlCmd, con) { CommandTimeout = 500 })
                {
                    var sqlAdapter = new SqlDataAdapter(cmd);
                    sqlAdapter.Fill(dataTable);
                }
            }

            return dataTable;

        }

        public void SQLDataWriter(string sqlCmd)
        {
            using (var con = new SqlConnection(m_connectionString))
            {
                con.Open();
                try
                {
                    using (var command = new SqlCommand(sqlCmd, con))
                    {
                        command.ExecuteNonQuery();
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }
            }
        }

    }

}

Body:
First off, you should be using parameterized commands to protect yourself from sql injection... In this instance you are indexing into the Rows collection without checking if there are any values in Rows.

Do this instead:

if(retValue.Rows.Count > 0)
{
    var rec = retValue.Rows[0];
}


问:
What measurement do you use in your development process to determine *Doneness* of your software?
I just finished listening to a very eye-opening podcast on Hanselminutes about the definition of "Done". So my question to everyone is "When do you consider a piece of software to be "Done"? Is it when it's fully unit tested? Is it when it's completely documented? What measurement do you use in your development process to determine Doneness of your software?

答:
When they client(1) considers it done, it's checked in, backed up, and documented.

Also: "done" rarely exists in web dev.

(1) where client may be an internal PM or such

OwnerDisplayName: Micah

OwnerDisplayName: annakata