问:
Extract URL from body of email
I have data to add to Excel. I found that we can do that by Outlook VBA. The content comes in the following format:

Title: Undergraduate student

Gender: Male

Country: Albania

Keyword:

1.Environment

2. Population

First Name: John

Phone number: 0532432444

Username: test@dda.com

File upload: http://all-free-download.com/free-photos/download/autumns-evening-sun_513398.html

I followed an old article and created this code:

Sub CopyToExcel()
    Dim xlApp As Object
    Dim xlWB As Object
    Dim xlSheet As Object

    Dim olItem As Outlook.MailItem
    Dim vText As Variant
    Dim sText As String
    Dim vItem As Variant

    Dim i As Long
    Dim rCount As Long
    Dim bXStarted As Boolean

    Const strPath As String = "E:\Project\Test oulook.xlsx"   ' the path of the workbook

    If Application.ActiveExplorer.Selection.Count = 0 Then
        MsgBox "No Items selected!", vbCritical, "Error"
        Exit Sub
    End If

    On Error Resume Next

    Set xlApp = GetObject(, "Excel.Application")
    If Err <> 0 Then
        Application.StatusBar = "Please wait while Excel source is opened ... "
        Set xlApp = CreateObject("Excel.Application")
        bXStarted = True
    End If

    On Error GoTo 0

    ' Open the workbook to input the data
    Set xlWB = xlApp.Workbooks.Open(strPath)
    Set xlSheet = xlWB.Sheets("Sheet1")

    ' Process each selected record
    rCount = xlSheet.UsedRange.Rows.Count
    For Each olItem In Application.ActiveExplorer.Selection
        sText = olItem.Body
        vText = Split(sText, Chr(13))

        ' Find the next empty line of the worksheet
        rCount = rCount + 1

        ' Check each line of text in the message body
        For i = UBound(vText) To 0 Step -1

            If InStr(1, vText(i), "title: ") > 0 Then
                vItem = Split(vText(i), Chr(58))
                xlSheet.Range("A" & rCount) = Trim(vItem(1))
            End If

            If InStr(1, vText(i), "gender: ") > 0 Then
                vItem = Split(vText(i), Chr(58))
                xlSheet.Range("B" & rCount) = Trim(vItem(1))
            End If

            If InStr(1, vText(i), "country: ") > 0 Then
                vItem = Split(vText(i), Chr(58))
                xlSheet.Range("C" & rCount) = Trim(vItem(1))
            End If

            If InStr(1, vText(i), "keyword: ") > 0 Then
                vItem = Split(vText(i), Chr(58))
                xlSheet.Range("E" & rCount) = Trim(vItem(1))
            End If

            If InStr(1, vText(i), "first_name: ") > 0 Then
                vItem = Split(vText(i), Chr(58))
                xlSheet.Range("G" & rCount) = Trim(vItem(1))
            End If

            If InStr(1, vText(i), "phone_number: ") > 0 Then
                vItem = Split(vText(i), Chr(58))
                xlSheet.Range("I" & rCount) = Trim(vItem(1))
            End If

            If InStr(1, vText(i), "username: ") > 0 Then
                vItem = Split(vText(i), Chr(58))
                xlSheet.Range("F" & rCount) = Trim(vItem(1))
            End If

            If InStr(1, vText(i), "upload: ") > 0 Then
                vItem = Split(vText(i), Chr(58))
                xlSheet.Range("O" & rCount) = Trim(vItem(1))
            End If

        Next i
        xlWB.Save

    Next olItem
    xlWB.Close SaveChanges:=True

    If bXStarted Then
        xlApp.Quit
    End If

    Set olItem = Nothing
    Set xlSheet = Nothing
    Set xlWB = Nothing
    Set xlApp = Nothing
End Sub
```

The upload field displays " http " not " http://all-free-download.com/free-photos/download/autumns-evening-sun_513398.html  ".

答:
Chr(58) is Colon

By doing Split(vText(i), Chr(58)), you are taking the original string and splitting it by the delimiter colon

eg: File upload: http://all-free-download.com/free-photos/download/autumns-evening-sun_513398.html

vItem(0)= File upload

vItem(1)= http

vItem(2)= //all-free-download.com/free-photos/download/autumns-evening-sun_513398.html

So in order to get the full link that you wanted, you have to concatenate vItem.

eg.  vItem(1) & ":" & vItem(2)

Title: Extract URL from body of email

Body:
I have data to add to Excel. I found that we can do that by Outlook VBA. The content comes in the following format:

Title: Undergraduate student

Gender: Male

Country: Albania

Keyword:

1.Environment

2. Population

First Name: John

Phone number: 0532432444

Username: test@dda.com

File upload: http://all-free-download.com/free-photos/download/autumns-evening-sun_513398.html

I followed an old article and created this code:

Sub CopyToExcel()
    Dim xlApp As Object
    Dim xlWB As Object
    Dim xlSheet As Object

    Dim olItem As Outlook.MailItem
    Dim vText As Variant
    Dim sText As String
    Dim vItem As Variant

    Dim i As Long
    Dim rCount As Long
    Dim bXStarted As Boolean

    Const strPath As String = "E:\Project\Test oulook.xlsx"   ' the path of the workbook

    If Application.ActiveExplorer.Selection.Count = 0 Then
        MsgBox "No Items selected!", vbCritical, "Error"
        Exit Sub
    End If

    On Error Resume Next

    Set xlApp = GetObject(, "Excel.Application")
    If Err <> 0 Then
        Application.StatusBar = "Please wait while Excel source is opened ... "
        Set xlApp = CreateObject("Excel.Application")
        bXStarted = True
    End If

    On Error GoTo 0

    ' Open the workbook to input the data
    Set xlWB = xlApp.Workbooks.Open(strPath)
    Set xlSheet = xlWB.Sheets("Sheet1")

    ' Process each selected record
    rCount = xlSheet.UsedRange.Rows.Count
    For Each olItem In Application.ActiveExplorer.Selection
        sText = olItem.Body
        vText = Split(sText, Chr(13))

        ' Find the next empty line of the worksheet
        rCount = rCount + 1

        ' Check each line of text in the message body
        For i = UBound(vText) To 0 Step -1

            If InStr(1, vText(i), "title: ") > 0 Then
                vItem = Split(vText(i), Chr(58))
                xlSheet.Range("A" & rCount) = Trim(vItem(1))
            End If

            If InStr(1, vText(i), "gender: ") > 0 Then
                vItem = Split(vText(i), Chr(58))
                xlSheet.Range("B" & rCount) = Trim(vItem(1))
            End If

            If InStr(1, vText(i), "country: ") > 0 Then
                vItem = Split(vText(i), Chr(58))
                xlSheet.Range("C" & rCount) = Trim(vItem(1))
            End If

            If InStr(1, vText(i), "keyword: ") > 0 Then
                vItem = Split(vText(i), Chr(58))
                xlSheet.Range("E" & rCount) = Trim(vItem(1))
            End If

            If InStr(1, vText(i), "first_name: ") > 0 Then
                vItem = Split(vText(i), Chr(58))
                xlSheet.Range("G" & rCount) = Trim(vItem(1))
            End If

            If InStr(1, vText(i), "phone_number: ") > 0 Then
                vItem = Split(vText(i), Chr(58))
                xlSheet.Range("I" & rCount) = Trim(vItem(1))
            End If

            If InStr(1, vText(i), "username: ") > 0 Then
                vItem = Split(vText(i), Chr(58))
                xlSheet.Range("F" & rCount) = Trim(vItem(1))
            End If

            If InStr(1, vText(i), "upload: ") > 0 Then
                vItem = Split(vText(i), Chr(58))
                xlSheet.Range("O" & rCount) = Trim(vItem(1))
            End If

        Next i
        xlWB.Save

    Next olItem
    xlWB.Close SaveChanges:=True

    If bXStarted Then
        xlApp.Quit
    End If

    Set olItem = Nothing
    Set xlSheet = Nothing
    Set xlWB = Nothing
    Set xlApp = Nothing
End Sub

The upload field displays " http " not " http://all-free-download.com/free-photos/download/autumns-evening-sun_513398.html  ".


来源: stackexchange

问:
How can I switch to a different tab group using the keyboard in visual studio 2013
Consider the following window setup:

Currently there are two tab groups open. The left tab group is active (with the ListingDetailsDTO.cs window active).

I would now like to switch to the right tab group, so visual studio will appear like this:

This is easily possible using the mouse (ie just left click the right window). However I cannot figure out how to do it with the keyboard alone. Assigning a shortcut to Window -> Move to next tab group came closest, but it also moves the current window to the next tab group, which isn't what I wanted. I thought Window.NextPane, or Window.NextSubpane might work, but they didn't.

Is there a way to do what I want? I am happy to install (preferably) free extensions to make this possible if necessary.

答:
For Visual Studio 2017/2019, I created an open-source extension to do this:

It by default adds two keyboard shortcuts:

Tools.NavigateTabGroups.Next (CTRL+SHIFT+Right) to move to the next tab group

Tools.NavigateTabGroups.Previous (CTRL+SHIFT+Left) to move to the previous group

There are six commands altogether (all of which can be assigned shortcuts):

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 4.0


问:
@Umbraco.TypedMedia(MyProperty) is null in Umbraco 7.6.1
I'm using Umbraco 7.6.1 and I'm trying to get the url for a media image using the code below in razor.

```<code>@{
   var bannerMediaItem = Umbraco.TypedMedia(Model.Content.Image);
   var bannerUrl = bannerMediaItem.Url;
}
</code>```

But bannerMediaItem is always null even though I know it exists. If I do this..

```<code>@Model.Content.Image
</code>```

It returns the id of the image e.g. 1086

答:
try this

```<code>var propertyValue = content.GetPropertyValue<int>(propertyName); // this will give you the id of the media item
var media = helper.TypedMedia(propertyValue);

var url = media == null ? string.Empty : media.Url;
</code>```

propertyName (string value) is the name of the property you have for your
banner.

content is the IPublishedContent

helper is the UmbracoHelper that you will get from Umbraco.Web

Thanks

Body:
I'm using Umbraco 7.6.1 and I'm trying to get the url for a media image using the code below in razor.

@{
   var bannerMediaItem = Umbraco.TypedMedia(Model.Content.Image);
   var bannerUrl = bannerMediaItem.Url;
}

But bannerMediaItem is always null even though I know it exists. If I do this..

@Model.Content.Image

It returns the id of the image e.g. 1086

Body:
try this

var propertyValue = content.GetPropertyValue<int>(propertyName); // this will give you the id of the media item
var media = helper.TypedMedia(propertyValue);

var url = media == null ? string.Empty : media.Url;

propertyName (string value) is the name of the property you have for your
banner.

content is the IPublishedContent

helper is the UmbracoHelper that you will get from Umbraco.Web

Thanks


问:
SQL Count rows in another table and join
I have 2 table in my database. The first is comments and the other is comments_votes.
I want to select all comments, and for each comment, select all it's votes from comments_votes, add them up together and join it with the first query as totalVote.

My comments table look like:

```<code>id      comment      video_id   date_sent
----------------------------------------
5      "...."           99        "2017-05-23"
18      "...."          99        "2017-05-23"
</code>```

comments_votes table look like:

```<code>id      user_id      comment_id   vote
----------------------------------------
45         86           5         1
45         23           5         1
78         12            18        -1
</code>```

And the final wished result would look like:

```<code>id      comment   video_id   votes_total
----------------------------------------
5      " ... "      99             2
18      "... "      99           -1
</code>```

I can manage simple SQL operations but this is beyond me. Is something like this even possible? If yes, how?

答:
```<code>select C.id, C.Comment, C.Video_ID, SUM(V.Votes) AS Vote_total
from comments C
left outer join comments_votes V
on C.id=V.comment_id
group by C.id, C.Comment, C.Video_ID
</code>```

Body:
I have 2 table in my database. The first is comments and the other is comments_votes.
I want to select all comments, and for each comment, select all it's votes from comments_votes, add them up together and join it with the first query as totalVote.

My comments table look like:

id      comment      video_id   date_sent
----------------------------------------
5      "...."           99        "2017-05-23"
18      "...."          99        "2017-05-23"

comments_votes table look like:

id      user_id      comment_id   vote
----------------------------------------
45         86           5         1
45         23           5         1
78         12            18        -1

And the final wished result would look like:

id      comment   video_id   votes_total
----------------------------------------
5      " ... "      99             2
18      "... "      99           -1

I can manage simple SQL operations but this is beyond me. Is something like this even possible? If yes, how?


问:
How to select specific class item from list?
how can I select specific class item from a list? I want to bind only Name in the label.

mycountry.cs

```<code>public class mycountry{

private string Id;
private string name;
private string capital;
private string majorcity;

public string ID { get{return Id;} set{Id = value;}}
public string Name { get{return name;} set{name = value;}}
public string Capital { get{return capital;} set{capital = value;}}
public string Majorcity { get{return majorcity;} set{majorcity = value;}}
}
</code>```

mycountrypage.xaml.cs

```<code>List<mycountry> c;
c =  DB.GetCountry();

ListView list = new ListView{
ItemsSource = c,
ItemTemplate = new DataTemplate(() =>{
Label name = new Label(); name.SetBinding(Label.TextProperty, c.?)}
}
</code>```

答:
use the existing TextCell type for simple cells</p>

```<code>list.ItemTemplate = new DataTemplate(typeof(TextCell));
list.ItemTemplate.SetBinding(TextCell.TextProperty, "Name");
</code>```

Body:
how can I select specific class item from a list? I want to bind only Name in the label.

mycountry.cs

public class mycountry{

private string Id;
private string name;
private string capital;
private string majorcity;

public string ID { get{return Id;} set{Id = value;}}
public string Name { get{return name;} set{name = value;}}
public string Capital { get{return capital;} set{capital = value;}}
public string Majorcity { get{return majorcity;} set{majorcity = value;}}
}

mycountrypage.xaml.cs

List<mycountry> c;
c =  DB.GetCountry();

ListView list = new ListView{
ItemsSource = c,
ItemTemplate = new DataTemplate(() =>{
Label name = new Label(); name.SetBinding(Label.TextProperty, c.?)}
}

Body:
use the existing TextCell type for simple cells

list.ItemTemplate = new DataTemplate(typeof(TextCell));
list.ItemTemplate.SetBinding(TextCell.TextProperty, "Name");


问:
Can you use a fixed size type and pointers together in the same union?
I'm investigating the possibility of defining a structure for a packet. I would like to set header variables in the packet and then set a pointer to the data part of the packet. My end goal is to be able to send this packet to a low level library that takes only a uint8_t*. I created this quick program to test the feasibility and it does not seem to work.

```<code>#include <iostream>
#include <cstdint>
#include <stdlib.h>

typedef union {
    struct {
        uint8_t header;
        uint8_t* data;
    };
    uint8_t* packet;
} sometype;

int main() {
    sometype s;
    s.header = 3;
    s.data = (uint8_t *) malloc(sizeof(uint8_t) * 2);
    s.data[0] = 1;
    s.data[1] = 2;

    for (unsigned int i = 0; i < 3; i++) {
        std::cout << s.packet[i] << std::endl;
    }

    std::cout << std::endl;

    std::cout << s.header << std::endl;
    std::cout << s.data[0] << std::endl;
    std::cout << s.data[1] << std::endl;
}
</code>```

My output is

```<code>�
�
�

</code>```

Which makes me realize I have some type of error in my code (I've never worked with union before). However, when I debug the program I can see the data in the union. Looking at the packet, I can see that this method does not appear to be working. The data in the packet is not 3, 1, 2. It is 300, 221, 020 instead.

```<code>(gdb) print s
$1 = {{header = 3 '\003', data = 0x613c20 "\001\002"}, packet = 0x400903 <main()+125> "\300\211ƿ`\020`"}
</code>```

Is this method that I am attempting valid? From google searches I saw someone say you can use whatever datatypes you want. Do I have to pack the structure using a pragma to get this to work or is this method not feasible?

答:
Yes, you have to use #pragma pack(1) to get the behavior most engineers expect.  And yes, this is how most communication low level software works.

Otherwise, compilers tend to align each element to its data size for performance and compatibility reasons.

There is enormous cross-compatibility with #pragma pack() across compilers.  See this for gcc.

Body:
I'm investigating the possibility of defining a structure for a packet. I would like to set header variables in the packet and then set a pointer to the data part of the packet. My end goal is to be able to send this packet to a low level library that takes only a uint8_t*. I created this quick program to test the feasibility and it does not seem to work.

#include <iostream>
#include <cstdint>
#include <stdlib.h>

typedef union {
    struct {
        uint8_t header;
        uint8_t* data;
    };
    uint8_t* packet;
} sometype;

int main() {
    sometype s;
    s.header = 3;
    s.data = (uint8_t *) malloc(sizeof(uint8_t) * 2);
    s.data[0] = 1;
    s.data[1] = 2;

    for (unsigned int i = 0; i < 3; i++) {
        std::cout << s.packet[i] << std::endl;
    }

    std::cout << std::endl;

    std::cout << s.header << std::endl;
    std::cout << s.data[0] << std::endl;
    std::cout << s.data[1] << std::endl;
}

My output is

�
�
�

Which makes me realize I have some type of error in my code (I've never worked with union before). However, when I debug the program I can see the data in the union. Looking at the packet, I can see that this method does not appear to be working. The data in the packet is not 3, 1, 2. It is 300, 221, 020 instead.

(gdb) print s
$1 = {{header = 3 '\003', data = 0x613c20 "\001\002"}, packet = 0x400903  "\300\211ƿ`\020`"}

Is this method that I am attempting valid? From google searches I saw someone say you can use whatever datatypes you want. Do I have to pack the structure using a pragma to get this to work or is this method not feasible?


问:
TLS: hard disable cipher vs not listing it
In the below TSL1.2 cipher list, why should one explicitly disable RC4 instead of just removing it from the list of ciphers.

```<code>ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:RSA+AESGCM:RSA+AES:!RC4
</code>```

What problems does it cause? Anything that I should be careful about with respect to client/server SSL communication?

答:
Yes you don't need !RC4 or even -RC4 because none of your terms ever adds any RC4 ciphersuites.

To be on the safe side, you might add -aNULL or !aNULL because your terms do add many anonymous suites. In practice many probably most or all of the systems you connect to won't negotiate any anonymous suite anyway, but it's best to make sure they can't.

I assume by SSL you actually mean the TLS protocol(s), preferably at least version 1.1. Because TLS (through 1.2 at least) is based on and very similar to SSL3 much software and documentation continues to use the old name, but you should be certain you never use the actual SSL3 protocol which is now badly broken by POODLE, and should try to avoid TLS1.0 which has the exposed-IV flaw that was exploited by BEAST although most stacks now adequately mitigate BEAST using 1/n (or sometimes 0/n) record splitting. And the GCM ciphersuites you prefer (by putting them first) only work in TLS1.2 (or 1.3 if and when it gets finalized and implemented).

Other more general considerations:

if you are the server, possess and configure at least one type (RSA, DSA, ECDSA) of privatekey that is sufficiently strong, generated properly, and protected from unauthorized disclosure, and a matching certificate chain from a CA the client(s) will trust, using sufficiently strong signatures (currently sha256 or better with RSA-2048 DSA-2048 ECC-224 or better), and for most application protocols (like HTTPS) containing the correct hostname(s). Since RSA is the algorithm most commonly certifiable by widely trusted CAs, the only one that can cover all the keyexchange terms you have gone to the trouble of adding, and the only one covered by the instructions copied to billions of websites by people who don't understand them and therefore can't improve them, you probably want RSA.

if you are the client, verify the server cert chain against trustworthy CAs and when applicable the hostname. Note that OpenSSL always (unless overridden) does the standard crypto (signature) and syntax (BC KU EKU policy etc) verification to a supplied truststore (roots or optionally anchors), but client through 1.0.2 doesn't check the hostname for you, and 1.1.0 only does if you explicitly configure it. OpenSSL does not check CRLs by default and does not fetch them, doesn't fetch OCSP, and AFAICS doesn't even check stapled OCSP yet, so you should add at least some of these, but I don't think many developers do.

In the rare case client authentication aka client cert[ificate] is used, mirror the above: client that wishes or agrees to authenticate must possess and use suitable privatekey and certificate chain, and server must verify it but usually not hostname and definitely not using stapling.

if you are the server, configure sufficiently strong and properly generated DHE (called tmp_dh) parameters -- 2048 bits is now the standard, unless you have to deal with obsolete clients (like Java 7) that can't handle it; and depending on OpenSSL version ECDHE (called tmp_ecdh) parameters -- P-256 or P-384 is usually best. 1.0.2+ can and should be set to choose ECDHE based on ClientHello 'auto'matically; below that for ECDHE, and in all versions for DHE, if you don't configure the parameters the associated ciphersuites won't be used even though you configured them as preferred.

If you are client try to verify the above, although verifying anything about DHE parameters other than raw size without generation information (which SSL/TLS does not carry in-band) is too hard. In the very rare case of 'explicit' (non-named) EC parameters for ECDHE verifying is too hard, but for named curves and especially the common ones (P-256 and P-384 blessed by former Suite B) you can rely on the (open) community having focussed attention on them.

Don't use SSL/TLS compression if you send sensitive data (like cookies) in the same record as attacker-influenced data. Many stacks never allow SSL/TLS compression, since application-level compression can usually perform better and cheaper for applications that need it, e.g. HTTP[S].

Body:
In the below TSL1.2 cipher list, why should one explicitly disable RC4 instead of just removing it from the list of ciphers.

ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:RSA+AESGCM:RSA+AES:!RC4

What problems does it cause? Anything that I should be careful about with respect to client/server SSL communication?


问:
How do you get the user to add to a list?
I want to make it so the user clicks a button, it opens up a dialog box, the user types in the name of an item, then it adds the item to a list. So far, I've gotten to where the dialog box opens up with an EditText, an OK and a Cancel button that dismisses the box. How do I do this? Here is my .java File:

```<code>package com.shoppinglist;

import android.app.ListActivity;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class ShoppingList extends Activity {
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    Button button1main = (Button) findViewById(R.id.Button01main);
    button1main.setOnClickListener(new OnClickListener()  {
     @Override
      public void onClick(View v)  {
       final Dialog dialog = new Dialog(ShoppingList.this);
       dialog.setContentView(R.layout.maindialog);
       dialog.setCancelable(true);

       Button button = (Button) dialog.findViewById(R.id.cancel);
       button.setOnClickListener(new OnClickListener()  {
        @Override
         public void onClick(View v)  {
          dialog.dismiss();
        }
        });
       dialog.show();
       }
     });
    }
}
</code>```

Thanks in advance!!!

答:
You can create a listView to hold your items. Use an array adapter to hold the item objects. One easy way out is to create a ListActivity instead of Activity and set your "Add item" button as a header or footer view. This way you can always display that button no matter how many items you have.

Look at the SDK for examples on ListViews. There are plenty of them.

ContentLicense: CC BY-SA 2.5

Body:
I want to make it so the user clicks a button, it opens up a dialog box, the user types in the name of an item, then it adds the item to a list. So far, I've gotten to where the dialog box opens up with an EditText, an OK and a Cancel button that dismisses the box. How do I do this? Here is my .java File:

package com.shoppinglist;

import android.app.ListActivity;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class ShoppingList extends Activity {
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    Button button1main = (Button) findViewById(R.id.Button01main);
    button1main.setOnClickListener(new OnClickListener()  {
     @Override
      public void onClick(View v)  {
       final Dialog dialog = new Dialog(ShoppingList.this);
       dialog.setContentView(R.layout.maindialog);
       dialog.setCancelable(true);

       Button button = (Button) dialog.findViewById(R.id.cancel);
       button.setOnClickListener(new OnClickListener()  {
        @Override
         public void onClick(View v)  {
          dialog.dismiss();
        }
        });
       dialog.show();
       }
     });
    }
}

Thanks in advance!!!


问:
How to import jquery using ES6 syntax?
I'm writing a new app using (JavaScript) ES6 syntax through babel transpiler and the preset-es2015 plugins, as well as semantic-ui for the style.

index.js

```<code>import * as stylesheet from '../assets/styles/app.scss';
import * as jquery2 from '../dist/scripts/jquery.min';
import * as jquery3 from '../node_modules/jquery/dist/jquery.min';

console.log($('my-app'));
</code>```

index.html

```<code><!DOCTYPE html>
<html lang="fr">
<head>
<body>
<script src="dist/app.js"></script>
</body>
</html>
</code>```

Project structure

```<code>.
├── app/
│   ├── index.js
├── assets/
├── dist/
│   ├── scripts/
│   │   ├── jquery.min.js
├── index.html
├── node_modules/
│   ├── jquery/
│   │   ├── dist/
│   │   │   ├── jquery.min.js
├── package.json
└── tests/
</code>```

package.json

```<code>  …
  "scripts": {
    "build:app": "browserify -e ./app/index.js -o ./dist/app.js",
    "copy:jquery": "cpy 'node_modules/jquery/dist/jquery.min.js' ./dist/scripts/",
    …
  },
  "devDependencies": {
    "babel-core": "6.3.x",
    "babel-preset-es2015": "6.3.x",
    "babelify": "7.2.x",
    "cpy": "3.4.x",
    "npm-run-all": "1.4.x",
    "sassify": "0.9.x",
    "semantic-ui": "2.1.x",
    …
  },
  "browserify": {
    "transform": [
      [ "babelify", { "presets": [ "es2015"]}],
      [ "sassify", { "auto-inject": true}]
    ]
  }
</code>```

Question

Using classic

答:
Import the entire JQuery's contents in the Global scope. This inserts $ into the current scope, containing all the exported bindings from the JQuery.

```<code>import * as $ from 'jquery';
</code>```

Now the $ belongs to the window object.

Title: How to import jquery using ES6 syntax?

Body:
I'm writing a new app using (JavaScript) ES6 syntax through babel transpiler and the preset-es2015 plugins, as well as semantic-ui for the style.

index.js

import * as stylesheet from '../assets/styles/app.scss';
import * as jquery2 from '../dist/scripts/jquery.min';
import * as jquery3 from '../node_modules/jquery/dist/jquery.min';

console.log($('my-app'));

index.html

<!DOCTYPE html>

Project structure

.
├── app/
│   ├── index.js
├── assets/
├── dist/
│   ├── scripts/
│   │   ├── jquery.min.js
├── index.html
├── node_modules/
│   ├── jquery/
│   │   ├── dist/
│   │   │   ├── jquery.min.js
├── package.json
└── tests/

package.json

  …
  "scripts": {
    "build:app": "browserify -e ./app/index.js -o ./dist/app.js",
    "copy:jquery": "cpy 'node_modules/jquery/dist/jquery.min.js' ./dist/scripts/",
    …
  },
  "devDependencies": {
    "babel-core": "6.3.x",
    "babel-preset-es2015": "6.3.x",
    "babelify": "7.2.x",
    "cpy": "3.4.x",
    "npm-run-all": "1.4.x",
    "sassify": "0.9.x",
    "semantic-ui": "2.1.x",
    …
  },
  "browserify": {
    "transform": [
      [ "babelify", { "presets": [ "es2015"]}],
      [ "sassify", { "auto-inject": true}]
    ]
  }

Question

Using classic

Body:
Import the entire JQuery's contents in the Global scope. This inserts $ into the current scope, containing all the exported bindings from the JQuery.

import * as $ from 'jquery';

Now the $ belongs to the window object.


答:
```<code>If InStr(1, vText(i), "upload: ") > 0 Then
    vItem = Split(vText(i), Chr(58), 2) '<< optional parameter controls how many splits...
    xlSheet.Range("O" & rCount) = Trim(vItem(1))
End If
</code>```

Title: Extract URL from body of email


问:
Create a custom animatable property
On UIView you can change the backgroundColour animated. And on a UISlideView you can change the value animated.

Can you add a custom property to your own UIView subclass so that it can be animated?

If I have a CGPath within my UIView then I can animate the drawing of it by changing the percentage drawn of the path.

Can I encapsulate that animation into the subclass.

i.e. I have a UIView with a CGPath that creates a circle.

If the circle is not there it represents 0%. If the circle is full it represents 100%. I can draw any value by changing the percentage drawn of the path. I can also animate the change (within the UIView subclass) by animating the percentage of the CGPath and redrawing the path.

Can I set some property (i.e. percentage) on the UIView so that I can stick the change into a UIView animateWithDuration block and it animate the change of the percentage of the path?

I hope I have explained what I would like to do well.

Essentially, all I want to do is something like...

```<code>[UIView animateWithDuration:1.0
 animations:^{
     myCircleView.percentage = 0.7;
 }
 completion:nil];
</code>```

and the circle path animate to the given percentage.

答:
Complete Swift 3 example:

```<code>public class CircularProgressView: UIView {

    public dynamic var progress: CGFloat = 0 {
        didSet {
            progressLayer.progress = progress
        }
    }

    fileprivate var progressLayer: CircularProgressLayer {
        return layer as! CircularProgressLayer
    }

    override public class var layerClass: AnyClass {
        return CircularProgressLayer.self
    }

    override public func action(for layer: CALayer, forKey event: String) -> CAAction? {
        if event == #keyPath(CircularProgressLayer.progress),
            let action = action(for: layer, forKey: #keyPath(backgroundColor)) as? CAAnimation,
            let animation: CABasicAnimation = (action.copy() as? CABasicAnimation) {
            animation.keyPath = #keyPath(CircularProgressLayer.progress)
            animation.fromValue = progressLayer.progress
            animation.toValue = progress
            self.layer.add(animation, forKey: #keyPath(CircularProgressLayer.progress))
            return animation
        }
        return super.action(for: layer, forKey: event)
    }

}

/*
* Concepts taken from:
* https://stackoverflow.com/a/37470079
*/
fileprivate class CircularProgressLayer: CALayer {
    @NSManaged var progress: CGFloat
    let startAngle: CGFloat = 1.5 * .pi
    let twoPi: CGFloat = 2 * .pi
    let halfPi: CGFloat = .pi / 2

    override class func needsDisplay(forKey key: String) -> Bool {
        if key == #keyPath(progress) {
            return true
        }
        return super.needsDisplay(forKey: key)
    }

    override func draw(in ctx: CGContext) {
        super.draw(in: ctx)

        UIGraphicsPushContext(ctx)

        //Light Grey
        UIColor.lightGray.setStroke()

        let center = CGPoint(x: bounds.midX, y: bounds.midY)
        let strokeWidth: CGFloat = 4
        let radius = (bounds.size.width / 2) - strokeWidth
        let path = UIBezierPath(arcCenter: center, radius: radius, startAngle: 0, endAngle: twoPi, clockwise: true)
        path.lineWidth = strokeWidth
        path.stroke()

        //Red
        UIColor.red.setStroke()

        let endAngle = (twoPi * progress) - halfPi
        let pathProgress = UIBezierPath(arcCenter: center, radius: radius, startAngle: startAngle, endAngle: endAngle , clockwise: true)
        pathProgress.lineWidth = strokeWidth
        pathProgress.lineCapStyle = .round
        pathProgress.stroke()

        UIGraphicsPopContext()
    }
}

let circularProgress = CircularProgressView(frame: CGRect(x: 0, y: 0, width: 80, height: 80))
UIView.animate(withDuration: 2, delay: 0, options: .curveEaseInOut, animations: {
    circularProgress.progress = 0.76
}, completion: nil)
</code>```

There is a great objc article here, which goes into details about how this works

As well as a objc project that uses the same concepts here:

Essentially action(for layer:) will be called when an object is being animated from an animation block, we can start our own animations with the same properties (stolen from the backgroundColor property) and animate the changes.

Title: Create a custom animatable property

Body:
On UIView you can change the backgroundColour animated. And on a UISlideView you can change the value animated.

Can you add a custom property to your own UIView subclass so that it can be animated?

If I have a CGPath within my UIView then I can animate the drawing of it by changing the percentage drawn of the path.

Can I encapsulate that animation into the subclass.

i.e. I have a UIView with a CGPath that creates a circle.

If the circle is not there it represents 0%. If the circle is full it represents 100%. I can draw any value by changing the percentage drawn of the path. I can also animate the change (within the UIView subclass) by animating the percentage of the CGPath and redrawing the path.

Can I set some property (i.e. percentage) on the UIView so that I can stick the change into a UIView animateWithDuration block and it animate the change of the percentage of the path?

I hope I have explained what I would like to do well.

Essentially, all I want to do is something like...

[UIView animateWithDuration:1.0
 animations:^{
     myCircleView.percentage = 0.7;
 }
 completion:nil];

and the circle path animate to the given percentage.

Body:
Complete Swift 3 example:

public class CircularProgressView: UIView {

    public dynamic var progress: CGFloat = 0 {
        didSet {
            progressLayer.progress = progress
        }
    }

    fileprivate var progressLayer: CircularProgressLayer {
        return layer as! CircularProgressLayer
    }

    override public class var layerClass: AnyClass {
        return CircularProgressLayer.self
    }

    override public func action(for layer: CALayer, forKey event: String) -> CAAction? {
        if event == #keyPath(CircularProgressLayer.progress),
            let action = action(for: layer, forKey: #keyPath(backgroundColor)) as? CAAnimation,
            let animation: CABasicAnimation = (action.copy() as? CABasicAnimation) {
            animation.keyPath = #keyPath(CircularProgressLayer.progress)
            animation.fromValue = progressLayer.progress
            animation.toValue = progress
            self.layer.add(animation, forKey: #keyPath(CircularProgressLayer.progress))
            return animation
        }
        return super.action(for: layer, forKey: event)
    }

}

/*
* Concepts taken from:
* https://stackoverflow.com/a/37470079
*/
fileprivate class CircularProgressLayer: CALayer {
    @NSManaged var progress: CGFloat
    let startAngle: CGFloat = 1.5 * .pi
    let twoPi: CGFloat = 2 * .pi
    let halfPi: CGFloat = .pi / 2

    override class func needsDisplay(forKey key: String) -> Bool {
        if key == #keyPath(progress) {
            return true
        }
        return super.needsDisplay(forKey: key)
    }

    override func draw(in ctx: CGContext) {
        super.draw(in: ctx)

        UIGraphicsPushContext(ctx)

        //Light Grey
        UIColor.lightGray.setStroke()

        let center = CGPoint(x: bounds.midX, y: bounds.midY)
        let strokeWidth: CGFloat = 4
        let radius = (bounds.size.width / 2) - strokeWidth
        let path = UIBezierPath(arcCenter: center, radius: radius, startAngle: 0, endAngle: twoPi, clockwise: true)
        path.lineWidth = strokeWidth
        path.stroke()

        //Red
        UIColor.red.setStroke()

        let endAngle = (twoPi * progress) - halfPi
        let pathProgress = UIBezierPath(arcCenter: center, radius: radius, startAngle: startAngle, endAngle: endAngle , clockwise: true)
        pathProgress.lineWidth = strokeWidth
        pathProgress.lineCapStyle = .round
        pathProgress.stroke()

        UIGraphicsPopContext()
    }
}

let circularProgress = CircularProgressView(frame: CGRect(x: 0, y: 0, width: 80, height: 80))
UIView.animate(withDuration: 2, delay: 0, options: .curveEaseInOut, animations: {
    circularProgress.progress = 0.76
}, completion: nil)

There is a great objc article here, which goes into details about how this works

As well as a objc project that uses the same concepts here:

Essentially action(for layer:) will be called when an object is being animated from an animation block, we can start our own animations with the same properties (stolen from the backgroundColor property) and animate the changes.


问:
How can I use bash's select on a newline-separated list?
How can I use bash's select on a newline-separated list?

I'm actually trying to improve the following snippet in a working script:

```<code># for example
nwd=/media/$USER/some-drive

# This makes a newline-separated list. I'm open to options that make a
# list in a different fashion. I usually loop with find -print0 for this
# kind of thing, but I don't know an easy way to omit a particular
# element ($nwd) from a null-separated list.
volumes="$( ls /media/$USER | grep -v "$( basename -- "$nwd" )" )"

# If there's only one option, I don't need the user to choose.
if [ 1 -eq "$( echo "$volumes" | wc -l )" ]; then
  mount_point="/media/$USER/$volumes"
else
  # KNOWN BUG: It is impossible to select devices with spaces in their names.
  echo "Please select the appropriate device:"
  select mount_point in $volumes Quit; do
    case "$mount_point" in
    Quit ) exit $EXIT_USER_HALT;;
    '' ) echo "Invalid option. Try another one." >&2;continue;;
    * ) break;;
    esac
  done
  mount_point="/media/$USER/$mount_point"
fi
</code>```

答:
Using extended patterns, you can populate an array with the desired file names:

```<code>shopt -s extglob
nwd=/media/$USER/some-drive
volumes=( /media/$USER/!("$(basename -- "$nwd")") )
# Or more generally,
# volumes=( "$(dirname -- "$nwd")"/!("$(basename -- "$nwd")") )
</code>```

Then you can use the array as

```<code>if (( ${#volumes[@]} == 1 )); then
    mount_point="/media/$USER/$volumes"  # or ${volumes[0]}
else
    echo "Please select the appropriate device:"
    select mount_point in "${volumes[@]}" Quit; do
        case $mount_point in
            Quit) exit $EXIT_USER_HALT ;;
            '') echo "Invalid option. Try another one." >&2; continue ;;
            *) break ;;
        esac
    done
fi
</code>```

Using an array also fixes the inability to select mount points whose name contains a space. (In fact, it will work with any valid file path, including those that might contain glob metacharacters or newlines.)

Body:
How can I use bash's select on a newline-separated list?

I'm actually trying to improve the following snippet in a working script:

# for example
nwd=/media/$USER/some-drive

# This makes a newline-separated list. I'm open to options that make a
# list in a different fashion. I usually loop with find -print0 for this
# kind of thing, but I don't know an easy way to omit a particular
# element ($nwd) from a null-separated list.
volumes="$( ls /media/$USER | grep -v "$( basename -- "$nwd" )" )"

# If there's only one option, I don't need the user to choose.
if [ 1 -eq "$( echo "$volumes" | wc -l )" ]; then
  mount_point="/media/$USER/$volumes"
else
  # KNOWN BUG: It is impossible to select devices with spaces in their names.
  echo "Please select the appropriate device:"
  select mount_point in $volumes Quit; do
    case "$mount_point" in
    Quit ) exit $EXIT_USER_HALT;;
    '' ) echo "Invalid option. Try another one." >&2;continue;;
    * ) break;;
    esac
  done
  mount_point="/media/$USER/$mount_point"
fi

Body:
Using extended patterns, you can populate an array with the desired file names:

shopt -s extglob
nwd=/media/$USER/some-drive
volumes=( /media/$USER/!("$(basename -- "$nwd")") )
# Or more generally,
# volumes=( "$(dirname -- "$nwd")"/!("$(basename -- "$nwd")") )

Then you can use the array as

if (( ${#volumes[@]} == 1 )); then
    mount_point="/media/$USER/$volumes"  # or ${volumes[0]}
else
    echo "Please select the appropriate device:"
    select mount_point in "${volumes[@]}" Quit; do
        case $mount_point in
            Quit) exit $EXIT_USER_HALT ;;
            '') echo "Invalid option. Try another one." >&2; continue ;;
            *) break ;;
        esac
    done
fi

Using an array also fixes the inability to select mount points whose name contains a space. (In fact, it will work with any valid file path, including those that might contain glob metacharacters or newlines.)


问:
ImportError: No module named 'theano'
I have installed (/library/python/2.7/site-packages) theano on my mac and still get this error.

My code is

```<code>import theano
theano.test()
</code>```

and the error

```<code>Traceback (most recent call last):
  File "/Users/mac/Downloads/n.py", line 1, in <module>
    import theano
ImportError: No module named 'theano'
</code>```

I did install theano using pip install theano for python 2.7.

Any idea on why its throwing up the error.

Also I installed Anaconda and it throws the same error as working on idle.

答:
I had similiar problem too,I tried serval methods,but not work.
Last,this commond help me.
you can try:

pip install -r
  https://raw.githubusercontent.com/Lasagne/Lasagne/v0.1/requirements.txt

pip install -r
  https://raw.githubusercontent.com/Lasagne/Lasagne/master/requirements.txt

pip install https://github.com/Lasagne/Lasagne/archive/master.zip

pip install -r
  https://raw.githubusercontent.com/dnouri/kfkd-tutorial/master/requirements.txt

Title: ImportError: No module named 'theano'

Body:
I have installed (/library/python/2.7/site-packages) theano on my mac and still get this error.

My code is

import theano
theano.test()

and the error

Traceback (most recent call last):
  File "/Users/mac/Downloads/n.py", line 1, in <module>
    import theano
ImportError: No module named 'theano'

I did install theano using pip install theano for python 2.7.

Any idea on why its throwing up the error.

Also I installed Anaconda and it throws the same error as working on idle.


问:
WordPress REST API: Can't upload content-type image/jpeg
The WordPress REST API apparently won't let me upload a file with content-type 'image/jpeg'.

If I set content-type to an empty string, I'm able to create a media item and upload an attached file (which appears in both the media library and the wp_content/uploads directory). Doing this, however, results in an invalid image which WordPress can't process.

This is the code I'm using:

```<code>def post():
    url = 'https://www.example.com/wp-json/wp/v2/media'
    data = open('C:\\Pictures\\foo.jpg', 'rb').read()
    r = requests.post(url=url,
                    files={'filename1': data},
                    data={'title': 'Files test'},
                    headers={'Content-Type': '', 'Content-Disposition': 'attachment; filename={}'.format('foo.jpg')},
                    auth=('username', 'password'))
    return (r.status_code, r.text)
</code>```

When I set Content-Type to 'image/jpg', 'image/jpeg', 'image', 'multipart', 'application' or 'application/image' (I'm getting desperate) I get a 403.

If I set it to 'application/json' as suggested by others, I get a 400 with 'invalid JSON body passed'.

If I omit Content-Type I get a 500 with the following message:

```<code>{"code":"rest_upload_unknown_error","message":"File is empty. Please upload something more substantial. This error could also be caused by uploads being disabled in your php.ini or by post_max_size being defined as smaller than upload_max_filesize in php.ini.","data": {"status":500}}')
</code>```

My file is not empty (it's 26kB) and the suggested PHP.ini errors presumably can't apply if I am able to upload a file with Content-Type = ''.

Any suggestions, please?

答:
Okay, I've got a workaround which uploads the image properly (by simply uploading data rather than a file):

```<code>def post():
    url = 'https://www.example.com/wp-json/wp/v2/media'
    data = open('C:\\Pictures\\foo.jpg', 'rb').read()
    r = requests.post(url=url,
                    data=data,
                    headers={'Content-Type': '', 'Content-Disposition': 'attachment; filename={}'.format('foo.jpg')},
                    auth=('username', 'password'))
    return (r.status_code, r.text)
</code>```

Note that Content-Type is still set to '', but somehow it now works.

Body:
The WordPress REST API apparently won't let me upload a file with content-type 'image/jpeg'.

If I set content-type to an empty string, I'm able to create a media item and upload an attached file (which appears in both the media library and the wp_content/uploads directory). Doing this, however, results in an invalid image which WordPress can't process.

This is the code I'm using:

def post():
    url = 'https://www.example.com/wp-json/wp/v2/media'
    data = open('C:\\Pictures\\foo.jpg', 'rb').read()
    r = requests.post(url=url,
                    files={'filename1': data},
                    data={'title': 'Files test'},
                    headers={'Content-Type': '', 'Content-Disposition': 'attachment; filename={}'.format('foo.jpg')},
                    auth=('username', 'password'))
    return (r.status_code, r.text)

When I set Content-Type to 'image/jpg', 'image/jpeg', 'image', 'multipart', 'application' or 'application/image' (I'm getting desperate) I get a 403.

If I set it to 'application/json' as suggested by others, I get a 400 with 'invalid JSON body passed'.

If I omit Content-Type I get a 500 with the following message:

{"code":"rest_upload_unknown_error","message":"File is empty. Please upload something more substantial. This error could also be caused by uploads being disabled in your php.ini or by post_max_size being defined as smaller than upload_max_filesize in php.ini.","data": {"status":500}}')

My file is not empty (it's 26kB) and the suggested PHP.ini errors presumably can't apply if I am able to upload a file with Content-Type = ''.

Any suggestions, please?

Body:
Okay, I've got a workaround which uploads the image properly (by simply uploading data rather than a file):

def post():
    url = 'https://www.example.com/wp-json/wp/v2/media'
    data = open('C:\\Pictures\\foo.jpg', 'rb').read()
    r = requests.post(url=url,
                    data=data,
                    headers={'Content-Type': '', 'Content-Disposition': 'attachment; filename={}'.format('foo.jpg')},
                    auth=('username', 'password'))
    return (r.status_code, r.text)

Note that Content-Type is still set to '', but somehow it now works.


问:
Create cron job to run with MySQL
I've got a code that will delete a WordPress post from my database if it contains a certain text:

```<code>DELETE FROM wp_posts WHERE post_excerpt LIKE "%neuroscience%"
</code>```

I want to get this to run every hour, but I don't know if I should initiate this within the MySQL platform, or via cPanel. I would prefer the latter so all my cron jobs would be in one place. But the truth is I don't know how to code either!

答:
Why not just CREATE TRIGGER in MySQL itself ?
It will delete the post whenever they occur and if you use BEFORE UPDATE it won't even get into the database.

Title: Create cron job to run with MySQL

Body:
I've got a code that will delete a WordPress post from my database if it contains a certain text:

DELETE FROM wp_posts WHERE post_excerpt LIKE "%neuroscience%"

I want to get this to run every hour, but I don't know if I should initiate this within the MySQL platform, or via cPanel. I would prefer the latter so all my cron jobs would be in one place. But the truth is I don't know how to code either!


问:
Customized look on first login
I'm working on a java Spring webapp. There is requirement that each user will have possibility to customize the webapp look & feel. I'd like if the user will see the customized look, even on his first login. How would you do that?

My ideas are for the time being

multiple contexts(per customer), but it is not dynamic

send user a link with some attribute, then set the custom info to cookies

in Spring I can possibly create some path variable (@RequestMapping(value = "/{customerId}/login"))

just create universal login page, which will be not customizable

How would you achieve that?

答:
You can give separate URLs to each user, could be using sub-domain or url parameters. Then fetch the request URL in your handling page to deliver specific look-n-feel.

You could also try to explore GrooveUI, which is a third party tool that allows you to define website theme based on access URL.

Title: Customized look on first login


问:
Enable Controls - Colour stripping issue
I currently have a couple of checkboxes performing the below code.

```<code>Private Sub CheckBox2_Click()
    Dim en As Boolean
    en = CheckBox2.Value
    EnableControls Array(CheckBox3, CheckBox4, CheckBox5, CheckBox6, CheckBox7, CheckBox9, CheckBox10, CheckBox11, TextBox1), en

End Sub

Private Sub EnableControls(cons, bEnable As Boolean)
    Dim con
    For Each con In cons
        With con
            .Enabled = bEnable
            .BackColor = IIf(bEnable, vbWhite, RGB(240, 240, 240))
        End With
    Next con
End Sub
</code>```

So when Checkbox=False the other checkbox fields are greyed out and you are unable to check them. However, once they are ungreyed out their whole back colour goes from the default "form background grey" to a bold white - any ideas on how to just grey the boxes out and when they are 'un-greyed' they just go back to their default colour????

答: A little testing shows you can leave your code as-is and set your checkboxes' BackStyle to fmBackStyleTransparent in the form designer

Body:
I currently have a couple of checkboxes performing the below code.

Private Sub CheckBox2_Click()
    Dim en As Boolean
    en = CheckBox2.Value
    EnableControls Array(CheckBox3, CheckBox4, CheckBox5, CheckBox6, CheckBox7, CheckBox9, CheckBox10, CheckBox11, TextBox1), en

End Sub

Private Sub EnableControls(cons, bEnable As Boolean)
    Dim con
    For Each con In cons
        With con
            .Enabled = bEnable
            .BackColor = IIf(bEnable, vbWhite, RGB(240, 240, 240))
        End With
    Next con
End Sub

So when Checkbox=False the other checkbox fields are greyed out and you are unable to check them. However, once they are ungreyed out their whole back colour goes from the default "form background grey" to a bold white - any ideas on how to just grey the boxes out and when they are 'un-greyed' they just go back to their default colour????


问:
ListView inside Gridview
I would like to use a GridView layout, so that every item of the Gridlayout has its own ListView. I have been looking for code sample but I haven't found any. Should I use different adapter classes for the GridView and the ListView?
Thank you in advance!

Edit: I have created a GridView that displays all the some tiles, and I want every grid item to include a list, so I have added a ListView to the layout of the GridView items. Unfortunately I 'm having problems connecting the listview to the adapter.

This is the adapter of the gridView:

```<code>public class MainViewAdapter extends ArrayAdapter<Category> {
private Context mContext;
private int layoutResourceId;
private ArrayList<Category> mGridData = new ArrayList<Category>();
ArrayAdapter adapter;

public MainViewAdapter(Context mContext, int layoutResourceId, ArrayList<Category> mGridData) {
    super(mContext, layoutResourceId, mGridData);
    this.layoutResourceId = layoutResourceId;
    this.mContext = mContext;
    this.mGridData = mGridData;
}

public void setGridData(ArrayList<Category> mGridData) {
    this.mGridData = mGridData;
    notifyDataSetChanged();
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View row = convertView;
    ViewHolder holder;
    String imageUrl;

    if (row == null) {
        LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
        row = inflater.inflate(layoutResourceId, parent, false);
        holder = new ViewHolder();
        holder.SubListView = (ListView) row.findViewById(R.id.SubList);
        holder.titleTextView = (TextView) row.findViewById(R.id.category_title);
        holder.simpleDraweeView = (SimpleDraweeView) row.findViewById(R.id.category_image);
        row.setTag(holder);
    } else {
        holder = (ViewHolder) row.getTag();
    }

    Category category = mGridData.get(position);
    Log.i("position", "" + position);
    holder.titleTextView.setText(Html.fromHtml(category.getTitle()));
    imageUrl = category.getImage();
    Log.i("image url",imageUrl );
    Uri imageUri = Uri.parse(imageUrl);
    holder.simpleDraweeView.setImageURI(imageUri);

    List SubCategories = category.getSubCateg();
    Log.i("@MainViewAdapter - SubCategories", category.getSubCateg().toString());

    //list SubCategories to ArrayList
    ArrayList<SubCategory> listOfSub = new ArrayList<>(SubCategories.size());
    listOfSub.addAll(SubCategories);
    Log.i("listOfSub",listOfSub.toString());

    //ArrayList to ListView
    holder.SubListView.setAdapter(adapter);

    return row;
}

static class ViewHolder {
    TextView titleTextView;
    SimpleDraweeView simpleDraweeView;
    ListView SubListView;
}}
</code>```

And here is the adapter of the listview:

```<code>public class SubListAdapter extends ArrayAdapter<SubCategory> {
private int layoutResourceId;
private ArrayList<SubCategory> mSubGridData = new ArrayList<SubCategory>();
ArrayAdapter adapter;

private final Context mContext;

public SubListAdapter(Context mContext, int layoutResourceId, ArrayList<SubCategory> mSubGridData) {
    super(mContext, R.layout.subcategory_item, mSubGridData);

    this.layoutResourceId = layoutResourceId;
    this.mContext = mContext;
    this.mSubGridData = mSubGridData;
}

public void setSubGridData(ArrayList<SubCategory> mSubGridData) {
    this.mSubGridData = mSubGridData;
    notifyDataSetChanged();
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    View row = convertView;
    SubListAdapter.ViewHolder holder;
    String imageUrl;

    if (row == null) {
        LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
        row = inflater.inflate(layoutResourceId, parent, false);
        holder = new ViewHolder();
        holder.SubTitleTextView = (TextView) row.findViewById(R.id.subCatItemTitle);
        row.setTag(holder);
    } else {
        holder = (SubListAdapter.ViewHolder) row.getTag();

    return rowView;
}

static class ViewHolder {
    TextView SubTitleTextView;
    ListView SubListView;
}}
</code>```

I am having some problems with the second adapter.

答:
You just create a GridView android setAdapter for it .in this adapter ,create a layout.xml which has a listView in it.then do it as usual.

ps:you would not get the real height of the nested listView if you use layout_width="warp_content". because nested listView couldn't get real height with "warp_content

Measure it would be fine .

Title: ListView inside Gridview

Body:
I would like to use a GridView layout, so that every item of the Gridlayout has its own ListView. I have been looking for code sample but I haven't found any. Should I use different adapter classes for the GridView and the ListView?
Thank you in advance!

Edit: I have created a GridView that displays all the some tiles, and I want every grid item to include a list, so I have added a ListView to the layout of the GridView items. Unfortunately I 'm having problems connecting the listview to the adapter.

This is the adapter of the gridView:

public class MainViewAdapter extends ArrayAdapter<Category> {
private Context mContext;
private int layoutResourceId;
private ArrayList<Category> mGridData = new ArrayList<Category>();
ArrayAdapter adapter;

public MainViewAdapter(Context mContext, int layoutResourceId, ArrayList<Category> mGridData) {
    super(mContext, layoutResourceId, mGridData);
    this.layoutResourceId = layoutResourceId;
    this.mContext = mContext;
    this.mGridData = mGridData;
}

public void setGridData(ArrayList<Category> mGridData) {
    this.mGridData = mGridData;
    notifyDataSetChanged();
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View row = convertView;
    ViewHolder holder;
    String imageUrl;

    if (row == null) {
        LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
        row = inflater.inflate(layoutResourceId, parent, false);
        holder = new ViewHolder();
        holder.SubListView = (ListView) row.findViewById(R.id.SubList);
        holder.titleTextView = (TextView) row.findViewById(R.id.category_title);
        holder.simpleDraweeView = (SimpleDraweeView) row.findViewById(R.id.category_image);
        row.setTag(holder);
    } else {
        holder = (ViewHolder) row.getTag();
    }

    Category category = mGridData.get(position);
    Log.i("position", "" + position);
    holder.titleTextView.setText(Html.fromHtml(category.getTitle()));
    imageUrl = category.getImage();
    Log.i("image url",imageUrl );
    Uri imageUri = Uri.parse(imageUrl);
    holder.simpleDraweeView.setImageURI(imageUri);

    List SubCategories = category.getSubCateg();
    Log.i("@MainViewAdapter - SubCategories", category.getSubCateg().toString());

    //list SubCategories to ArrayList
    ArrayList<SubCategory> listOfSub = new ArrayList<>(SubCategories.size());
    listOfSub.addAll(SubCategories);
    Log.i("listOfSub",listOfSub.toString());

    //ArrayList to ListView
    holder.SubListView.setAdapter(adapter);

    return row;
}

static class ViewHolder {
    TextView titleTextView;
    SimpleDraweeView simpleDraweeView;
    ListView SubListView;
}}

And here is the adapter of the listview:

public class SubListAdapter extends ArrayAdapter<SubCategory> {
private int layoutResourceId;
private ArrayList<SubCategory> mSubGridData = new ArrayList<SubCategory>();
ArrayAdapter adapter;

private final Context mContext;

public SubListAdapter(Context mContext, int layoutResourceId, ArrayList<SubCategory> mSubGridData) {
    super(mContext, R.layout.subcategory_item, mSubGridData);

    this.layoutResourceId = layoutResourceId;
    this.mContext = mContext;
    this.mSubGridData = mSubGridData;
}

public void setSubGridData(ArrayList<SubCategory> mSubGridData) {
    this.mSubGridData = mSubGridData;
    notifyDataSetChanged();
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    View row = convertView;
    SubListAdapter.ViewHolder holder;
    String imageUrl;

    if (row == null) {
        LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
        row = inflater.inflate(layoutResourceId, parent, false);
        holder = new ViewHolder();
        holder.SubTitleTextView = (TextView) row.findViewById(R.id.subCatItemTitle);
        row.setTag(holder);
    } else {
        holder = (SubListAdapter.ViewHolder) row.getTag();

    return rowView;
}

static class ViewHolder {
    TextView SubTitleTextView;
    ListView SubListView;
}}

I am having some problems with the second adapter.


问:
How do I get the value of a selected option an use it on an "if"?
I have this HTML:

```<code><select id="categories">
    <option value="category1">Category 1</option>
    <option value="category2">Category 2</option>
</select>
<input type="search" id="search" placeholder="Search here" autofocus>
</code>```

And this jquery:

```<code>var categories = $("#categories option:selected").val();
var search = $("#search");

if (categories = "category2") {

    search.attr("placeholder", "Search for category 2");
} else {

    search.attr("placeholder", "Search for category 1");
}
</code>```

I'm trying to put a different placeholder according to the selected value, but no matter what is selected, it always show the first placeholder. This might seem silly, but further I want to be able to pick the value of the selected option to make the search in that specific category, kinda like the Amazon website.

I have used == to compare, but nothing happens, the placeholder stays with "Search here".

PS: With this code running, using the console on Chrome, if I type and execute categories it will always show in the console category2, no matter which one is selected, but if I type and execute $("#categories option:selected").val();, then it will show the selected value. I tried to put this directly inside the if in the code, but returned the same problem. I also tried to replace the else for if (categories = "category1"), but then it was the same problem, but this time the placeholder showed was always the second one.

答:
//you should add an onChange event,like this:
$("#categories").change(function(e){
   var categories = e.target.value;
   if (categories == "category2") {
    ...
   } else {
    ...
   }
})```

Body:
I have this HTML:

<select id="categories">
    <option value="category1">Category 1</option>
    <option value="category2">Category 2</option>
</select>
<input type="search" id="search" placeholder="Search here" autofocus>

And this jquery:

var categories = $("#categories option:selected").val();
var search = $("#search");

if (categories = "category2") {

    search.attr("placeholder", "Search for category 2");
} else {

    search.attr("placeholder", "Search for category 1");
}

I'm trying to put a different placeholder according to the selected value, but no matter what is selected, it always show the first placeholder. This might seem silly, but further I want to be able to pick the value of the selected option to make the search in that specific category, kinda like the Amazon website.

I have used == to compare, but nothing happens, the placeholder stays with "Search here".

PS: With this code running, using the console on Chrome, if I type and execute categories it will always show in the console category2, no matter which one is selected, but if I type and execute $("#categories option:selected").val();, then it will show the selected value. I tried to put this directly inside the if in the code, but returned the same problem. I also tried to replace the else for if (categories = "category1"), but then it was the same problem, but this time the placeholder showed was always the second one.


问:
How to disable all attribute menu items in a ul/li List when one of them is clicked?
I can click on the Photos1, Photos2, Photos3, and Photos4 menus very quickly, and the "$.get(..." is sent to the server 4 times. I need to disable all these menus after any one is clicked. Environment: NodeJS, Express, Pug, Jquery Thanks, Pat</p>

```<code>--------------DOM----------------------------------
// file = photos.pug
div#wrapper2
    div#altnav
      ul
        include includes/altnav.pug
        include includes/navjs.pug
---------------------------------------------------
// file = includes/altnav.pug
li: a.navigation(href='#', data-level='/images/cs/Photos1') Photos1
li: a.navigation(href='#', data-level='/images/cs/Photos2') Photos2
li: a.navigation(href='#', data-level='/images/cs/Photos3') Photos3
li: a.navigation(href='#', data-level='/images/cs/Photos4') Photos4
---------------------------------------------------
// file = includes/navjs.pug
script.
    $(function(){ // jQuery DOM ready
        $('.navigation').click(function () {

            $(this).css({   // Disable this menu item
                "pointer-events": "none",
                "cursor": "default"
            });
// ??????? I NEED TO DISABLE ALL Menus in this List ???????
            var level = 'm' + $(this).data('level');        // Append an 'm' so I know this came from navjs.pug
            var url = '/navigation?level=' + escape(level); // Send this to the /router/photos.js
            $.get(url, function (data) {
                $('body').html(data);           // data = new HTML page to be loaded by browser
            });
        });
    });
</code>```

答:
I would apply an id attribute to all of the elements with .navigation and then write a function, passing the id of $(this) to the function and disable all other menu items that don't match that id, like so:

```<code>function disableAllBut(id) {
    $(.navigation).prop('disable', true);
    $(id).prop('disable', false);
}
</code>```

Body:
I can click on the Photos1, Photos2, Photos3, and Photos4 menus very quickly, and the "$.get(..." is sent to the server 4 times. I need to disable all these menus after any one is clicked. Environment: NodeJS, Express, Pug, Jquery Thanks, Pat

--------------DOM----------------------------------
// file = photos.pug
div#wrapper2
    div#altnav
      ul
        include includes/altnav.pug
        include includes/navjs.pug
---------------------------------------------------
// file = includes/altnav.pug
li: a.navigation(href='#', data-level='/images/cs/Photos1') Photos1
li: a.navigation(href='#', data-level='/images/cs/Photos2') Photos2
li: a.navigation(href='#', data-level='/images/cs/Photos3') Photos3
li: a.navigation(href='#', data-level='/images/cs/Photos4') Photos4
---------------------------------------------------
// file = includes/navjs.pug
script.
    $(function(){ // jQuery DOM ready
        $('.navigation').click(function () {

            $(this).css({   // Disable this menu item
                "pointer-events": "none",
                "cursor": "default"
            });
// ??????? I NEED TO DISABLE ALL Menus in this List ???????
            var level = 'm' + $(this).data('level');        // Append an 'm' so I know this came from navjs.pug
            var url = '/navigation?level=' + escape(level); // Send this to the /router/photos.js
            $.get(url, function (data) {
                $('body').html(data);           // data = new HTML page to be loaded by browser
            });
        });
    });

Body:
I would apply an id attribute to all of the elements with .navigation and then write a function, passing the id of $(this) to the function and disable all other menu items that don't match that id, like so:

function disableAllBut(id) {
    $(.navigation).prop('disable', true);
    $(id).prop('disable', false);
}


问:
pragma directive in UIViewController
When i create a UITableViewController class, the template has some #pragma directives:

```<code>#pragma mark -
#pragma mark View lifecycle
</code>```

at the start and:

```<code>#pragma mark -
#pragma mark Table view data source
</code>```

at the beginning of the implementation of the data source methods.

I know that #pragma is a compiler directive, but why do we need to notify the compiler of the above?

Does this mean that we have to give a #pragma directive every time we implement any kind of data source/delegate protocols?

答:
You dont need to use them. They are simply for code "prettiness" and separating methods.

In my screenshot example, they are used to draw the lines you see, separating delegates.

#pragma mark - draws the line and #pragma mark My Delegates shows you whatever text you see in BOLD.

Title: pragma directive in UIViewController

Body:
When i create a UITableViewController class, the template has some #pragma directives:

#pragma mark -
#pragma mark View lifecycle

at the start and:

#pragma mark -
#pragma mark Table view data source

at the beginning of the implementation of the data source methods.

I know that #pragma is a compiler directive, but why do we need to notify the compiler of the above?

Does this mean that we have to give a #pragma directive every time we implement any kind of data source/delegate protocols?


问:
3DES encryption not matching third party API
My C# 3DES encryption is not matching the third party API I'm using. Is there anything wrong with my code?

```<code>static void Main(string[] args)
{
String sharedSec = "654A7EA2C9914A0B972937F4EA45FED3";

byte[] byteArraySharedSec = Convert.FromBase64String(sharedSec);
TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();

tdes.KeySize = 192;
tdes.Key = byteArraySharedSec;
tdes.Mode = CipherMode.ECB;
tdes.Padding = PaddingMode.PKCS7;

ICryptoTransform ict = tdes.CreateEncryptor();
ICryptoTransform dct = tdes.CreateDecryptor();

Console.WriteLine("SharedSec: {0}", sharedSec);
Console.WriteLine("byteArraySharedSec: {0}\n", ToReadableByteArray(byteArraySharedSec));

long unixTimestamp = 1299481200;

byte[] unixTimestampByte = BitConverter.GetBytes(unixTimestamp);

Console.WriteLine("Timestamp: {0}, length: {1} ", ToReadableByteArray(unixTimestampByte), unixTimestampByte.Length);

byte[] result = ict.TransformFinalBlock(unixTimestampByte, 0, unixTimestampByte.Length);

Console.WriteLine("After 3DES encrypting: {0}, length {1}\n\n  ", ToReadableByteArray(result), result.Length);
}

static public string ToReadableByteArray(byte[] bytes)
{
    return string.Join(",", bytes);
}
</code>```

The output (you can see byteArraySharedSec is correct but encrypting is not):

SharedSec: 654A7EA2C9914A0B972937F4EA45FED3

byteArraySharedSec: 235,158,0,236,64,54,11,223,117,224,13,1,247,189,189,223,177,120,16,14,57,20,64,247

Timestamp: 112,130,116,77,0,0,0,0, length: 8

After 3DES encrypting:
  213,60,183,244,171,116,202,205,233,17,226,8,70,9,111,43, length 16

API Doc has given this example:

The 3DES encryption uses:

192 bit key

ECB Mode

PKCS7 Padding

Example SHARED_SECRET: 654A7EA2C9914A0B972937F4EA45FED3

Convert SHARED_SECRET to byte array by Base64 decoding. This is the    3DES key: { 235, 158, 0, 236, 64, 54, 11, 223, 117, 224, 13, 1, 247, 189, 189, 223, 177, 120, 16, 14, 57, 20, 64, 247}

Example timestamp (7AM 7th March 2011 GMT): 1299481200

3DES encrypt (ECB mode, PKCS7 Padding) the timestamp using the 3DES    key : 128 bit (16 byte) result for this example { 82, 191, 213, 179, 179, 73, 1, 218, 247, 68, 254, 199, 19, 159, 1, 138}

答:
You're encrypting a different value than the example gave you.

Treating the timestamp as string, and using the UTF8 encoding to get its bytes representation should gave you the same result:

```<code>...
byte[] unixTimestampByte = Encoding.UTF8.GetBytes(unixTimestamp.ToString());
...
</code>```

Body:
My C# 3DES encryption is not matching the third party API I'm using. Is there anything wrong with my code?

static void Main(string[] args)
{
String sharedSec = "654A7EA2C9914A0B972937F4EA45FED3";

byte[] byteArraySharedSec = Convert.FromBase64String(sharedSec);
TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();

tdes.KeySize = 192;
tdes.Key = byteArraySharedSec;
tdes.Mode = CipherMode.ECB;
tdes.Padding = PaddingMode.PKCS7;

ICryptoTransform ict = tdes.CreateEncryptor();
ICryptoTransform dct = tdes.CreateDecryptor();

Console.WriteLine("SharedSec: {0}", sharedSec);
Console.WriteLine("byteArraySharedSec: {0}\n", ToReadableByteArray(byteArraySharedSec));

long unixTimestamp = 1299481200;

byte[] unixTimestampByte = BitConverter.GetBytes(unixTimestamp);

Console.WriteLine("Timestamp: {0}, length: {1} ", ToReadableByteArray(unixTimestampByte), unixTimestampByte.Length);

byte[] result = ict.TransformFinalBlock(unixTimestampByte, 0, unixTimestampByte.Length);

Console.WriteLine("After 3DES encrypting: {0}, length {1}\n\n  ", ToReadableByteArray(result), result.Length);
}

static public string ToReadableByteArray(byte[] bytes)
{
    return string.Join(",", bytes);
}

The output (you can see byteArraySharedSec is correct but encrypting is not):

SharedSec: 654A7EA2C9914A0B972937F4EA45FED3

byteArraySharedSec: 235,158,0,236,64,54,11,223,117,224,13,1,247,189,189,223,177,120,16,14,57,20,64,247

Timestamp: 112,130,116,77,0,0,0,0, length: 8

After 3DES encrypting:
  213,60,183,244,171,116,202,205,233,17,226,8,70,9,111,43, length 16

API Doc has given this example:

The 3DES encryption uses:

192 bit key

ECB Mode

PKCS7 Padding

Example SHARED_SECRET: 654A7EA2C9914A0B972937F4EA45FED3

Convert SHARED_SECRET to byte array by Base64 decoding. This is the    3DES key: { 235, 158, 0, 236, 64, 54, 11, 223, 117, 224, 13, 1, 247, 189, 189, 223, 177, 120, 16, 14, 57, 20, 64, 247}

Example timestamp (7AM 7th March 2011 GMT): 1299481200

3DES encrypt (ECB mode, PKCS7 Padding) the timestamp using the 3DES    key : 128 bit (16 byte) result for this example { 82, 191, 213, 179, 179, 73, 1, 218, 247, 68, 254, 199, 19, 159, 1, 138}

Body:
You're encrypting a different value than the example gave you.

Treating the timestamp as string, and using the UTF8 encoding to get its bytes representation should gave you the same result:

...
byte[] unixTimestampByte = Encoding.UTF8.GetBytes(unixTimestamp.ToString());
...


问:
How to make the weights of an RNN cell untrainable in Tensorflow?
I'm trying to make a Tensorflow graph where part of the graph is already pre-trained and running in prediction mode, while the rest trains. I've defined my pre-trained cell like so:

```<code>rnn_cell = tf.contrib.rnn.BasicLSTMCell(100)

state0 = tf.Variable(pretrained_state0,trainable=False)
state1 = tf.Variable(pretrained_state1,trainable=False)
pretrained_state = [state0, state1]

outputs, states = tf.contrib.rnn.static_rnn(rnn_cell,
                                            data_input,
                                            dtype=tf.float32,
                                            initial_state = pretrained_state)
</code>```

Setting the initial variables to trainable=False doesn't help. These are just used to initialize the weights and as a result the weights still change.

I still need to run an optimizer in my training step, since the rest of my model needs to train. But how can I prevent the optimizer from changing the weights in this rnn cell?

Is there a rnn_cell equivalent to trainable=False?

答:
You can use either tf.stop_gradient() to prevent the pretrained parts of the graph from updating its weights or you can use the optimiser() where you can specify which parts of the graph should be trained. The second method would involve:

```<code> #Create variable scope for the trainable parts of the graph: tf.variable_scope('train').

 # get trainable variables
 t_vars = tf.trainable_variables()
 train_vars = [var for var in t_vars if var.name.startswith('train')]
 # train only the variables of a particular scope
 opt = optimizer.minimize(cost, var_list=train_vars)
</code>```

Body:
I'm trying to make a Tensorflow graph where part of the graph is already pre-trained and running in prediction mode, while the rest trains. I've defined my pre-trained cell like so:

rnn_cell = tf.contrib.rnn.BasicLSTMCell(100)

state0 = tf.Variable(pretrained_state0,trainable=False)
state1 = tf.Variable(pretrained_state1,trainable=False)
pretrained_state = [state0, state1]

outputs, states = tf.contrib.rnn.static_rnn(rnn_cell,
                                            data_input,
                                            dtype=tf.float32,
                                            initial_state = pretrained_state)

Setting the initial variables to trainable=False doesn't help. These are just used to initialize the weights and as a result the weights still change.

I still need to run an optimizer in my training step, since the rest of my model needs to train. But how can I prevent the optimizer from changing the weights in this rnn cell?

Is there a rnn_cell equivalent to trainable=False?

Body:
You can use either tf.stop_gradient() to prevent the pretrained parts of the graph from updating its weights or you can use the optimiser() where you can specify which parts of the graph should be trained. The second method would involve:

 #Create variable scope for the trainable parts of the graph: tf.variable_scope('train').

 # get trainable variables
 t_vars = tf.trainable_variables()
 train_vars = [var for var in t_vars if var.name.startswith('train')]
 # train only the variables of a particular scope
 opt = optimizer.minimize(cost, var_list=train_vars)


问:
Appending a function to an existing onclick event at page load
I have the following html code that is pre written by the app I am using, which I do not have access to, i.e.

```<code><td align="center" class="shuttleControl">
  <img src="/i/mydb/icons/shuttle_reload.png" onclick="g_Shuttlep_v61.reset();" alt="Reset"  title="Reset"/>
  <img src="/i/mydb/icons/shuttle_last.png" onclick="g_Shuttlep_v61.move_all();" alt="Move All" title="Move All"/>
  <img src="/i/mydb/icons/shuttle_right.png" onclick="g_Shuttlep_v61.move();" alt="Move" title="Move" />
  <img src="/i/mydb/icons/shuttle_left.png" onclick="g_Shuttlep_v61.remove();" alt="Remove" title="Remove" />
  <img src="/i/mydb/icons/shuttle_first.png" onclick="g_Shuttlep_v61.remove_all();" alt="Remove All" title="Remove All" />
</td>
</code>```

Based on the above code, using jQuery, would it be possible that when the page finishes loading, search for the img src "shuttle_last.png" and append to it's onclick call, my own function get_Count(); ?

That is, I would then see the following code when I do a view page source for this particular line, i.e.:

```<code><img src="/i/mydb/icons/shuttle_last.png" onclick="g_Shuttlep_v61.move_all();get_Count();" alt="Move All" title="Move All"/>
</code>```

Is this possible - if so, would really appreciate a code sample?

Thanks.

答:
Will not this work:

```<code>$('img[src$="shuttle_last.png"]').click(function() {
    get_Count();
});
</code>```

?

Body:
I have the following html code that is pre written by the app I am using, which I do not have access to, i.e.

Based on the above code, using jQuery, would it be possible that when the page finishes loading, search for the img src "shuttle_last.png" and append to it's onclick call, my own function get_Count(); ?

That is, I would then see the following code when I do a view page source for this particular line, i.e.:

Is this possible - if so, would really appreciate a code sample?

Thanks.

Body:
Will not this work:

$('img[src$="shuttle_last.png"]').click(function() {
    get_Count();
});

?


问:
IOS: Disable dismiss function when tap outside UIActionsheet
I have a problem about UIActionsheet.
When user tap outside action sheet, app will auto call dismiss function to dismiss action sheet, so how can I disable this function? -> User only press cancel button to dismiss action sheet.
Thanks,</p>

答:
Don't use .cancel UIAlertActionStyle.

If you remvoe the ".cancel" style, the tapping outside dismiss feature will be disabled.

You need to add your own custom Cancel option and tapping on that button, you can dismiss the action sheet.


问:
#1067 - Invalid default value for 'membership'
I am using a SQL file included in my program and once I fixed an issue that I was able to find the answer to in here (THANK YOU).. I ran it again and got the following error:

SQL query:

```<code># Create table structure for 'member' table
CREATE TABLE member(

memberID INT( 11 ) NOT NULL AUTO_INCREMENT ,
title VARCHAR( 80 ) NOT NULL DEFAULT  '',
firstname VARCHAR( 80 ) NOT NULL DEFAULT  '',
lastname VARCHAR( 80 ) NOT NULL DEFAULT  '',
email VARCHAR( 80 ) NOT NULL DEFAULT  '',
address VARCHAR( 80 ) NOT NULL DEFAULT  '',
suburb VARCHAR( 80 ) NOT NULL DEFAULT  '',
state VARCHAR( 80 ) NOT NULL DEFAULT  '',
country VARCHAR( 80 ) NOT NULL DEFAULT  '',
postcode VARCHAR( 11 ) NOT NULL DEFAULT  '',
mobile VARCHAR( 80 ) NOT NULL DEFAULT  '',
phone VARCHAR( 80 ) NOT NULL DEFAULT  '',
fax VARCHAR( 80 ) NOT NULL DEFAULT  '',
membership INT( 2 ) NOT NULL DEFAULT  '',
payment INT( 2 ) NOT NULL DEFAULT  '',
startdate BIGINT( 14 ) NOT NULL DEFAULT 0,
enddate BIGINT( 14 ) NOT NULL DEFAULT 0,
userID INT( 11 ) NOT NULL ,
PRIMARY KEY ( memberID ) ,
UNIQUE (
memberID
)
) ENGINE = MYISAM ;
</code>```

MySQL said:

```<code>#1067 - Invalid default value for 'membership'
</code>```

What do I need to change to make this work ?  this is an older script, but I am not knowledgeable enough to know what  needs to be changed for MySQL 5.5 version.

Thank you so much for your help!

And I'm sure there will be other errors popping up after I fix this one..

答:
I was getting:

```<code>Incorrect integer value: '' for column 'column_name' at row 1
</code>```

I've fixed it editing /etc/mysql/my.cnf or /etc/mysql/mysql.conf.d/mysqld.cnf files. Then find the following line:

```<code>sql-mode="STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"
</code>```

and replace it for

```<code>sql-mode=""
</code>```

and restart MySQL: service mysql restart

Body:
I am using a SQL file included in my program and once I fixed an issue that I was able to find the answer to in here (THANK YOU).. I ran it again and got the following error:

SQL query:

# Create table structure for 'member' table
CREATE TABLE member(

memberID INT( 11 ) NOT NULL AUTO_INCREMENT ,
title VARCHAR( 80 ) NOT NULL DEFAULT  '',
firstname VARCHAR( 80 ) NOT NULL DEFAULT  '',
lastname VARCHAR( 80 ) NOT NULL DEFAULT  '',
email VARCHAR( 80 ) NOT NULL DEFAULT  '',
address VARCHAR( 80 ) NOT NULL DEFAULT  '',
suburb VARCHAR( 80 ) NOT NULL DEFAULT  '',
state VARCHAR( 80 ) NOT NULL DEFAULT  '',
country VARCHAR( 80 ) NOT NULL DEFAULT  '',
postcode VARCHAR( 11 ) NOT NULL DEFAULT  '',
mobile VARCHAR( 80 ) NOT NULL DEFAULT  '',
phone VARCHAR( 80 ) NOT NULL DEFAULT  '',
fax VARCHAR( 80 ) NOT NULL DEFAULT  '',
membership INT( 2 ) NOT NULL DEFAULT  '',
payment INT( 2 ) NOT NULL DEFAULT  '',
startdate BIGINT( 14 ) NOT NULL DEFAULT 0,
enddate BIGINT( 14 ) NOT NULL DEFAULT 0,
userID INT( 11 ) NOT NULL ,
PRIMARY KEY ( memberID ) ,
UNIQUE (
memberID
)
) ENGINE = MYISAM ;

MySQL said:

#1067 - Invalid default value for 'membership'

What do I need to change to make this work ?  this is an older script, but I am not knowledgeable enough to know what  needs to be changed for MySQL 5.5 version.

Thank you so much for your help!

And I'm sure there will be other errors popping up after I fix this one..

Body:
I was getting:

Incorrect integer value: '' for column 'column_name' at row 1

I've fixed it editing /etc/mysql/my.cnf or /etc/mysql/mysql.conf.d/mysqld.cnf files. Then find the following line:

sql-mode="STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"

and replace it for

sql-mode=""

and restart MySQL: service mysql restart


问:
Stuck in Ipython debugger loop
Everytime I press 'q', I get redirected to another ipdb session. I could just close the terminal window, but is there a better to kill the loop?</p>

答:
The main way I use to exit the loop is Ctrl + Z.

Otherwise, it is also possible to execute:

```<code>ipdb> import os; os._exit(1)
</code>```

Here's a source to corroborate: How to quit ipdb while in post-mortem debugging?

Title: Stuck in Ipython debugger loop

Body:
The main way I use to exit the loop is Ctrl + Z.

Otherwise, it is also possible to execute:

ipdb> import os; os._exit(1)

Here's a source to corroborate: How to quit ipdb while in post-mortem debugging?


问:
Adding From Header Field HTTP POST Header in Gsoap
I am using g-soap-2.8 to send a post request to a web service. But the problem is that the web service requires From (Http Header Field) must be present in Header. But gsoap has no context related to From header field.

Can anyone explain how to add this particular header field-value pair in gsoap.

答:
The soap.http_extra_header string can be used for this:

```<code>soap->http_extra_header = "SomeField: SomeValue(s)";
</code>```

You can add multiple extra HTTP headers by separating them with \r\n in the string. Set this string before making the call. The string will be reset to NULL when the call completes, so the extra headers do no accidentally bleed into the next calls.

Body:
The soap.http_extra_header string can be used for this:

soap->http_extra_header = "SomeField: SomeValue(s)";

You can add multiple extra HTTP headers by separating them with \r\n in the string. Set this string before making the call. The string will be reset to NULL when the call completes, so the extra headers do no accidentally bleed into the next calls.


问:
How to add class only to the header of group of links
I have a list like to:

```<code><ul>
<li><a class="group-active">Group 1</a>
    <ul>
        <li routerLinkActive="active"><a [routerLink]="['/group1/page1']">Group 1 - Page 1</a>
        <li routerLinkActive="active"><a [routerLink]="['/group1/page2']">Group 1 - Page 2</a>
        <li routerLinkActive="active"><a [routerLink]="['/group1/page3']">Group 1 - Page 3</a>
    </ul>
</li>
<li><a>Group 2</a>
    <ul>
        <li routerLinkActive="active"><a [routerLink]="['/group2/page1']">Group 2 - Page 1</a>
        <li routerLinkActive="active"><a [routerLink]="['/group2/page2']">Group 2 - Page 2</a>
        <li routerLinkActive="active"><a [routerLink]="['/group2/page3']">Group 2 - Page 3</a>
    </ul>
</li>
<li><a>Group 3</a>
    <ul>
        <li routerLinkActive="active"><a [routerLink]="['/group3/page1']">Group 3 - Page 1</a>
        <li routerLinkActive="active"><a [routerLink]="['/group3/page2']">Group 3 - Page 2</a>
        <li routerLinkActive="active"><a [routerLink]="['/group3/page3']">Group 3 - Page 3</a>
    </ul>
</li>
</ul>
</code>```

I need:
change the class "group-active" (of the first group) when i choose one of their elements. Their elements works fine, but i can't apply the style to corresponding element header.

Any idea?

Thanks

答:
That's a good question. I could see many people needing this.

Export the routerLinkActive to a template variable and then use isActive:

```<code><li><a [class.group-active]="r1.isActive || r2.isActive || r2.isActive">Group 1</a>
    <ul>
        <li routerLinkActive="active" #r1="routerLinkActive"><a [routerLink]="['/group1/page1']" #r1="routerLinkActive">Group 1 - Page 1</a>
        <li routerLinkActive="active" #r2="routerLinkActive"><a [routerLink]="['/group1/page2']">Group 1 - Page 2</a>
        <li routerLinkActive="active" #r3="routerLinkActive"><a [routerLink]="['/group1/page3']">Group 1 - Page 3</a>
    </ul>
</li>
</code>```

You could also write a simple directive that has a boolean like this:

```<code>@Directive({
   selector: '[any-active]',
   exportAs 'anyActive'
})
public class AnyActiveDirective implements DoCheck {
  @ViewChildren(RouterLinkActive)
  public links: QueryList<RouterLinkActive>;

  public active: boolean = false;

  public constructor(private cdr: ChangeDetectorRef) {
  }

  public ngDoCheck() {
     if(this.links) {
        const active = !!this.links.find((link)=>link.isActive);
        if(this.active !== active) {
            thia.active = active;
            this.cdr.markForCheck();
        }
     }
  }
}
</code>```

Then in the template:

```<code><li any-active #group1="actActive"><a [class.group-active]="group1.active">Group 1</a>
    <ul>
        <li routerLinkActive="active"><a [routerLink]="['/group1/page1']" #r1="routerLinkActive">Group 1 - Page 1</a>
        <li routerLinkActive="active"><a [routerLink]="['/group1/page2']">Group 1 - Page 2</a>
        <li routerLinkActive="active"><a [routerLink]="['/group1/page3']">Group 1 - Page 3</a>
    </ul>
</li>
</code>```

You can try the first approach if your template is kind of static, but if your links are generated with a *ngFor then give the custom directive a try.

UPDATED:

I don't think my previous answer was very good. The routerLinkActive directive will set the CSS value if any children with routerLink are active.

Therefore, this should be enough to get it working:

```<code><li><a routerLinkActive="group-active">Group 1</a>
    <ul>
        <li routerLinkActive="active"><a [routerLink]="['/group1/page1']">Group 1 - Page 1</a>
        <li routerLinkActive="active"><a [routerLink]="['/group1/page2']">Group 1 - Page 2</a>
        <li routerLinkActive="active"><a [routerLink]="['/group1/page3']">Group 1 - Page 3</a>
    </ul>
</li>
</code>```

Body:
I have a list like to:

Group 1

Group 1 - Page 1

Group 1 - Page 2

Group 1 - Page 3

Group 2

Group 2 - Page 1

Group 2 - Page 2

Group 2 - Page 3

Group 3

Group 3 - Page 1

Group 3 - Page 2

Group 3 - Page 3

I need:
change the class "group-active" (of the first group) when i choose one of their elements. Their elements works fine, but i can't apply the style to corresponding element header.

Any idea?

Thanks

Body:
That's a good question. I could see many people needing this.

Export the routerLinkActive to a template variable and then use isActive:

<li><a [class.group-active]="r1.isActive || r2.isActive || r2.isActive">Group 1</a>
    <ul>
        <li routerLinkActive="active" #r1="routerLinkActive"><a [routerLink]="['/group1/page1']" #r1="routerLinkActive">Group 1 - Page 1</a>
        <li routerLinkActive="active" #r2="routerLinkActive"><a [routerLink]="['/group1/page2']">Group 1 - Page 2</a>
        <li routerLinkActive="active" #r3="routerLinkActive"><a [routerLink]="['/group1/page3']">Group 1 - Page 3</a>
    </ul>
</li>

You could also write a simple directive that has a boolean like this:

@Directive({
   selector: '[any-active]',
   exportAs 'anyActive'
})
public class AnyActiveDirective implements DoCheck {
  @ViewChildren(RouterLinkActive)
  public links: QueryList<RouterLinkActive>;

  public active: boolean = false;

  public constructor(private cdr: ChangeDetectorRef) {
  }

  public ngDoCheck() {
     if(this.links) {
        const active = !!this.links.find((link)=>link.isActive);
        if(this.active !== active) {
            thia.active = active;
            this.cdr.markForCheck();
        }
     }
  }
}

Then in the template:

<li any-active #group1="actActive"><a [class.group-active]="group1.active">Group 1</a>
    <ul>
        <li routerLinkActive="active"><a [routerLink]="['/group1/page1']" #r1="routerLinkActive">Group 1 - Page 1</a>
        <li routerLinkActive="active"><a [routerLink]="['/group1/page2']">Group 1 - Page 2</a>
        <li routerLinkActive="active"><a [routerLink]="['/group1/page3']">Group 1 - Page 3</a>
    </ul>
</li>

You can try the first approach if your template is kind of static, but if your links are generated with a *ngFor then give the custom directive a try.

UPDATED:

I don't think my previous answer was very good. The routerLinkActive directive will set the CSS value if any children with routerLink are active.

Therefore, this should be enough to get it working:

<li><a routerLinkActive="group-active">Group 1</a>
    <ul>
        <li routerLinkActive="active"><a [routerLink]="['/group1/page1']">Group 1 - Page 1</a>
        <li routerLinkActive="active"><a [routerLink]="['/group1/page2']">Group 1 - Page 2</a>
        <li routerLinkActive="active"><a [routerLink]="['/group1/page3']">Group 1 - Page 3</a>
    </ul>
</li>


问:
dropping trailing '.0' from floats
I'm looking for a  way to convert numbers to string format, dropping any redundant '.0'

The input data is a mix of floats and strings. Desired output:

0   --> '0'

0.0 --> '0'

0.1 --> '0.1'

1.0 --> '1'

I've come up with the following generator expression, but I wonder if there's a faster way:

```<code>(str(i).rstrip('.0') if i else '0' for i in lst)
</code>```

The truth check is there to prevent 0 from becoming an empty string.

EDIT: The more or less acceptable solution I have for now is this:

```<code>('%d'%i if i == int(i) else '%s'%i for i in lst)
</code>```

It just seems strange that there is no elegant way to handle this (fairly straightforward) case in python.

答:
I was dealing with a value from a json dictionary (returned by an API). All the above didnt help me so i constructed by own helper function. It truncates all the trailing zeros.

I Hope it helps someone out there

```<code>def remove_zeros(num):
    nums = list(num)
    indexes = (list(reversed(range(len(nums)))))
    for i in indexes:
        if nums[i] == '0':
            del nums[-1]
        else:
            break
    return "".join(nums)

num = "0.000000363000"
print(remove_zeros(num))
</code>```

prints :

```<code>    0.000000363
</code>```

OwnerDisplayName: Algorias

Title: dropping trailing '.0' from floats

Body:
I'm looking for a  way to convert numbers to string format, dropping any redundant '.0'

The input data is a mix of floats and strings. Desired output:

0   --> '0'

0.0 --> '0'

0.1 --> '0.1'

1.0 --> '1'

I've come up with the following generator expression, but I wonder if there's a faster way:

(str(i).rstrip('.0') if i else '0' for i in lst)

The truth check is there to prevent 0 from becoming an empty string.

EDIT: The more or less acceptable solution I have for now is this:

('%d'%i if i == int(i) else '%s'%i for i in lst)

It just seems strange that there is no elegant way to handle this (fairly straightforward) case in python.

LastEditorDisplayName: Algorias

Body:
I was dealing with a value from a json dictionary (returned by an API). All the above didnt help me so i constructed by own helper function. It truncates all the trailing zeros.

I Hope it helps someone out there

def remove_zeros(num):
    nums = list(num)
    indexes = (list(reversed(range(len(nums)))))
    for i in indexes:
        if nums[i] == '0':
            del nums[-1]
        else:
            break
    return "".join(nums)

num = "0.000000363000"
print(remove_zeros(num))

prints :

    0.000000363