问:
For Loop Not Executing Properly wrapped around Try/Except
I have a function that looks like this:

```<code>def get_users(yaml_file="AD_Users.yml"):
with open(yaml_file, 'r') as stream:
    try:
        data = yaml.load(stream)
    except yaml.YAMLError as exc:
        print(exc)
return data.itervalues()

 def create_user_in_ad(new_users): #username, password, base_dn, fname, lname, domain):
    # LDAP connection
    for new_user in new_users:
        try:
            logging.info('Connecting to LDAP Server %s ' % LDAP_SERVER)
            ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, 0)
            ldap_connection = ldap.initialize(LDAP_SERVER)
            ldap_connection.simple_bind_s(BIND_DN, BIND_PASS)
            print "Connected to LDAP Server!"
        except ldap.LDAPError, error_message:
            print "Error connecting to LDAP server: %s" % error_message
            #logging.info('Unable to connect to LDAP Server %s ' % LDAP_SERVER)
            return False
#           sys.exit(1)

      # Check and see if user exists
        try:
            print new_user['username']
            logging.info('Querying AD for user: %s ' % new_user['username'])
            user_results = ldap_connection.search_s(BASE_DN, ldap.SCOPE_SUBTREE,
                                                  '(&(sAMAccountName=' +
                                                  new_user['username'] +
                                                  ')(objectClass=person))',
                                                  ['distinguishedName'])
            print user_results
        except ldap.LDAPError, error_message:
            print "Error finding username: %s" % error_message
            logging.info('Unable to query for user: %s ' % new_user['username'])
            return False

      # Check the results
        if len(user_results) != 0:
            print "User", new_user['username'], "already exists in AD:"
            return False
            sys.exit(1)

      # Lets build our user: Disabled to start (514)
        USER_DN = 'cn=' + new_user['fname'] + ' ' + new_user['lname'] + ',' + BASE_DN
        GROUP_DN = 'ou=' + new_user['group_dn'] + ',' + BASE_DN
        user_attrs = {}
        user_attrs['objectClass'] = \
                    ['top', 'person', 'organizationalPerson', 'user']
        user_attrs['cn'] = new_user['fname'] + ' ' + new_user['lname']
        user_attrs['userPrincipalName'] = new_user['username'] + '@' + new_user['domain']

      # Add the new user account
        try:
            ldap_connection.add_s(USER_DN, user_ldif)
            logging.info('Adding user into AD: %s ' % new_user['username'])
        except ldap.LDAPError, error_message:
            print "Error adding new user: %s" % error_message
            return False

      # Add the password
        try:
            ldap_connection.modify_s(USER_DN, add_pass)
            logging.info('Password added for user: %s ' % new_user['username'])
        except ldap.LDAPError, error_message:
            print "Error setting password: %s" % error_message
            return False

      # Change the account back to enabled
        try:
            ldap_connection.modify_s(USER_DN, mod_acct)
            logging.info('Enabling AD Account for user: %s ' % new_user['username'])
        except ldap.LDAPError, error_message:
            print "Error enabling user: %s" % error_message
            return False

      # Add user to their primary group
        try:
            ldap_connection.modify_s(GROUP_DN, add_member)
            logging.info('Adding user to group %s: ' % new_user['group_dn'])
        except ldap.LDAPError, error_message:
            print "Error adding user to group: %s" % error_message
        return
new_users = get_users()
if args.createusers is not "None":
    create_user_in_ad(new_users)
</code>```

It calls in a YAML File with user info:

```<code> User1:
    username: adtest2
    fname: adtest2
    lname: adtest2
    domain: test.com
    group_dn: test
#   group:

  # User2:
  #    username: testing
  #    fname: testing
  #    lname: bbbbb
  #    domain: test.com
  #    group_dn: test
# #   group:

    ldap_connection.unbind_s()

    print "User %s has been created in AD!" % new_user['username']

    # All is good
    return True
</code>```

The problem right now is its only executing on the second user when it is not commented out, and I'm wondering did I do something wrong in my for loop? It is doing everything I would like for it to do properly. I'm using Python 2.7.13 btw!

Output now shows only the second user:

```<code>    Connected to LDAP Server!
adtest2
</code>```

答: The issue was that the return was being executed inside of the for loop. I simply moved it outside of the for loop. </p>

Body:
I have a function that looks like this:

def get_users(yaml_file="AD_Users.yml"):
with open(yaml_file, 'r') as stream:
    try:
        data = yaml.load(stream)
    except yaml.YAMLError as exc:
        print(exc)
return data.itervalues()

 def create_user_in_ad(new_users): #username, password, base_dn, fname, lname, domain):
    # LDAP connection
    for new_user in new_users:
        try:
            logging.info('Connecting to LDAP Server %s ' % LDAP_SERVER)
            ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, 0)
            ldap_connection = ldap.initialize(LDAP_SERVER)
            ldap_connection.simple_bind_s(BIND_DN, BIND_PASS)
            print "Connected to LDAP Server!"
        except ldap.LDAPError, error_message:
            print "Error connecting to LDAP server: %s" % error_message
            #logging.info('Unable to connect to LDAP Server %s ' % LDAP_SERVER)
            return False
#           sys.exit(1)

      # Check and see if user exists
        try:
            print new_user['username']
            logging.info('Querying AD for user: %s ' % new_user['username'])
            user_results = ldap_connection.search_s(BASE_DN, ldap.SCOPE_SUBTREE,
                                                  '(&(sAMAccountName=' +
                                                  new_user['username'] +
                                                  ')(objectClass=person))',
                                                  ['distinguishedName'])
            print user_results
        except ldap.LDAPError, error_message:
            print "Error finding username: %s" % error_message
            logging.info('Unable to query for user: %s ' % new_user['username'])
            return False

      # Check the results
        if len(user_results) != 0:
            print "User", new_user['username'], "already exists in AD:"
            return False
            sys.exit(1)

      # Lets build our user: Disabled to start (514)
        USER_DN = 'cn=' + new_user['fname'] + ' ' + new_user['lname'] + ',' + BASE_DN
        GROUP_DN = 'ou=' + new_user['group_dn'] + ',' + BASE_DN
        user_attrs = {}
        user_attrs['objectClass'] = \
                    ['top', 'person', 'organizationalPerson', 'user']
        user_attrs['cn'] = new_user['fname'] + ' ' + new_user['lname']
        user_attrs['userPrincipalName'] = new_user['username'] + '@' + new_user['domain']

      # Add the new user account
        try:
            ldap_connection.add_s(USER_DN, user_ldif)
            logging.info('Adding user into AD: %s ' % new_user['username'])
        except ldap.LDAPError, error_message:
            print "Error adding new user: %s" % error_message
            return False

      # Add the password
        try:
            ldap_connection.modify_s(USER_DN, add_pass)
            logging.info('Password added for user: %s ' % new_user['username'])
        except ldap.LDAPError, error_message:
            print "Error setting password: %s" % error_message
            return False

      # Change the account back to enabled
        try:
            ldap_connection.modify_s(USER_DN, mod_acct)
            logging.info('Enabling AD Account for user: %s ' % new_user['username'])
        except ldap.LDAPError, error_message:
            print "Error enabling user: %s" % error_message
            return False

      # Add user to their primary group
        try:
            ldap_connection.modify_s(GROUP_DN, add_member)
            logging.info('Adding user to group %s: ' % new_user['group_dn'])
        except ldap.LDAPError, error_message:
            print "Error adding user to group: %s" % error_message
        return
new_users = get_users()
if args.createusers is not "None":
    create_user_in_ad(new_users)

It calls in a YAML File with user info:

 User1:
    username: adtest2
    fname: adtest2
    lname: adtest2
    domain: test.com
    group_dn: test
#   group:

  # User2:
  #    username: testing
  #    fname: testing
  #    lname: bbbbb
  #    domain: test.com
  #    group_dn: test
# #   group:

    ldap_connection.unbind_s()

    print "User %s has been created in AD!" % new_user['username']

    # All is good
    return True

The problem right now is its only executing on the second user when it is not commented out, and I'm wondering did I do something wrong in my for loop? It is doing everything I would like for it to do properly. I'm using Python 2.7.13 btw!

Output now shows only the second user:

    Connected to LDAP Server!
adtest2


来源: stackexchange

问:
How to stop Refresh/Reload of page in asp.net
I think page load is bigest issue of asp.net(webform)

I reserach alot about but i not get any solution

I use update panel but update panel not work

So please expect update panel give any other solution

e.g I have button i click onbutton after that full page goes refersh but i dnt want this

Is this possible when i click on button just show some progress bar for refershing page

Please give some suitable example

Because Page load so irrating me

Thanks :)

Update

```<code>  <asp:button ID="btn" runat="server" onclick="btn_click" />
</code>```

Now here i want to show datalist data without loading page

```<code>    <asp:datalist ID="dlist" runat="server" >
    <item template>
          <asp:label ID="lbl" runat="server" Text='<%#Eval("Comments") %>'/>
    </item template>
    </asp:datalist>
</code>```

答:
There is no need of JQuery or Javascript if you want  to use Update panel.

Here is the code that will do work for you.

default.aspx

```<code><asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:button ID="btn" runat="server" OnClick="btn_click" />
<asp:datalist ID="dlist" runat="server" >
<itemtemplate>
      <asp:label ID="lbl" runat="server" Text='<%#Eval("Comments") %>'/>
</itemtemplate>
</asp:datalist>

</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btn" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
</code>```

Then at back end I've given datatable to the datalist by following way.

default.aspx.cs

```<code>protected void btn_click(object sender, EventArgs e)
{

   //*Here You'll have to put your Own Logic. I've binded datalist just for example.*
    DataTable dt = new DataTable();
    dt.Columns.Add("Comments");
    dt.Rows.Add("abc");
    dlist.DataSource = dt;
    dlist.DataBind();
}
</code>```

Update panel always works. and there is no reason to hate this
  control. Yeah, If you want to perform operations from your front end
  only then Jquery is best choice.

ContentLicense: CC BY-SA 3.0

Body:
I think page load is bigest issue of asp.net(webform)

I reserach alot about but i not get any solution

I use update panel but update panel not work

So please expect update panel give any other solution

e.g I have button i click onbutton after that full page goes refersh but i dnt want this

Is this possible when i click on button just show some progress bar for refershing page

Please give some suitable example

Because Page load so irrating me

Thanks :)

Update

  <asp:button ID="btn" runat="server" onclick="btn_click" />

Now here i want to show datalist data without loading page

    <asp:datalist ID="dlist" runat="server" >
    <item template>
          <asp:label ID="lbl" runat="server" Text='<%#Eval("Comments") %>'/>
    </item template>
    </asp:datalist>

Body:
There is no need of JQuery or Javascript if you want  to use Update panel.

Here is the code that will do work for you.

default.aspx

<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:button ID="btn" runat="server" OnClick="btn_click" />
<asp:datalist ID="dlist" runat="server" >
<itemtemplate>
      <asp:label ID="lbl" runat="server" Text='<%#Eval("Comments") %>'/>
</itemtemplate>
</asp:datalist>

</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btn" EventName="Click" />
</Triggers>
</asp:UpdatePanel>

Then at back end I've given datatable to the datalist by following way.

default.aspx.cs

protected void btn_click(object sender, EventArgs e)
{

   //*Here You'll have to put your Own Logic. I've binded datalist just for example.*
    DataTable dt = new DataTable();
    dt.Columns.Add("Comments");
    dt.Rows.Add("abc");
    dlist.DataSource = dt;
    dlist.DataBind();
}

Update panel always works. and there is no reason to hate this
  control. Yeah, If you want to perform operations from your front end
  only then Jquery is best choice.


问:
How to parse a JSON Object within two JSON Array's?
I'm trying to get the item name, brand name and total carbohydrate value out of the following JSON Array but am having problems with accessing the the individual values within the "fields" section. Anyone with any pointers to retrieve this info?

```<code>{
</code>```

"total_hits": 49127,
  "max_score": 11.919899,
  "hits": [
    {

```<code>  "_index": "f762ef22-e660-434f-9071-a10ea6691c27",
  "_type": "item",
  "_id": "513fceb375b8dbbc21000022",
  "_score": 11.919899,
  "fields": {
    "item_id": "513fceb375b8dbbc21000022",
    "item_name": "Cheese, cheddar - 1 cup, diced",
    "brand_name": "USDA",
    "nf_total_carbohydrate": 4.08,
    "nf_serving_size_qty": 1,
    "nf_serving_size_unit": "serving"
  }
},
{
  "_index": "f762ef22-e660-434f-9071-a10ea6691c27",
  "_type": "item",
  "_id": "513fceb375b8dbbc21000021",
  "_score": 11.788424,
  "fields": {
    "item_id": "513fceb375b8dbbc21000021",
    "item_name": "Cheese, cheddar - 1 cup, melted",
    "brand_name": "USDA",
    "nf_total_carbohydrate": 7.54,
    "nf_serving_size_qty": 1,
    "nf_serving_size_unit": "serving"
  }
</code>```

/* sorry for some reason i can't get the formatting right but the "hits" is a parent of the whole highlighted code section*/

答:
Try this:

```<code>    try {
        JSONObject object = new JSONObject(json);
        JSONArray hits = object.getJSONArray("hits");
        for (int i = 0; i < hits.length(); i++) {
            JSONObject fields = hits.getJSONObject(i).getJSONObject("fields");
            String itemName = fields.getString("item_name");
            String brandName = fields.getString("brand_name");
            double carbohydrate = fields.getDouble("nf_total_carbohydrate");
            Log.d("HitTag", itemName+" "+brandName+" "+carbohydrate);
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
</code>```

I assume that you have this json:

```<code>{
  "total_hits": 49127,
  "max_score": 11.919899,
  "hits": [
    {
      "_index": "f762ef22-e660-434f-9071-a10ea6691c27",
      "_type": "item",
      "_id": "513fceb375b8dbbc21000022",
      "_score": 11.919899,
      "fields": {
        "item_id": "513fceb375b8dbbc21000022",
        "item_name": "Cheese, cheddar - 1 cup, diced",
        "brand_name": "USDA",
        "nf_total_carbohydrate": 4.08,
        "nf_serving_size_qty": 1,
        "nf_serving_size_unit": "serving"
      }
    },
    {
      "_index": "f762ef22-e660-434f-9071-a10ea6691c27",
      "_type": "item",
      "_id": "513fceb375b8dbbc21000021",
      "_score": 11.788424,
      "fields": {
        "item_id": "513fceb375b8dbbc21000021",
        "item_name": "Cheese, cheddar - 1 cup, melted",
        "brand_name": "USDA",
        "nf_total_carbohydrate": 7.54,
        "nf_serving_size_qty": 1,
        "nf_serving_size_unit": "serving"
      }
    }
  ]
}
</code>```

Body:
I'm trying to get the item name, brand name and total carbohydrate value out of the following JSON Array but am having problems with accessing the the individual values within the "fields" section. Anyone with any pointers to retrieve this info?

{

"total_hits": 49127,
  "max_score": 11.919899,
  "hits": [
    {

  "_index": "f762ef22-e660-434f-9071-a10ea6691c27",
  "_type": "item",
  "_id": "513fceb375b8dbbc21000022",
  "_score": 11.919899,
  "fields": {
    "item_id": "513fceb375b8dbbc21000022",
    "item_name": "Cheese, cheddar - 1 cup, diced",
    "brand_name": "USDA",
    "nf_total_carbohydrate": 4.08,
    "nf_serving_size_qty": 1,
    "nf_serving_size_unit": "serving"
  }
},
{
  "_index": "f762ef22-e660-434f-9071-a10ea6691c27",
  "_type": "item",
  "_id": "513fceb375b8dbbc21000021",
  "_score": 11.788424,
  "fields": {
    "item_id": "513fceb375b8dbbc21000021",
    "item_name": "Cheese, cheddar - 1 cup, melted",
    "brand_name": "USDA",
    "nf_total_carbohydrate": 7.54,
    "nf_serving_size_qty": 1,
    "nf_serving_size_unit": "serving"
  }

/* sorry for some reason i can't get the formatting right but the "hits" is a parent of the whole highlighted code section*/

Body:
Try this:

    try {
        JSONObject object = new JSONObject(json);
        JSONArray hits = object.getJSONArray("hits");
        for (int i = 0; i < hits.length(); i++) {
            JSONObject fields = hits.getJSONObject(i).getJSONObject("fields");
            String itemName = fields.getString("item_name");
            String brandName = fields.getString("brand_name");
            double carbohydrate = fields.getDouble("nf_total_carbohydrate");
            Log.d("HitTag", itemName+" "+brandName+" "+carbohydrate);
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

I assume that you have this json:

{
  "total_hits": 49127,
  "max_score": 11.919899,
  "hits": [
    {
      "_index": "f762ef22-e660-434f-9071-a10ea6691c27",
      "_type": "item",
      "_id": "513fceb375b8dbbc21000022",
      "_score": 11.919899,
      "fields": {
        "item_id": "513fceb375b8dbbc21000022",
        "item_name": "Cheese, cheddar - 1 cup, diced",
        "brand_name": "USDA",
        "nf_total_carbohydrate": 4.08,
        "nf_serving_size_qty": 1,
        "nf_serving_size_unit": "serving"
      }
    },
    {
      "_index": "f762ef22-e660-434f-9071-a10ea6691c27",
      "_type": "item",
      "_id": "513fceb375b8dbbc21000021",
      "_score": 11.788424,
      "fields": {
        "item_id": "513fceb375b8dbbc21000021",
        "item_name": "Cheese, cheddar - 1 cup, melted",
        "brand_name": "USDA",
        "nf_total_carbohydrate": 7.54,
        "nf_serving_size_qty": 1,
        "nf_serving_size_unit": "serving"
      }
    }
  ]
}


问:
Error with OnTouchListener
I get an error trying to implement an OnTouchListener:

The method onTouch(View, MotionEvent)
  of type new View.OnTouchListener(){}
  must override a superclass method

I have no idea why it's not working as it seems I'm overrriding the method correctly:

```<code>public class MyActivity extends Activity
{
    ...creation code etc...

    OnTouchListener mTouchListener = new OnTouchListener()
    {
        @Override
        public boolean onTouch(View v, MotionEvent event)
        {
                 ...touch code...
            }
        }
}
</code>```

Any ideas on how I can debug this?

答:
In Eclipse, go to Windows>Preference>Java>Compiler and select 1.6.

You might be using 1.5, and 1.5 does not allow @Override on interfaces methods, but just on superclass method.
1.6 does.

If it still doesn't work, remove the @Override line...

```<code>public class MyActivity extends Activity
{
    ...creation code etc...

    OnTouchListener mTouchListener = new OnTouchListener()
    {

        public boolean onTouch(View v, MotionEvent event)
        {
                 ...touch code...
            }
        }
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: Error with OnTouchListener

Body:
I get an error trying to implement an OnTouchListener:

The method onTouch(View, MotionEvent)
  of type new View.OnTouchListener(){}
  must override a superclass method

I have no idea why it's not working as it seems I'm overrriding the method correctly:

public class MyActivity extends Activity
{
    ...creation code etc...

    OnTouchListener mTouchListener = new OnTouchListener()
    {
        @Override
        public boolean onTouch(View v, MotionEvent event)
        {
                 ...touch code...
            }
        }
}

Any ideas on how I can debug this?

Body:
In Eclipse, go to Windows>Preference>Java>Compiler and select 1.6.

You might be using 1.5, and 1.5 does not allow @Override on interfaces methods, but just on superclass method.
1.6 does.

If it still doesn't work, remove the @Override line...

public class MyActivity extends Activity
{
    ...creation code etc...

    OnTouchListener mTouchListener = new OnTouchListener()
    {

        public boolean onTouch(View v, MotionEvent event)
        {
                 ...touch code...
            }
        }
}


问:
Passing a variable into another page and running the variable
Is it possible to pass a variable from one page to the next page and running that variable at the same time?

What I am trying to do is have a search bar that allows the user to search and upon enter opening up a new page that has a datatable. I want to pass what they type into search bar into the search bar of the datatable and have the results shown.

```<code><!-- START Search form-->
            <form role="search" action="searchalltransactions.cfm" class="navbar-form">
               <div class="form-group has-feedback">
                  <input type="text" placeholder="Type and hit enter ..." class="form-control">
                  <div data-search-dismiss="" class="fa fa-times form-control-feedback"></div>
               </div>
               <button type="submit" class="hidden btn btn-default">Submit</button>
            </form>
            <!-- END Search form-->
</code>```

Is something like this possible? I am not familiar with this and just trying to learn how to do this if its even possible.

How can I pass this into the (search that datatables creates) on the next page searchalltransactions.cfm

Search that jquery datatables creates

```<code> <input class="form-control input-sm" placeholder="" aria-controls="processing1" type="search">
</code>```

答:
It's a little goofy, but you can do this on the results page, after datatables is initialized:

```<code><cfoutput>
<script>
table.search( '#url.search#' ).draw();
</script>
</cfoutput>
</code>```

Keep in mind this is running in javascript. All database results are being loaded into the browser, which is then filtering. If you're going to GET or POST a search, you should do your filtering/searching in the database query instead.

More on this:
https://datatables.net/reference/api/search()

Body:
Is it possible to pass a variable from one page to the next page and running that variable at the same time?

What I am trying to do is have a search bar that allows the user to search and upon enter opening up a new page that has a datatable. I want to pass what they type into search bar into the search bar of the datatable and have the results shown.

            <form role="search" action="searchalltransactions.cfm" class="navbar-form">

                  <input type="text" placeholder="Type and hit enter ..." class="form-control">

               <button type="submit" class="hidden btn btn-default">Submit</button>
            </form>

Is something like this possible? I am not familiar with this and just trying to learn how to do this if its even possible.

How can I pass this into the (search that datatables creates) on the next page searchalltransactions.cfm

Search that jquery datatables creates

 <input class="form-control input-sm" placeholder="" aria-controls="processing1" type="search">

Body:
It's a little goofy, but you can do this on the results page, after datatables is initialized:

<cfoutput>
<script>
table.search( '#url.search#' ).draw();
</script>
</cfoutput>

Keep in mind this is running in javascript. All database results are being loaded into the browser, which is then filtering. If you're going to GET or POST a search, you should do your filtering/searching in the database query instead.

More on this:
https://datatables.net/reference/api/search()


问:
Make a single property optional in TypeScript
In TypeScript, 2.2...

Let's say I have a Person type:

```<code>interface Person {
  name: string;
  hometown: string;
  nickname: string;
}
</code>```

And I'd like to create a function that returns a Person, but doesn't require a nickname:

```<code>function makePerson(input: ???): Person {
  return {...input, nickname: input.nickname || input.name};
}
</code>```

What should be the type of input? I'm looking for a dynamic way to specify a type that is identical to Person except that nickname is optional (nickname?: string | undefined). The closest thing I've figured out so far is this:

```<code>type MakePersonInput = Partial<Person> & {
  name: string;
  hometown: string;
}
</code>```

but that's not quite what I'm looking for, since I have to specify all the types that are required instead of the ones that are optional.

答:
Ok well what you are really describing is two different "Types" of people (i.e. Person types) .. A normal person and a nick named person.

```<code>interface Person {
    name: string;
    hometown: string;
}

interface NicknamedPerson extends Person {
    nickname: string;
}
</code>```

Then in the case where you don't really want a nicknamed person but just a person you just implement the Person interface.

An alternative way to do this if you wanted to hang on to just one Person interface is having a different implementation for a non nicknamed person:

```<code>interface Person {
  name: string;
  hometown: string;
  nickname: string;
}
class NicknamedPerson implements Person {
    constructor(public name: string, public hometown: string, public nickname: string) {}
}

class RegularPerson implements Person {
    nickname: string;
    constructor(public name: string, public hometown: string) {
        this.nickname = name;
    }
}

makePerson(input): Person {
     if(input.nickname != null) {
       return new NicknamedPerson(input.name, input.hometown, input.nickname);
     } else {
       return new RegularPerson(input.name, input.hometown);
     }
}
</code>```

This enables you to still assign a nickname (which is just the persons name in case of an absence of a nickname) and still uphold the Person interface's contract.  It really has more to do with how you intend on using the interface.  Does the code care about the person having a nickname?  If not, then the first proposal is probably better.

Body:
In TypeScript, 2.2...

Let's say I have a Person type:

interface Person {
  name: string;
  hometown: string;
  nickname: string;
}

And I'd like to create a function that returns a Person, but doesn't require a nickname:

function makePerson(input: ???): Person {
  return {...input, nickname: input.nickname || input.name};
}

What should be the type of input? I'm looking for a dynamic way to specify a type that is identical to Person except that nickname is optional (nickname?: string | undefined). The closest thing I've figured out so far is this:

type MakePersonInput = Partial<Person> & {
  name: string;
  hometown: string;
}

but that's not quite what I'm looking for, since I have to specify all the types that are required instead of the ones that are optional.

Body:
Ok well what you are really describing is two different "Types" of people (i.e. Person types) .. A normal person and a nick named person.

interface Person {
    name: string;
    hometown: string;
}

interface NicknamedPerson extends Person {
    nickname: string;
}

Then in the case where you don't really want a nicknamed person but just a person you just implement the Person interface.

An alternative way to do this if you wanted to hang on to just one Person interface is having a different implementation for a non nicknamed person:

interface Person {
  name: string;
  hometown: string;
  nickname: string;
}
class NicknamedPerson implements Person {
    constructor(public name: string, public hometown: string, public nickname: string) {}
}

class RegularPerson implements Person {
    nickname: string;
    constructor(public name: string, public hometown: string) {
        this.nickname = name;
    }
}

makePerson(input): Person {
     if(input.nickname != null) {
       return new NicknamedPerson(input.name, input.hometown, input.nickname);
     } else {
       return new RegularPerson(input.name, input.hometown);
     }
}

This enables you to still assign a nickname (which is just the persons name in case of an absence of a nickname) and still uphold the Person interface's contract.  It really has more to do with how you intend on using the interface.  Does the code care about the person having a nickname?  If not, then the first proposal is probably better.


问:
Sorting unique objects on basis of other states
I have collection of employees with states as name,salary,id.

```<code>    TreeSet ts=new TreeSet();
    ts.add(new Employee("neeraj", 10000, 123));
    ts.add(new Employee("neeraj", 10000, 789));
    ts.add(new Employee("ankit", 30000, 345));
    ts.add(new Employee("ankit", 40000, 456));
</code>```

How to sort employees with unique name on basis of salary?

答:
Java 8 solution:

```<code>Collections.sort(employees, Comparator.comparing(Employee::getName)
    .thenComparing(Report::getSalary));
</code>```

Body:
I have collection of employees with states as name,salary,id.

    TreeSet ts=new TreeSet();
    ts.add(new Employee("neeraj", 10000, 123));
    ts.add(new Employee("neeraj", 10000, 789));
    ts.add(new Employee("ankit", 30000, 345));
    ts.add(new Employee("ankit", 40000, 456));

How to sort employees with unique name on basis of salary?

Body:
Java 8 solution:

Collections.sort(employees, Comparator.comparing(Employee::getName)
    .thenComparing(Report::getSalary));


问:
What are the actual formats supported by CngKeyBlobFormat?
The Microsoft pages provide "minimal" information about the formats that can be used by CngKey.Import. Which actual formats are actually represented by the following CngKeyBlobFormat properties?

EccPrivateBlob

EccPublicBlob

GenericPrivateBlob

GenericPublicBlob

OpaqueTransportBlob

Pkcs8PrivateBlob

Only the PKCS#8 private key format hints slightly about the format of the key, but it doesn't specify if the private key needs to be wrapped or if just the inner PKCS#8 structure is accepted.

The more information about these formats the better of course.

答:
A thing to keep in mind throughout all of this is that CNG is extendable through CNG Providers, which may be the default Microsoft Software one, a Smart Card, or a 3rd party provider like an HSM. Any provider may choose to ignore or not support any of these formats. This eventually boils down to NCryptImportKey being called. There are a number of formats that are supported by CNG that are not listed here. The remarks section there has quite a bit of information about the types and links for data structures.

As you see in the NCryptImportKey documentation, the key format is a string. The CngKeyBlobFormat is just a wrapper around those strings. You can look in the reference source to see how these properties map to the Win32 strings. For example, the EccPrivateBlob property is the "ECCPRIVATEBLOB" string.

Pkcs8PrivateBlob

As you noted, this format is specified by the PKCS#8 standard.

OpaqueTransportBlob

This one Microsoft can't really document because it is an opaque blob, and is not portable between providers. Essentially, this is meant to be a representation the provider chooses.

GenericPublicBlob

This will be a binary representation of the BCRYPT_KEY_BLOB structure. The first field in the structure determines which structure it is with magic values. For example, with RSA public key, it will be a BCRYPT_RSAKEY_BLOB.

GenericPrivateBlob

This is the same as above except the private parameters are filled in.

EccPublicBlob

This will be a BCRYPT_ECCKEY_BLOB structure. It is similar as above in that a magic value will determine the actual contents of the blob.

EccPrivateBlob

This will be the same as above except the private parameters are filled in.

In the cases for BCRYPT_KEY_BLOB and BCRYPT_ECCKEY_BLOB structures, the structures act as a "header" for the key. The actual key material will be in the same blob of memory, after the struct. The "amount" of key material will be known based on the magic value, and the other values in the header.


问:
Django: text-input instead selection on foreignkey
I want to create a messaging function in ma django app. User should be able to write other users a textmessage.

models.py

```<code>from django.contrib.auth.models import User
class Message(models.Model):
    recipient   = models.ForeignKey(User, null=True)
    contentDescription = models.CharField(max_length=1000, null=True)
</code>```

By default, with no forms.py entry I get a selection, which will be unuseful with many users. I want the message sender to type in the user name, or in the first step the user id (which I could resolve with ajax from the name) .

Integer

But with forms.py

```<code>recipient =         forms.IntegerField(    widget=forms.NumberInput , required=False,)
</code>```

I get:

```<code>    Cannot assign "11": "Transport.recipient" must be a "User" instance.
</code>```

ChoiceField and NumberInput

with:

```<code>recipient =          forms.ChoiceField(  widget=forms.NumberInput, required=False,)
</code>```

I get the error message "not valid"

Is it possible to write the foreignkey 'manually' at all?

答:
Try this:</p>

```<code>recipient = forms.ModelChoiceField(queryset=User.objects.all(), widget=forms.Select, required=False)
</code>```

Body:
I want to create a messaging function in ma django app. User should be able to write other users a textmessage.

models.py

from django.contrib.auth.models import User
class Message(models.Model):
    recipient   = models.ForeignKey(User, null=True)
    contentDescription = models.CharField(max_length=1000, null=True)

By default, with no forms.py entry I get a selection, which will be unuseful with many users. I want the message sender to type in the user name, or in the first step the user id (which I could resolve with ajax from the name) .

Integer

But with forms.py

recipient =         forms.IntegerField(    widget=forms.NumberInput , required=False,)

I get:

    Cannot assign "11": "Transport.recipient" must be a "User" instance.

ChoiceField and NumberInput

with:

recipient =          forms.ChoiceField(  widget=forms.NumberInput, required=False,)

I get the error message "not valid"

Is it possible to write the foreignkey 'manually' at all?

Body:
Try this:

recipient = forms.ModelChoiceField(queryset=User.objects.all(), widget=forms.Select, required=False)


问:
Dynamically adding words to a context in REBOL
Imagine the following REBOL code:

```foo: context [bar: 3]```

I now have a context foo in which 'bar is defined. How can I dynamically inject a new word into this context? Is it possible?

I've tried:

```set/any in foo 'baz 3```

But that doesn't work because the expression in foo 'baz fails because there is no word 'baz defined in the foo context.

I should add that I realize one way to do this is as follows:

```foo-prototype: [bar: 3]
foo: context foo-prototype
foo: context head append foo-prototype [baz: 3]```

But what if you don't have access to foo's prototype block?

答:
There are several ways to work around the fact that in REBOL/2 it's just not posssible to extend object contexts.

Probably you can just use BLOCK!s instead of OBJECT!s:

```<code>>> blobject: [foo 1]
== [foo 1]
>> blobject/bar
** Script Error: Invalid path value: bar
** Near: blobject/bar
>> append blobject [bar 2]
== [foo 1 bar 2]
>> blobject/bar: 3
== 3
</code>```

You can even make 'self working by just appending the object itself:

```<code>>> insert blobject reduce ['self blobject]
== [[...] foo 1 bar 2]
>> same? blobject blobject/self
== true
</code>```

But as you've asked for extending OBJECT!s, you may go for Peter W A Wood's solution to simply clone the object. Just keep in mind that with this approach the resulting clone really is a different thing than the original object.

So, if some word has been set to hold the object prior to cloning/extending, after cloning the object that word will still hold the unextended object:

```<code>>> remember: object: make object! [foo: 1]
>> object: make object [bar: 2]
>> same? remember object
== false
>> probe remember
make object! [
   foo: 1
]
</code>```

In case it's essential for you to keep "references" to the object intact, you might want to wrap the object you need to extend in an outer object as in

```<code>>> remember: object: make object! [access: make object! [foo: 1]]
>> object/access: make object/access [bar: 2]
>> same? remember object
== true
</code>```

You can then safley extend the object while keeping, given you only store references to the container.

REBOL/3, btw, will allow adding words to OBJECT!s.

OwnerDisplayName: Revolucent

Body:
Imagine the following REBOL code:

foo: context [bar: 3]

I now have a context foo in which 'bar is defined. How can I dynamically inject a new word into this context? Is it possible?

I've tried:

set/any in foo 'baz 3

But that doesn't work because the expression in foo 'baz fails because there is no word 'baz defined in the foo context.

I should add that I realize one way to do this is as follows:

foo-prototype: [bar: 3]
foo: context foo-prototype
foo: context head append foo-prototype [baz: 3]

But what if you don't have access to foo's prototype block?

LastEditorDisplayName: Revolucent

Body:
There are several ways to work around the fact that in REBOL/2 it's just not posssible to extend object contexts.

Probably you can just use BLOCK!s instead of OBJECT!s:

>> blobject: [foo 1]
== [foo 1]
>> blobject/bar
** Script Error: Invalid path value: bar
** Near: blobject/bar
>> append blobject [bar 2]
== [foo 1 bar 2]
>> blobject/bar: 3
== 3

You can even make 'self working by just appending the object itself:

>> insert blobject reduce ['self blobject]
== [[...] foo 1 bar 2]
>> same? blobject blobject/self
== true

But as you've asked for extending OBJECT!s, you may go for Peter W A Wood's solution to simply clone the object. Just keep in mind that with this approach the resulting clone really is a different thing than the original object.

So, if some word has been set to hold the object prior to cloning/extending, after cloning the object that word will still hold the unextended object:

>> remember: object: make object! [foo: 1]
>> object: make object [bar: 2]
>> same? remember object
== false
>> probe remember
make object! [
   foo: 1
]

In case it's essential for you to keep "references" to the object intact, you might want to wrap the object you need to extend in an outer object as in

>> remember: object: make object! [access: make object! [foo: 1]]
>> object/access: make object/access [bar: 2]
>> same? remember object
== true

You can then safley extend the object while keeping, given you only store references to the container.

REBOL/3, btw, will allow adding words to OBJECT!s.

OwnerDisplayName: Christian Ensel


问:
Java wordsearch method, searching given 2d array
I am trying to pass a word to my findWord method which checks a 2d array of stype String[][] "a" for said word. Row and column are the dimensions of "a". I am not checking diagonal or reverse, only forwards. I believe that nearly if not all of my logic is correct, but I think I'm getting a bounds error. No error is being thrown, but the code just isn't working properly by returning false in random cases that it should return true. Code compiles and runs fine. (i.e it checking past the amount of columns that exist).

```<code>public boolean findWord(String word)  {
    int cL = column;
    for(int i = 0; i < row; i++) {
        for(int j = 0; j < column; j++) {
            if(a[i][j].equals(word.substring(0,1))) {
                int c = 1;
                int parameter = j + word.length();
                if(parameter <= cL) {
                    for(int k = j; k < parameter; k++) {
                        if(!a[i][k].equals(word.substring(c,c+1)))
                            return false;
                        c++;
                    }
                    return true;
                }
            } else {
                return false;
            }
        }
    }
    return true;
}
</code>```

答:
I have run a few test cases. I have not yet found a case where your method returns true despite the word being in the array.

The flaws I have seen in your code are:

You start looking in a[0][0]. If the string found here isn’t equal to the first letter of your word, you immediately return false without looking any further.

Say that the first letter of the word does match a[0][0]. Now you set c to 1, but since i and k are 0, you now compare the second letter of the word to a[0][0]. That is unlikely to match. It only does of the word begins with the same letter twice.

Finally, I did manage to get a StringIndexOutOfBoundsException, namely by searching for aa in a row containing a, b, c. Second time through the innermost loop c is 2, and you therefore try to take out the substring between indices 2 and 3 of a word that has length 2.

You’ve got some fixing to do. Enjoy your work.

Body:
I am trying to pass a word to my findWord method which checks a 2d array of stype String[][] "a" for said word. Row and column are the dimensions of "a". I am not checking diagonal or reverse, only forwards. I believe that nearly if not all of my logic is correct, but I think I'm getting a bounds error. No error is being thrown, but the code just isn't working properly by returning false in random cases that it should return true. Code compiles and runs fine. (i.e it checking past the amount of columns that exist).

public boolean findWord(String word)  {
    int cL = column;
    for(int i = 0; i < row; i++) {
        for(int j = 0; j < column; j++) {
            if(a[i][j].equals(word.substring(0,1))) {
                int c = 1;
                int parameter = j + word.length();
                if(parameter <= cL) {
                    for(int k = j; k < parameter; k++) {
                        if(!a[i][k].equals(word.substring(c,c+1)))
                            return false;
                        c++;
                    }
                    return true;
                }
            } else {
                return false;
            }
        }
    }
    return true;
}


问:
How to pass Reactive variables among different templates in Meteor?
I have 2 separate templates:

<template name = "MusicControl">

</template>

<template name = "MusicSystem">

</template>
```

I have 2 JavaScript files associated with these 2 templates.

What I want is that if an event occurs ("click" event) on the MusicControl template, it sets some sort of global variable (but not Session variable) so that I can access it in another template as a helper function.

How to implement in Reactive-Dict in Meteor?

Do not worry I have the helper functions defined for both the template in their respective js.

And one thing, these <templates> are independent of each other, I just want to listen the event in <template 1> on <template 2> by using some sort of global variable.

答:
for this scenario, i generally use a reactive variable owned by the parent, whose job it is to coordinate among its children. i would not use a global variable here.

below are the basics. Child1 sets the shared var and Child2 uses it. the parent owns it. Child1 and Child2 have no relationship to one another.

```<code><template name="Parent">
    {{> Child1 sharedVarSetter=getSharedVarSetterFn}}
    {{> Child2 sharedVar=sharedVar}}
</template>
</code>```

JS:

```<code>Template.Parent.onCreated(function() {
    this.sharedVar = new ReactiveVar();
});

Template.Parent.helpers({
    sharedVar() {
        return Template.instance().sharedVar.get();
    },

    getSharedVarSetterFn() {
        let template = Template.instance();

        return function(newValue) {
            template.sharedVar.set(newValue);
        }
    }
});

Template.Child1.onCreated(function() {
    this.sharedVarSetterFn = new ReactiveVar(Template.currentData().sharedVarSetter);
});
</code>```

and somewhere in Child1 (helper, event handler, what have you):

```<code>let fn = template.sharedVarSetterFn.get();

if (_.isFunction(fn)) {
    fn(newValue);
}
</code>```

here, i've shown just 1 shared var. but if you have multiple, a reactive dict could work the same way.

Body:
I have 2 separate templates:

<template name = "MusicControl">

</template>

<template name = "MusicSystem">

</template>

I have 2 JavaScript files associated with these 2 templates.

What I want is that if an event occurs ("click" event) on the MusicControl template, it sets some sort of global variable (but not Session variable) so that I can access it in another template as a helper function.

How to implement in Reactive-Dict in Meteor?

Do not worry I have the helper functions defined for both the template in their respective js.

And one thing, these <templates> are independent of each other, I just want to listen the event in <template 1> on <template 2> by using some sort of global variable.

Body:
for this scenario, i generally use a reactive variable owned by the parent, whose job it is to coordinate among its children. i would not use a global variable here.

below are the basics. Child1 sets the shared var and Child2 uses it. the parent owns it. Child1 and Child2 have no relationship to one another.

<template name="Parent">
    {{> Child1 sharedVarSetter=getSharedVarSetterFn}}
    {{> Child2 sharedVar=sharedVar}}
</template>

JS:

Template.Parent.onCreated(function() {
    this.sharedVar = new ReactiveVar();
});

Template.Parent.helpers({
    sharedVar() {
        return Template.instance().sharedVar.get();
    },

    getSharedVarSetterFn() {
        let template = Template.instance();

        return function(newValue) {
            template.sharedVar.set(newValue);
        }
    }
});

Template.Child1.onCreated(function() {
    this.sharedVarSetterFn = new ReactiveVar(Template.currentData().sharedVarSetter);
});

and somewhere in Child1 (helper, event handler, what have you):

let fn = template.sharedVarSetterFn.get();

if (_.isFunction(fn)) {
    fn(newValue);
}

here, i've shown just 1 shared var. but if you have multiple, a reactive dict could work the same way.


问:
Http Post C# with Json response
I would like to get a method that generates an http post with the following configuration in c#.

```<code>  POST pqs.php HTTP/1.1
  Host: nationalmap.gov/epqs/pqs.php
  Content-Type: application/x-www-form-urlencoded
  Content-Length: length
  x=string&y=string&units=string&output=string
</code>```

I tried the following however I am getting invalid coordinates although they do exist in the map ( example tried is lat = 36.574832 and lon = -85.411825

Here is the code I am using:

```<code>public class ElevationUSGISPull
{
    public string responseString = null;
    private string BASEURL = "http://nationalmap.gov/epqs/pqs.php";

    public bool httpPostElevationRequest( string lon,string lat)
    {

        try
        {
            using (WebClient client = new WebClient())
            {

                byte[] response =
                client.UploadValues(BASEURL, new NameValueCollection()
                {
                { "x", lon },
                { "y", lat },
                {"units", "feet" },
                {"output","json" },
                });

                string result = System.Text.Encoding.UTF8.GetString(response);
                responseString = result;
            }
            return true;
        }
        catch(Exception eX)
        {
            return false;
        }
    }
}
</code>```

The error I am getting is as below:

```<code><error>General failure: Invalid Coordinates</error>
</code>```

Moreover has anyone tried the .gov website to get elevation data. I used the google server however it has many restrictions related to number of requests and I am trying to do many requests for a given area.

Below is a website for verifying the lat and longs with a good json response.

https://nationalmap.gov/epqs/

Thanks all.

I have also tried the following example here:
http://ronaldrosiernet.azurewebsites.net/Blog/2013/12/07/posting_urlencoded_key_values_with_httpclient

But is giving me the following error.

```<code>Exception thrown: 'System.NullReferenceException'
</code>```

I modified the code to this:

```<code>  public async Task<string> HTTPPOST(string lon, string lat)
    {
        var client = new HttpClient();
        client.BaseAddress = new Uri(BASEURL);
        var request = new HttpRequestMessage(HttpMethod.Post, "");

        var keyValues = new List<KeyValuePair<string, string>>();
        keyValues.Add(new KeyValuePair<string, string>("x", lon));
        keyValues.Add(new KeyValuePair<string, string>("y", lat));
        keyValues.Add(new KeyValuePair<string, string>("units", "feet"));
        keyValues.Add(new KeyValuePair<string, string>("output", "json"));

        request.Content = new FormUrlEncodedContent(keyValues);
        var response = await client.SendAsync(request);

        return response.ToString();
    }
</code>```

答:
Use .NET HttpClient
Find an example here</p>

Title: Http Post C# with Json response

Body:
I would like to get a method that generates an http post with the following configuration in c#.

  POST pqs.php HTTP/1.1
  Host: nationalmap.gov/epqs/pqs.php
  Content-Type: application/x-www-form-urlencoded
  Content-Length: length
  x=string&y=string&units=string&output=string

I tried the following however I am getting invalid coordinates although they do exist in the map ( example tried is lat = 36.574832 and lon = -85.411825

Here is the code I am using:

public class ElevationUSGISPull
{
    public string responseString = null;
    private string BASEURL = "http://nationalmap.gov/epqs/pqs.php";

    public bool httpPostElevationRequest( string lon,string lat)
    {

        try
        {
            using (WebClient client = new WebClient())
            {

                byte[] response =
                client.UploadValues(BASEURL, new NameValueCollection()
                {
                { "x", lon },
                { "y", lat },
                {"units", "feet" },
                {"output","json" },
                });

                string result = System.Text.Encoding.UTF8.GetString(response);
                responseString = result;
            }
            return true;
        }
        catch(Exception eX)
        {
            return false;
        }
    }
}

The error I am getting is as below:

<error>General failure: Invalid Coordinates</error>

Moreover has anyone tried the .gov website to get elevation data. I used the google server however it has many restrictions related to number of requests and I am trying to do many requests for a given area.

Below is a website for verifying the lat and longs with a good json response.

https://nationalmap.gov/epqs/

Thanks all.

I have also tried the following example here:
http://ronaldrosiernet.azurewebsites.net/Blog/2013/12/07/posting_urlencoded_key_values_with_httpclient

But is giving me the following error.

Exception thrown: 'System.NullReferenceException'

I modified the code to this:

  public async Task<string> HTTPPOST(string lon, string lat)
    {
        var client = new HttpClient();
        client.BaseAddress = new Uri(BASEURL);
        var request = new HttpRequestMessage(HttpMethod.Post, "");

        var keyValues = new List<KeyValuePair<string, string>>();
        keyValues.Add(new KeyValuePair<string, string>("x", lon));
        keyValues.Add(new KeyValuePair<string, string>("y", lat));
        keyValues.Add(new KeyValuePair<string, string>("units", "feet"));
        keyValues.Add(new KeyValuePair<string, string>("output", "json"));

        request.Content = new FormUrlEncodedContent(keyValues);
        var response = await client.SendAsync(request);

        return response.ToString();
    }


问:
CSS -> Hover effect dosen't work
My CSS Code don't detect, if my cursor over the div: But if i active "hover" with the browser developer tool, it works.

Explain: The Div shows, if I go over a button, but the div hide out, if i go out of the button...

My code:

.profilanzeige2 {
  width: 20%;
  float: right;
  position: absolute;
  text-align: center;
  padding: 10px;
  top: -250px;
  right: 0px;
  z-index: -1;
  border-radius: 0px 0px 10px 10px;
  color: white;
  /* border: 1px solid #797979; */
  background-image: none;
  background: #16b751;
  background: -moz-linear-gradient(top, #16b751 0%, #19ad46 100%);
  background: -webkit-linear-gradient(top, #16b751 0%,#19ad4619ad46 100%);
  background: linear-gradient(to bottom, #16b751 0%,#19ad46 100%);
  filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#16b751', endColorstr='#19ad46',GradientType=0 );
  transition: top 1s ease-in-out;
  border: 1px solid #e7e7e7;
}

#profilanzeige:hover ~ #profilanzeige2, .profilanzeige2:hover {
    top: 54px !important;
}

#profilanzeige:hover + #profilanzeige2, .profilanzeige2:hover {
    top: 54px !important;
}

.profil:hover ~ #profilanzeige2, #profilanzeige2:hover {
    top: 54px !important;
}

.profil:hover + #profilanzeige2, #profilanzeige2:hover {
    top: 54px !important;
}
```

<pre class="lang-html prettyprint-override"><code><div class="profilanzeige2" id="profilanzeige2">
        <img src="https://ftimg.de/images/2017/03/02/5e2c4f6af5024d26bb95d074a3ed9a86.png">

        <p class="profil-name"><?php echo $user['icname']; ?></p>

        <button type="button" class="btn btn-default" class="Profilanzeigen">
          Profil anzeigen
        </button>

        <button type="button" class="btn btn-default" class="Abmelden" href="logout.php">
          Abmelden
        </button>
      </div>
</code>```

答: Fixxed, i had z-index on -1. I change it to over 0 and all work fine.</p>

Title: CSS -> Hover effect dosen't work

Body:
My CSS Code don't detect, if my cursor over the div: But if i active "hover" with the browser developer tool, it works.

Explain: The Div shows, if I go over a button, but the div hide out, if i go out of the button...

My code:

.profilanzeige2 {
  width: 20%;
  float: right;
  position: absolute;
  text-align: center;
  padding: 10px;
  top: -250px;
  right: 0px;
  z-index: -1;
  border-radius: 0px 0px 10px 10px;
  color: white;
  /* border: 1px solid #797979; */
  background-image: none;
  background: #16b751;
  background: -moz-linear-gradient(top, #16b751 0%, #19ad46 100%);
  background: -webkit-linear-gradient(top, #16b751 0%,#19ad4619ad46 100%);
  background: linear-gradient(to bottom, #16b751 0%,#19ad46 100%);
  filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#16b751', endColorstr='#19ad46',GradientType=0 );
  transition: top 1s ease-in-out;
  border: 1px solid #e7e7e7;
}

#profilanzeige:hover ~ #profilanzeige2, .profilanzeige2:hover {
    top: 54px !important;
}

#profilanzeige:hover + #profilanzeige2, .profilanzeige2:hover {
    top: 54px !important;
}

.profil:hover ~ #profilanzeige2, #profilanzeige2:hover {
    top: 54px !important;
}

.profil:hover + #profilanzeige2, #profilanzeige2:hover {
    top: 54px !important;
}

<?php echo $user['icname']; ?>

        <button type="button" class="btn btn-default" class="Profilanzeigen">
          Profil anzeigen
        </button>

        <button type="button" class="btn btn-default" class="Abmelden" href="logout.php">
          Abmelden
        </button>


问:
Notepad++ autocomplete text file adjustments?
I would like to have the Notepad++ autocomplete feature

ignore dashes

include apostrophes

when working on plain text files. I cannot find a plain text XML definition file in the autocomplete directory: C:\Program Files (x86)\Notepad++\plugins\APIs\

Is there any way to change the standard search functionality for plain text files in Notepad++?

答:
QuickText is a free plugin for Notepad++ that you can use to add text snippets to the application. You define a tag and substitution text, and only need to type the text in Notepad++ and press Tab afterwards to replace it automatically with the selected substitution text.

credits:http://www.ghacks.net/2014/02/22/work-text-snippets-notepad/

OR

I Personally Suggest You to try Sublime Text and its is the Most Customize able Text Editor which may be Extended to your own Needs. It is the Best Text Editor in the Current scenario.


问:
How to make your desktop Java app looks like Open Office or Eclipse etc.?
How to make your desktop Java app looks like Open Office or Eclipse  etc ?
Installation process looks like any Windpws app. installation. There is no Java logo on the to on a app window. You run it by .exe file. How it is done? Is this jar->exe conversion?
Is there any free tool to do that?</p>

答: I tried Jar2Exe, and JSmooth, they both produce exe files from jar archives.</p>


问:
Converting a String to Datetime in Python
I'm having some issues searching for date in my sqlite database (using peewee as ORM). If a user enters a specific date in format like 03/31/2017, nothing is happening even though that is a valid date in my database.  I'm pretty sure this is some sort of formatting problem, but i'm using same format across the search input and the database query--so not sure what problem might be.</p>

```<code>from collections import OrderedDict
import datetime
import os

from peewee import *

db = SqliteDatabase('wlg.db')

fmt = '%m/%d/%Y'

class Entry(Model):
    notes = TextField()
    name = TextField()
    task = TextField()
    minutes = IntegerField()
    date = DateField(formats=[fmt])

    class Meta:
        database = db

def initialize():
    """Create database and table if they don't exist"""
    db.connect()
    db.create_tables([Entry], safe=True)

def clear():
    os.system('cls' if os.name == 'nt' else 'clear')

def menu_loop():
    """Show the menu"""
    choice = None

    while choice != 'q':
        clear()
        print("Enter 'q' to quit")
        for key, value in menu.items():
            print('{}) {}'.format(key, value.__doc__))
        choice = input('Action: ').lower().strip()

        if choice in menu:
            clear()
            menu[choice]()

def add_entry():
    """Add an entry"""
    print("Enter your name or 'm' to return to main menu.")
    while True:
        name = input('> ')
        if name.lower().strip() != 'm':
            task = input("What task did you do? ")
            minutes = input("How many minutes did it take? ")
            notes = input("Please enter any notes about the task: ")
            date = datetime.date.today().strftime(fmt)
            Entry.create(name=name, task=task, minutes=minutes, notes=notes, date=date)
            input("Hit Enter/Return to go back and add a task or view previous entries.")
            break
        else:
            menu_loop()

def view_entries(search_employee=None, search_date=None, search_time=None, search_term=None):
    """View previous entries"""
    entries = Entry.select().order_by(Entry.date.desc())

    if search_employee:
        entries = entries.where(Entry.name.contains(search_employee))

    elif search_date:
        dt = datetime.datetime.strptime(search_date, fmt)
        entries = entries.where(Entry.date == dt)

    elif search_time:
        entries = entries.where(Entry.minutes == int(search_time))

    elif search_term:
        entries = entries.where((Entry.task.contains(search_term))|(Entry.notes.contains(search_term)))

    for entry in entries:
        date = entry.date.strftime(fmt)
        print(date)
        print('='*len(date))
        print("Name: " + entry.name)
        print("Task: " + entry.task)
        print("Minutes Taken: " + str(entry.minutes))
        print("Task Notes: " + entry.notes)
        print("Date: " + date)
        print('n) next entry')
        print('q) return to main menu')

        next_action = input('Action: [Nq] ').lower().strip()
        if next_action == 'q':
            break

def search_by_employee():
    view_entries(search_employee=input('Search query: '))

def search_by_date():
    view_entries(search_date=input('Enter Date in Format(mm/dd/yyyy)): '))

def search_by_time():
    view_entries(search_time=input('Search query: '))
    # while True:
    #     search_time = (input('Search query: '))
    #     try:
    #         search_time = int(search_time)
    #         view_entries(search_time)
    #     except ValueError:
    #         print("Not a valid entry. Please try again")

def search_by_term():
    view_entries(search_term = input('Search query: '))

def search_entries():
    """Search previous entries"""
    # view_entries(input('Search query: '))
    while True:
        lookup = input("Lookup by Employee(E), Date(D), Time(T) or Search Term(S): ")
        lookup.lower()

        if lookup == 'e':
            search_by_employee()
            break
        elif lookup == 'd':
            search_by_date()
            break
        elif lookup == 't':
            search_by_time()
            break
        elif lookup == 's':
            search_by_term()
            break
        else:
            print("Sorry invalid option. Please try again")

def delete_entry(entry):
    """Delete an entry"""
    pass

menu = OrderedDict([
    ('a', add_entry),
    ('v', view_entries),
    ('s', search_entries)
])

if __name__ == '__main__':
    initialize()
    menu_loop()
</code>```

答:
03/31/2017 is not a valid date here (France).

If you want locale-specific date handling, I believe the python datetime supports it.

Locale date formatting in Python

However, if your application has international users, you should be very, very careful, because 01/02/2017 is Feb. 1st or Jan. 2nd depending on the part of the world your users come from.

I find text dates much better for display. For example, in French it would be "1er Février" but "Feb. 1" is non-ambiguous and absolutely fine if the website is set to English.

However, displaying "02/01" is asking for trouble.

//End rant.

Hypotheses that may explain your issue:

Using datetime.datetime, but your column is a date without time. Something could go wrong in the conversion. Using the proper type is always a good idea.

Add print() to make sure your date is converted into a python date object properly.

You declare:

```<code>date = DateField(formats=[fmt])
</code>```

Since there is a "fmt" specification this makes me think that peewee performs some kind of internal conversion between SQLite internal date format (ISO YYYY-MM-DD), and possibly requires a "mm/dd/yyyy" string instead of a date object. You should check this.

Also check if your ORM peewee has a way to display the SQL queries it issues. This should make the mistakes obvious.

Body:
I'm having some issues searching for date in my sqlite database (using peewee as ORM). If a user enters a specific date in format like 03/31/2017, nothing is happening even though that is a valid date in my database.  I'm pretty sure this is some sort of formatting problem, but i'm using same format across the search input and the database query--so not sure what problem might be.

from collections import OrderedDict
import datetime
import os

from peewee import *

db = SqliteDatabase('wlg.db')

fmt = '%m/%d/%Y'

class Entry(Model):
    notes = TextField()
    name = TextField()
    task = TextField()
    minutes = IntegerField()
    date = DateField(formats=[fmt])

    class Meta:
        database = db

def initialize():
    """Create database and table if they don't exist"""
    db.connect()
    db.create_tables([Entry], safe=True)

def clear():
    os.system('cls' if os.name == 'nt' else 'clear')

def menu_loop():
    """Show the menu"""
    choice = None

    while choice != 'q':
        clear()
        print("Enter 'q' to quit")
        for key, value in menu.items():
            print('{}) {}'.format(key, value.__doc__))
        choice = input('Action: ').lower().strip()

        if choice in menu:
            clear()
            menu[choice]()

def add_entry():
    """Add an entry"""
    print("Enter your name or 'm' to return to main menu.")
    while True:
        name = input('> ')
        if name.lower().strip() != 'm':
            task = input("What task did you do? ")
            minutes = input("How many minutes did it take? ")
            notes = input("Please enter any notes about the task: ")
            date = datetime.date.today().strftime(fmt)
            Entry.create(name=name, task=task, minutes=minutes, notes=notes, date=date)
            input("Hit Enter/Return to go back and add a task or view previous entries.")
            break
        else:
            menu_loop()

def view_entries(search_employee=None, search_date=None, search_time=None, search_term=None):
    """View previous entries"""
    entries = Entry.select().order_by(Entry.date.desc())

    if search_employee:
        entries = entries.where(Entry.name.contains(search_employee))

    elif search_date:
        dt = datetime.datetime.strptime(search_date, fmt)
        entries = entries.where(Entry.date == dt)

    elif search_time:
        entries = entries.where(Entry.minutes == int(search_time))

    elif search_term:
        entries = entries.where((Entry.task.contains(search_term))|(Entry.notes.contains(search_term)))

    for entry in entries:
        date = entry.date.strftime(fmt)
        print(date)
        print('='*len(date))
        print("Name: " + entry.name)
        print("Task: " + entry.task)
        print("Minutes Taken: " + str(entry.minutes))
        print("Task Notes: " + entry.notes)
        print("Date: " + date)
        print('n) next entry')
        print('q) return to main menu')

        next_action = input('Action: [Nq] ').lower().strip()
        if next_action == 'q':
            break

def search_by_employee():
    view_entries(search_employee=input('Search query: '))

def search_by_date():
    view_entries(search_date=input('Enter Date in Format(mm/dd/yyyy)): '))

def search_by_time():
    view_entries(search_time=input('Search query: '))
    # while True:
    #     search_time = (input('Search query: '))
    #     try:
    #         search_time = int(search_time)
    #         view_entries(search_time)
    #     except ValueError:
    #         print("Not a valid entry. Please try again")

def search_by_term():
    view_entries(search_term = input('Search query: '))

def search_entries():
    """Search previous entries"""
    # view_entries(input('Search query: '))
    while True:
        lookup = input("Lookup by Employee(E), Date(D), Time(T) or Search Term(S): ")
        lookup.lower()

        if lookup == 'e':
            search_by_employee()
            break
        elif lookup == 'd':
            search_by_date()
            break
        elif lookup == 't':
            search_by_time()
            break
        elif lookup == 's':
            search_by_term()
            break
        else:
            print("Sorry invalid option. Please try again")

def delete_entry(entry):
    """Delete an entry"""
    pass

menu = OrderedDict([
    ('a', add_entry),
    ('v', view_entries),
    ('s', search_entries)
])

if __name__ == '__main__':
    initialize()
    menu_loop()

Body:
03/31/2017 is not a valid date here (France).

If you want locale-specific date handling, I believe the python datetime supports it.

Locale date formatting in Python

However, if your application has international users, you should be very, very careful, because 01/02/2017 is Feb. 1st or Jan. 2nd depending on the part of the world your users come from.

I find text dates much better for display. For example, in French it would be "1er Février" but "Feb. 1" is non-ambiguous and absolutely fine if the website is set to English.

However, displaying "02/01" is asking for trouble.

//End rant.

Hypotheses that may explain your issue:

Using datetime.datetime, but your column is a date without time. Something could go wrong in the conversion. Using the proper type is always a good idea.

Add print() to make sure your date is converted into a python date object properly.

You declare:

date = DateField(formats=[fmt])

Since there is a "fmt" specification this makes me think that peewee performs some kind of internal conversion between SQLite internal date format (ISO YYYY-MM-DD), and possibly requires a "mm/dd/yyyy" string instead of a date object. You should check this.

Also check if your ORM peewee has a way to display the SQL queries it issues. This should make the mistakes obvious.


问:
My ip becomes localhost when accesing XAMMP directory remotely
I'm working on a local installation of Moodle using XAMMP. I need a coworker (we are both connected to the same LAN) to change some settings; she sees the main dashboard when she inputs my ip (which means, she already has access to my XAMMP directory), the problem is whenever she inputs

```<code>{my_ip}/moodle/
</code>```

in the browser, {my_ip} turns to localhost

```<code>localhost/moodle/
</code>```

which obviously outcomes ERR_CONNECTION_REFUSED as a result.

How can I prevent this? How can I give her permission to see the /moodle/ directory remotely?

答: Change the $CFG->wwwroot variable in your config.php file, as it is currently pointing to "localhost/moodle", so when she loads your site, that is the URL it redirects to.</p>

Body:
I'm working on a local installation of Moodle using XAMMP. I need a coworker (we are both connected to the same LAN) to change some settings; she sees the main dashboard when she inputs my ip (which means, she already has access to my XAMMP directory), the problem is whenever she inputs

{my_ip}/moodle/

in the browser, {my_ip} turns to localhost

localhost/moodle/

which obviously outcomes ERR_CONNECTION_REFUSED as a result.

How can I prevent this? How can I give her permission to see the /moodle/ directory remotely?


问:
ReactJS giving inst.render is not a function error
I was showing a really basic Hello World with React and ReactDOM when I got a strange error Uncaught TypeError: inst.render is not a function. See it in this JSBin.

I've used React a lot, but new to ES6. Any ideas what I'm not seeing here?

The error seems to be saying that Hello does not have a render method, but I'm not sure.

```<code><!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
  <script src="
               https://cdnjs.cloudflare.com/ajax/libs/redux/3.0.4/redux.js" type="text/javascript"></script>
  <script src="https://fb.me/react-0.14.0.js"></script>
  <script src="https://fb.me/react-dom-0.14.0.js"></script>
</head>
<body>
  <div id="root"></div>

  <script>
const Hello = () => {
  <h1>Hi</h1>
};

const foo = () => {
  ReactDOM.render(
    <Hello />,
    document.getElementById('root')
  );
}

foo();
</script>
</body>
</html>
</code>```

答: I got this error because I was accidentally calling return someObj in my component's constructor. Once I removed it, problem solved.

Body:
I was showing a really basic Hello World with React and ReactDOM when I got a strange error Uncaught TypeError: inst.render is not a function. See it in this JSBin.

I've used React a lot, but new to ES6. Any ideas what I'm not seeing here?

The error seems to be saying that Hello does not have a render method, but I'm not sure.

<!DOCTYPE html>

  <meta charset="utf-8">
  <title>JS Bin</title>


问:
How to filter records with arithmetic operation on columns of different type in Slick 3
For example I have this simplified model where timestamp and duration both represent seconds.

case class Item(id: Int, : Long, duration: Int)

val max_timestmap: Long = ???
val stmt = items.filter(x => (x.timestamp + x.duration) <= max_timestamp)
db.run(stmt.result)

Above will not compile with following error that I have hard time understanding.

ambiguous implicit values:
[error]  both value BooleanOptionColumnCanBeQueryCondition in object CanBeQueryCondition of type => slick.lifted.CanBeQueryCondition[slick.lifted.Rep[Option[Boolean]]]
[error]  and value BooleanCanBeQueryCondition in object CanBeQueryCondition of type => slick.lifted.CanBeQueryCondition[Boolean]
[error]  match expected type slick.lifted.CanBeQueryCondition[Nothing]
[error]                 filter(x => (x.timestamp + x.duration) <= max_timestamp)

Update 1:
Seems like the issues stems for the fact that timestamp is Long and duration is Int. When both are of the same data type it seems to compile.

Update 2:
I found this solution to work. Cast duration to Long using x.duration.asInstanceOf[Rep[Long]] or probably more appropriate x.duration.asColumnOf[Long]

答:
According to Slick documentation COMING FROM SQL TO SLICK:

Arithmetic operation in different types require explicit casts using .asColumnOf[T].

As you have already discovered, you have to explicitly cast duration to Long: x.duration.asColumnOf[Long].


问:
Returning an element from list
I'm trying to return an individual from the list that has fitness greater than or equal to 90. To do so I have to sort the list, but I think there is a better way.. how can I do this withought sorting. Like at the instant when the if condition becomes true print that perticular individual from the list.</p>

```<code>    if any(individual.fitness >= 90 for individual in individuals):
        print('Threshold met!')
        individuals = sorted(
            individuals, key=lambda individual: individual.fitness, reverse=True)
        return individuals[0]
</code>```

答:
```<code>list = [11, 35, 90, 95, 98, 89, 85]
list2 = [i for i in list if i>= 90]
print(list2)
</code>```

Output of the above code is: [90, 95, 98]

It will return the list of values of your criteria. If you want to get every element individually, add these kines:

```<code>for individual in list2:
    print (individual)
</code>```

These lines will give this output:

90
 95
 98

Title: Returning an element from list

Body:
I'm trying to return an individual from the list that has fitness greater than or equal to 90. To do so I have to sort the list, but I think there is a better way.. how can I do this withought sorting. Like at the instant when the if condition becomes true print that perticular individual from the list.

    if any(individual.fitness >= 90 for individual in individuals):
        print('Threshold met!')
        individuals = sorted(
            individuals, key=lambda individual: individual.fitness, reverse=True)
        return individuals[0]

Body:
list = [11, 35, 90, 95, 98, 89, 85]
list2 = [i for i in list if i>= 90]
print(list2)

Output of the above code is: [90, 95, 98]

It will return the list of values of your criteria. If you want to get every element individually, add these kines:

for individual in list2:
    print (individual)

These lines will give this output:

90
 95
 98


问:
On cloudflare I want to disable caching and see my website changes immediately that I've pushed live
On cloudflare I want to disable caching and see my website changes immediately that I've pushed live.

Things I've tried:

I've put development mode on.

Create a bypass on caching in page rules.

Purged an individual webpage.

Purged the website.

Set cache to clear every 2 hours.

None of the above worked.

Tech I'm using:

Angular2

SystemJS

Typescript which becomes javascript on build.

Firebase for hosting and database.

Cloudflare for SSL etc.

The only way people see my website changes, it if they hard refresh.

The main problem is I've got a javascript file called app.js and its has all my javascript in for my Angular app. And it doesnt seem like its trying to get the resource in the browser.

I've changed the app.js to app.js?1490959855777
And still doesnt fetch the file again.

I basically want to see my JS file without a user having to hard refresh.

答:
Based on the discussion above, it looks like the caching is happening on the browser - since a hard refresh will get the new file contents.

I think what happened is CF told the browser to hold onto that file for a very log time. And the browser is listening to that request.

Because you can't ask your users to do a hard refresh, you'll need to rename the static files that are being cached so aggressively.


问:
Change language in Grails JavaMelody plugin
I have installed Grails JavaMelody plugin. It works properly except the language in my Chrome browser. It uses German and there is no way how to change it to English - not in application nor using get params ?lang=en_US, ?lang=en, ?locale=en. I've also tried to delete all cookies.

When I open the same page in Safari, the language is English. How can you set it for Chrome?

答:
The language of the javamelody reports depends on the language of the browser.
So you can set English as the first language in the Chrome Parameters menu.

Otherwise, you could fix the locale of the reports whatever the browser's language, by using the javamelody parameter locale.
For doing that in Grails, you can add in your grails-app/conf/application.yml, for example:

```<code>javamelody:
    locale: en_US
</code>```

Body:
The language of the javamelody reports depends on the language of the browser.
So you can set English as the first language in the Chrome Parameters menu.

Otherwise, you could fix the locale of the reports whatever the browser's language, by using the javamelody parameter locale.
For doing that in Grails, you can add in your grails-app/conf/application.yml, for example:

javamelody:
    locale: en_US


问:
NSUserDefaults write to disk?
I am writing an index for the currently selected UITabBar to [NSUserDefaults standardUserDefaults] but I am getting the odd situation where the index is not writen to disk. I am using

```<code>// TO WRITE
NSNumber *selectedTab = [NSNumber numberWithInt:[tabBarController selectedIndex]];
[[NSUserDefaults standardUserDefaults] setObject:selectedTab forKey:@"selectedTab"];
</code>```

and ...

```<code>// TO READ
NSNumber *selectTab = [[NSUserDefaults standardUserDefaults] objectForKey:@"selectedTab"];
NSLog(@"SelectTab: %@", selectTab);
[tabController setSelectedIndex:[selectTab intValue]];
</code>```

Can anyone tell me if setObject:forKey: does the actual write to disk, or do I need to force the write using something like synchronize ?

答:
Yes. You need to call synchronize to make sure your changes are actually written.

```<code>[[NSUserDefaults standardUserDefaults] synchronize];
</code>```

Usually it's done in applicationWillResignActive handler.

Title: NSUserDefaults write to disk?

Body:
I am writing an index for the currently selected UITabBar to [NSUserDefaults standardUserDefaults] but I am getting the odd situation where the index is not writen to disk. I am using

// TO WRITE
NSNumber *selectedTab = [NSNumber numberWithInt:[tabBarController selectedIndex]];
[[NSUserDefaults standardUserDefaults] setObject:selectedTab forKey:@"selectedTab"];

and ...

// TO READ
NSNumber *selectTab = [[NSUserDefaults standardUserDefaults] objectForKey:@"selectedTab"];
NSLog(@"SelectTab: %@", selectTab);
[tabController setSelectedIndex:[selectTab intValue]];

Can anyone tell me if setObject:forKey: does the actual write to disk, or do I need to force the write using something like synchronize ?

Body:
Yes. You need to call synchronize to make sure your changes are actually written.

[[NSUserDefaults standardUserDefaults] synchronize];

Usually it's done in applicationWillResignActive handler.


问:
delete buttons defined in other function
I'm trying to get a button to dissapear when you click it, and other buttons to appear. Then when the "back" button is clicked, I want the newer buttons to dissapear again, and the original button to appear again.

The problem is that I don't know how to make a function retrieve information from another function. If I try to do anything to the search_button in the search(event) function, the search_button is not defined because it was only defined in the main() function.

```<code>import tkinter as tk
window = tk.Tk()
def search(event):

    #insert "delete search_button" logic here

    easy_button = tk.Button(window, text = "Easy")
    easy_button.bind("<Button-1>", easy_search)
    easy_button.pack()

    back_button = tk.Button(window, text = "Back")
    back_button.bind("<Button-1>", back_button1) #had to put 1 on end here. It seems back_button is predefined as an object
    back_button.pack()

def easy_search(event):
    #does a bunch of stuff that doesn't matter for this question
    pass

def back_button1(event):
    #this should delete easy_button and reinitiate search_button
    pass

def main():

    search_button = tk.Button(window, text = "Search")
    search_button.bind("<Button-1>", search)
    search_button.pack()

main()
window.mainloop()
</code>```

答:
The easiest way is to make everything into a class, in which all your functions could share the same self namespace. And that if you want to bind the button pressed with another function, use 'command' instead, unless you're actually using the event.

That will come together to this:

```<code>import tkinter as tk
window = tk.Tk()

class Search:
    def __init__(self):
        self.search_button = tk.Button(window, text = "Search")
        self.search_button['command'] = self.search
        self.search_button.pack()
    def search(self):
        self.search_button.pack_forget() # or .destroy() if you're never going to use it again
        self.easy_button = tk.Button(window, text = "Easy")
        self.easy_button['command'] = self.easy_search
        self.easy_button.pack()

        self.back_button = tk.Button(window, text = "Back")
        self.back_button['command'] = self.back_button1
        self.back_button.pack()

    def easy_search(self):
        #does a bunch of stuff that doesn't matter for this question
        pass

    def back_button1(self):
    #this should delete easy_button and reinitiate search_button
        pass

widgets = Search()
window.mainloop()
</code>```

There you can call the widget's destroy or pack_forget command.

Body:
I'm trying to get a button to dissapear when you click it, and other buttons to appear. Then when the "back" button is clicked, I want the newer buttons to dissapear again, and the original button to appear again.

The problem is that I don't know how to make a function retrieve information from another function. If I try to do anything to the search_button in the search(event) function, the search_button is not defined because it was only defined in the main() function.

import tkinter as tk
window = tk.Tk()
def search(event):

    #insert "delete search_button" logic here

    easy_button = tk.Button(window, text = "Easy")
    easy_button.bind("<Button-1>", easy_search)
    easy_button.pack()

    back_button = tk.Button(window, text = "Back")
    back_button.bind("<Button-1>", back_button1) #had to put 1 on end here. It seems back_button is predefined as an object
    back_button.pack()

def easy_search(event):
    #does a bunch of stuff that doesn't matter for this question
    pass

def back_button1(event):
    #this should delete easy_button and reinitiate search_button
    pass

def main():

    search_button = tk.Button(window, text = "Search")
    search_button.bind("<Button-1>", search)
    search_button.pack()

main()
window.mainloop()

Body:
The easiest way is to make everything into a class, in which all your functions could share the same self namespace. And that if you want to bind the button pressed with another function, use 'command' instead, unless you're actually using the event.

That will come together to this:

import tkinter as tk
window = tk.Tk()

class Search:
    def __init__(self):
        self.search_button = tk.Button(window, text = "Search")
        self.search_button['command'] = self.search
        self.search_button.pack()
    def search(self):
        self.search_button.pack_forget() # or .destroy() if you're never going to use it again
        self.easy_button = tk.Button(window, text = "Easy")
        self.easy_button['command'] = self.easy_search
        self.easy_button.pack()

        self.back_button = tk.Button(window, text = "Back")
        self.back_button['command'] = self.back_button1
        self.back_button.pack()

    def easy_search(self):
        #does a bunch of stuff that doesn't matter for this question
        pass

    def back_button1(self):
    #this should delete easy_button and reinitiate search_button
        pass

widgets = Search()
window.mainloop()

There you can call the widget's destroy or pack_forget command.


问:
How to properly set a property in a protocol from a conforming class?
I am writing a custom table header view that can expand/collapse, I wrote a protocol for it like below:

```<code>protocol ExpandableHeadViewDelegate{
    var expandStateReference   :  [String : Bool] { get set }
    var tblVw                  :   UITableView { get set }
    func didTapActionFromHeadVw(_ view: ExpandableHeadView, tag: Int)
}
</code>```

Here is my expandable head view class, what Im trying to achieve is when this view is tapped I will be able to call the methods that I need from the UITableView where expandableView is embedded:

```<code>class ExpandableHeadView: UIView {
    var delegate : ExpandableHeadViewDelegate?
    //set up tap recognizer
    .
    .
    .
    .
    private func viewTapped {
        if let delegate = delegate {
            delegate.tblVw.reloadData()
        }
    }

}
</code>```

My viewcontroller that utilizes this class is as below:

```<code>class PlayersViewController: UIViewController,UITableViewDelegate,
UITableViewDataSource, ExpandableHeadViewDelegate {
    var expandedCells = [String : Bool]() //
    @IBOutlet var tableVw: UITableView! // compile time error
}
</code>```

The issue I am facing is even though I declare my 'var tableVw' in my delegate class, Xcode gives me an error:

Protocol requires property 'tableVw' with type 'UITableView'; do you
  want to add stub?

Setting var expandedCells .. however sets properly. If I set my tableVw as non-IBOutlet it can compile, but I want my tableVw to be an IBOutlet property.

EDIT:
Adding a stub variable for tableVw and assigning my tableView IBOutlet to it works. But Im still curious if this can be achieved without using a stub variable

```<code>internal var tableVw: UITableView?
@IBOutlet  var tableView: UITableView!
.
.
func viewDidload {
   self.tableVw = self.tableView
}
</code>```

答:
Quite simply - declare the property in your protocol as UITableView!. The ! matters - a lot.

! makes a variable an optional, but an explicitly unwrapped one. This basically means, that the unwrapping is done for you, under the hood. You promise the compiler, that although this variable can contain a nil, you will make sure it will be set with a proper value before you try to access it. In case of IBOutlets this is done for you by the SDK.

Body:
I am writing a custom table header view that can expand/collapse, I wrote a protocol for it like below:

protocol ExpandableHeadViewDelegate{
    var expandStateReference   :  [String : Bool] { get set }
    var tblVw                  :   UITableView { get set }
    func didTapActionFromHeadVw(_ view: ExpandableHeadView, tag: Int)
}

Here is my expandable head view class, what Im trying to achieve is when this view is tapped I will be able to call the methods that I need from the UITableView where expandableView is embedded:

class ExpandableHeadView: UIView {
    var delegate : ExpandableHeadViewDelegate?
    //set up tap recognizer
    .
    .
    .
    .
    private func viewTapped {
        if let delegate = delegate {
            delegate.tblVw.reloadData()
        }
    }

}

My viewcontroller that utilizes this class is as below:

class PlayersViewController: UIViewController,UITableViewDelegate,
UITableViewDataSource, ExpandableHeadViewDelegate {
    var expandedCells = [String : Bool]() //
    @IBOutlet var tableVw: UITableView! // compile time error
}

The issue I am facing is even though I declare my 'var tableVw' in my delegate class, Xcode gives me an error:

Protocol requires property 'tableVw' with type 'UITableView'; do you
  want to add stub?

Setting var expandedCells .. however sets properly. If I set my tableVw as non-IBOutlet it can compile, but I want my tableVw to be an IBOutlet property.

EDIT:
Adding a stub variable for tableVw and assigning my tableView IBOutlet to it works. But Im still curious if this can be achieved without using a stub variable

internal var tableVw: UITableView?
@IBOutlet  var tableView: UITableView!
.
.
func viewDidload {
   self.tableVw = self.tableView
}


问:
How to get column name in tab separated dataframe?
I have a tab separated file which I extracted in pandas dataframe as below:

```<code>import pandas as pd
data1 = pd.DataFrame.from_csv(r"C:\Users\Ashish\Documents\indeed_ml_dataset\train.tsv", sep="\t")
</code>```

data1

Here is how the data1 looks like:

Now, I want to view the column name tags. I don't know whether I should call it a column or not, but I have tried accessing it using the norm:

```<code>data2=data1[['tags']]
</code>```

but it errors out. I have tried several other things as well using index and loc, but all of them fails. Any suggestions?

答:
Try reading your data using pd.read_csv instead of pd.DataFrame.from_csv as  it takes first column as index by default.
For more info refer to this documentation on pandas website: http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.from_csv.html

Body:
I have a tab separated file which I extracted in pandas dataframe as below:

import pandas as pd
data1 = pd.DataFrame.from_csv(r"C:\Users\Ashish\Documents\indeed_ml_dataset\train.tsv", sep="\t")

data1

Here is how the data1 looks like:

Now, I want to view the column name tags. I don't know whether I should call it a column or not, but I have tried accessing it using the norm:

data2=data1[['tags']]

but it errors out. I have tried several other things as well using index and loc, but all of them fails. Any suggestions?


问:
Storing BLOB images in sql database for a SMALL website. - mysql
THere are many questions on stack overflow on whether storing images in a db is worth it for big websites and most poeple say no. I am making a very small website which will only potentially hold 20 images. I have spent alot of time setting up images to be uploaded to a database so would around 20 - 200 images - (around 10 - 50 KiB) slow down my website if I have the images stored on a database as a BLOB file.

I also likes the structure of a db as I can easily Add/Edit/Delete the images rather than going through the hassle of storing the images on a web server.

So basically is uploading 20-200 images that are around 10 - 50 KiB, will this slow down my website and how much slower would it get?

答:
The possible slow down depends on your environment. It should be negligible when your PHP implementation is right.

But the browser caching may really help you cut down the page load time. So, you will have to implement all the HTTP stuff related to the browser caching, e.g. HTTP HEAD, HTTP ETag, etc. Then, it's much easier to store the images as a local files, implement simple Add/Edit/Delete operations, and let the complicated caching stuff to the web server.


问:
Passport-Facebook authentication is not providing email for all Facebook accounts
I am using Passport-Facebook authentication.

```
  passport.use(new FacebookStrategy({
            clientID: 'CLIENT_ID',
            clientSecret: 'CLIENT_SECRET',
            callbackURL: "http://www.example.com/auth/facebook/callback"
        },
        function (accessToken, refreshToken, profile, done) {
            process.nextTick(function () {
               console.log(profile)
            });
        }
    ));
```

For some of the Facebook accounts I don't get the email_id and I even tried by using a scope variable such as below, but still I am unable to get the email_id.

profileUrl : " "  and ProfileFields : ['','']

答:
I would like to add more information here.

While adding profileFields: ['emails'] while creating FacebookStrategy and passport.authorize('facebook', { scope : ['email'] }) solves issue for most of the users.

There are other possible reasons where you will not get  user's email after authentication.

No e-mail address on account

No confirmed e-mail address on account

No verified e-mail address on account

User entered a security checkpoint which required them to reconfirm
their e-mail address and they have not yet done so

User's e-mail address is unreachable

you need to make sure that your user does not have any of the issues listed above. more information can be found https://developers.facebook.com/bugs/1802930019968631/

Body:
I am using Passport-Facebook authentication.

  passport.use(new FacebookStrategy({
            clientID: 'CLIENT_ID',
            clientSecret: 'CLIENT_SECRET',
            callbackURL: "http://www.example.com/auth/facebook/callback"
        },
        function (accessToken, refreshToken, profile, done) {
            process.nextTick(function () {
               console.log(profile)
            });
        }
    ));

For some of the Facebook accounts I don't get the email_id and I even tried by using a scope variable such as below, but still I am unable to get the email_id.

profileUrl : " "  and ProfileFields : ['','']


问:
Is there a maximum size to char[]?
IN JAVA

Is there a maximum size of char[]? Can I have a char[5,000,000]?

Is array in java composed of contiguous memory blocks?

答:
Maximum size depends on the architecture.

In C, an array consists in contiguous memory blocks. You can have an array as big as you want, as long as it fits in RAM (including disk-based virtual memory). There is an exception: arrays declared as local variables are allocated on the stack, which is quite small. The typical size for the stack in a multi-threaded application on a PC will be 1 megabyte. If you want a big array, you'd better create it as a global variable, or allocate it dynamically (with malloc()).

In Java, arrays are heap-allocated (with new). Whether they are contiguous or not is "none of your business": the very essence of Java is about shielding the programmer from the concrete implementation details (but really, on most Java virtual machines, arrays are contiguous). Java arrays are created and indexed with values expressed as an int type; thus, a Java array cannot have more than about 2 billions elements, even if the machine has more RAM than that: an int cannot hold bigger values. 5 millions is a piece of cake, and I routinely allocate arrays bigger than that.

Title: Is there a maximum size to char[]?