答:
Here is brief idea

```<code>var type = Type.GetType(f.TypeName);
var methodInfo = typeof(MethodHoderType).GetMethod("MyMethod");
var constructedMethodInfo = methodInfo.MakeGenericMethod(type);
constructedMethodInfo.Invoke(...);
</code>```

If it is instance method you should create an instance of type type to pass to Invoke method or pass null as first parameter if it is static method.

Look at the Type.GetType Method (String) and MethodInfo.MakeGenericMethod Method (Type[]) for more information.

Title: C#: How can I use a string to specify the Type (T) for a generic method?

Body:
Here is brief idea

var type = Type.GetType(f.TypeName);
var methodInfo = typeof(MethodHoderType).GetMethod("MyMethod");
var constructedMethodInfo = methodInfo.MakeGenericMethod(type);
constructedMethodInfo.Invoke(...);

If it is instance method you should create an instance of type type to pass to Invoke method or pass null as first parameter if it is static method.

Look at the Type.GetType Method (String) and MethodInfo.MakeGenericMethod Method (Type[]) for more information.


来源: stackexchange

问:
How do I make the keyboard go away when the user clicks somewhere else?

Possible Duplicate:

  Dismiss keyboard by touching background of UITableView

How do I make the keyboard go away when the user clicks somewhere else?

Note: I know how to make the keyboard disappear with sending the resignFirstResponder command to the UITextField.  At present the "Done" button is connected to all the correct code to do this and this works.

I have a UITableView with different UITableViewCells, and if the user moves onto another cell I want the keyboard to disappear.

So what events do I also need to include the resignFirstResponder in, for the keyboard to disappear.

Suppose UITableViewCell A has the UITextField, and UITableViewCell B has a button.  If the user presses the button in cell B, then I will need to send the command resignFirstResponder back to the UITextField in cell A.  First of all the button has no idea which cell it should sent the command to, and second even if the button did know which cell to send the command to how would it?

答:
You can create a generic 'hideKeyboard' method in which you can include all text fields that can be first responders. For example,

```<code>-(void) hideKeyboard {
     [textFieldName resignFirstResponder];
     [textFieldSurname resignFirstResponder];
     for (UITextField * txtField in arrTextFields) {
         [txtField resignFirstResponder];
      }
}
</code>```

Then, at various sections in your class, depending on the functionality required, call;

```<code>[self hideKeyBoard];
</code>```

This simple method means you won't need to keep track of the individual item that 'has the focus' / first responder status.

How to touch any part of the screen to make the keyboard go away
To touch somewhere outside the UITableView and have the keyboard disappear, place an invisible button on top of the 'touch area' that you want to respond to. Then, simply call [self hideKeyboard] from the touch event for that invisible button. Using IB, drag a new rounded button onto your view, then size it to take up the full size of the screen. Next,drag the button up or down the controls list in the IB document window so that button is behind all text fields and buttons, but in front of anything else (like images etc.). Finally, change the type of the button to 'Custom' to make it invisible, but still respond to events. Now all you have to do is to connect the new button's 'touch up inside' event to trigger the 'hideKeyboard' method.

Additionally, see this post for a brilliant solution to dismiss the keyboard when the above solution doesn't work : stackoverflow question 1823317

ContentLicense: CC BY-SA 2.5

Body:
You can create a generic 'hideKeyboard' method in which you can include all text fields that can be first responders. For example,

-(void) hideKeyboard {
     [textFieldName resignFirstResponder];
     [textFieldSurname resignFirstResponder];
     for (UITextField * txtField in arrTextFields) {
         [txtField resignFirstResponder];
      }
}

Then, at various sections in your class, depending on the functionality required, call;

[self hideKeyBoard];

This simple method means you won't need to keep track of the individual item that 'has the focus' / first responder status.

How to touch any part of the screen to make the keyboard go away
To touch somewhere outside the UITableView and have the keyboard disappear, place an invisible button on top of the 'touch area' that you want to respond to. Then, simply call [self hideKeyboard] from the touch event for that invisible button. Using IB, drag a new rounded button onto your view, then size it to take up the full size of the screen. Next,drag the button up or down the controls list in the IB document window so that button is behind all text fields and buttons, but in front of anything else (like images etc.). Finally, change the type of the button to 'Custom' to make it invisible, but still respond to events. Now all you have to do is to connect the new button's 'touch up inside' event to trigger the 'hideKeyboard' method.

Additionally, see this post for a brilliant solution to dismiss the keyboard when the above solution doesn't work : stackoverflow question 1823317


问:
Loading DataGrid from XML data file
I have a problem with loading data from an XML file in a WPF application.

XAML:

```<code>                    <DataGrid Name="dataGrid" ItemsSource="{Binding Path=Elements[Person]}" AutoGenerateColumns="False" HorizontalAlignment="Left" Height="331" Margin="12,10,-1.774,0" VerticalAlignment="Top" Width="834" FontSize="18" FontFamily="SimSun">
                    <DataGrid.Columns>
                        <DataGridCheckBoxColumn Header="Name" Binding="{Binding Path=Element[name].Value}"  />
                        <DataGridCheckBoxColumn Header="Surname" Binding="{Binding Path=Element[surname].Value}"  />
                        <DataGridCheckBoxColumn Header="Date born" Binding="{Binding Path=Element[dateBorn].Value}" />
                    </DataGrid.Columns>
                </DataGrid>
</code>```

XML File:

```<code><Persons>
<Person>
<name>Test1</name>
<surname>Test11</surname>
<dateBorn>02.12.1990</dateBorn>
</Person>

<Person>
<name>Test2</name>
<surname>Test22</surname>
<dateBorn>10.12.1991</dateBorn>
</Person>

<Person>
<name>Test3</name>
<surname>Test3</surname>
<dateBorn>09.12.1992</dateBorn>
</Person>
</code>```

My code:

```<code>        var peopleList = XElement.Load(dataBaseURL);
        dataGrid1.DataContext = peopleList;
</code>```

I get empty cells and  I load data from <person> </person> tags.

答:
Your ItemsSource looks correct, so do the bindings.

Try dataGrid1.DataContext = peopleList.Root; ?

ContentLicense: CC BY-SA 3.0

Title: Loading DataGrid from XML data file

Body:
I have a problem with loading data from an XML file in a WPF application.

XAML:

                    <DataGrid Name="dataGrid" ItemsSource="{Binding Path=Elements[Person]}" AutoGenerateColumns="False" HorizontalAlignment="Left" Height="331" Margin="12,10,-1.774,0" VerticalAlignment="Top" Width="834" FontSize="18" FontFamily="SimSun">
                    <DataGrid.Columns>
                        <DataGridCheckBoxColumn Header="Name" Binding="{Binding Path=Element[name].Value}"  />
                        <DataGridCheckBoxColumn Header="Surname" Binding="{Binding Path=Element[surname].Value}"  />
                        <DataGridCheckBoxColumn Header="Date born" Binding="{Binding Path=Element[dateBorn].Value}" />
                    </DataGrid.Columns>
                </DataGrid>

XML File:

<Persons>
<Person>
<name>Test1</name>
<surname>Test11</surname>
<dateBorn>02.12.1990</dateBorn>
</Person>

<Person>
<name>Test2</name>
<surname>Test22</surname>
<dateBorn>10.12.1991</dateBorn>
</Person>

<Person>
<name>Test3</name>
<surname>Test3</surname>
<dateBorn>09.12.1992</dateBorn>
</Person>

My code:

        var peopleList = XElement.Load(dataBaseURL);
        dataGrid1.DataContext = peopleList;

I get empty cells and  I load data from <person> </person> tags.


问:
Firebase notifications (only data) not receiving in Foreground
Hey everyone I've reading some problems that people have with Firebase and iOS notifications but seems that anybody is having the same issue.

For now I'm talking on FOREGROUND app state:

App receive the notification ever that have the parameter notification for exemple like this:

```<code>let notificationsParameters:[String:AnyObject] = [
        "to": "iphoneID",
        "content-available":true,
        "priority":"high",
// "notification" : [
//                "body" : "great match!",
//                "title" : "Portugal vs. Denmark",
//                "icon" : "myicon"
//            ],
        "data" : [
            "Nick" : "Mario",
            "Room" : "PortugalVSDenmark"
        ]
    ]
</code>```

but once I removed the notification part app doesn't receive nothing, even keeping in foreground where as I see everyone should receive the notification.

I added priority high to receiving even closed/background and content-available, that I read is suppoused to solve my problem but is not the case.

Here you have the involved code:

APP DELEGATE

```<code>func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        // Override point for customization after application launch.

        GMSServices.provideAPIKey(Constants.GoogleMaps.APIKey)
        FIRApp.configure()

        /* NOTFICATIONS */

        let notificationsType:UIUserNotificationType = [UIUserNotificationType.Alert, UIUserNotificationType.Badge, UIUserNotificationType.Sound]
        let notificationSettings = UIUserNotificationSettings(forTypes: notificationsType, categories: nil)
        application.registerForRemoteNotifications()
        application.registerUserNotificationSettings(notificationSettings)

        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.tokenRefreshNotification(_:)), name: kFIRInstanceIDTokenRefreshNotification, object: nil)

        return true
    }
</code>```

NOTIFICATIONS (IN APP DELEGATE)

As I understand this is what is suppouse that I will receive the data of the notification

```<code>func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject],
                     fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
        // If you are receiving a notification message while your app is in the background,
        // this callback will not be fired till the user taps on the notification launching the application.
        // TODO: Handle data of notification

        // Print message ID.
        print("Message ID: \(userInfo["gcm.message_id"]!)")

        // Print full message.
        print("%@", userInfo)
    }

    func tokenRefreshNotification(notification:NSNotification) {
        let refreshedToken = FIRInstanceID.instanceID().token()
        print("InstanceID token: \(refreshedToken)")

        connectToFCM()
    }

    func connectToFCM() {
        FIRMessaging.messaging().connectWithCompletion { (error) in
            if error != nil {
                print("GMS ERROR: \(error)")
            }
            else {
                print("Connected to GMS")
            }
        }
    }
</code>```

CALL TO FIREBASE NOTIFICATIONS

```<code>func sendNotification() {

        let notificationsParameters:[String:AnyObject] = [
            "to": "iphoneID",
            "content-available":true,
            "priority":"high",
            //            "notification" : [
            //                "body" : "great match!",
            //                "title" : "Portugal vs. Denmark",
            //                "icon" : "myicon"
            //            ],
            "data" : [
                "Nick" : "Mario",
                "Room" : "PortugalVSDenmark"
            ]
        ]

        let URL = NSURL(string: "https://fcm.googleapis.com/fcm/send")!
        let URLRequest = NSMutableURLRequest(URL: URL)

        URLRequest.HTTPMethod = "POST"

        URLRequest.setValue("key=\(Constants.Firebase.NotificationsKey)", forHTTPHeaderField: "Authorization")
        URLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")

        let encoding = Alamofire.ParameterEncoding.JSON

        let encoded = encoding.encode(URLRequest, parameters: (notificationsParameters)).0
        Alamofire.request(encoded)
    }
</code>```

Any further information you need just let me know!

答:
You were on the right track, but need an underscore instead of hyphen in the content_available parameter. No need to use the notification object if you want a data only (silent) notification using FCM.

Eg, in your FCM send request body:

```<code>{
    "to": "iPhoneID",
    "content_available": true,
    "priority": "high",
    "data": {
        "nick": "mario",
        "room": "PortugalVSDenmark"
    }
}
</code>```

Body:
Hey everyone I've reading some problems that people have with Firebase and iOS notifications but seems that anybody is having the same issue.

For now I'm talking on FOREGROUND app state:

App receive the notification ever that have the parameter notification for exemple like this:

let notificationsParameters:[String:AnyObject] = [
        "to": "iphoneID",
        "content-available":true,
        "priority":"high",
// "notification" : [
//                "body" : "great match!",
//                "title" : "Portugal vs. Denmark",
//                "icon" : "myicon"
//            ],
        "data" : [
            "Nick" : "Mario",
            "Room" : "PortugalVSDenmark"
        ]
    ]

but once I removed the notification part app doesn't receive nothing, even keeping in foreground where as I see everyone should receive the notification.

I added priority high to receiving even closed/background and content-available, that I read is suppoused to solve my problem but is not the case.

Here you have the involved code:

APP DELEGATE

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        // Override point for customization after application launch.

        GMSServices.provideAPIKey(Constants.GoogleMaps.APIKey)
        FIRApp.configure()

        /* NOTFICATIONS */

        let notificationsType:UIUserNotificationType = [UIUserNotificationType.Alert, UIUserNotificationType.Badge, UIUserNotificationType.Sound]
        let notificationSettings = UIUserNotificationSettings(forTypes: notificationsType, categories: nil)
        application.registerForRemoteNotifications()
        application.registerUserNotificationSettings(notificationSettings)

        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.tokenRefreshNotification(_:)), name: kFIRInstanceIDTokenRefreshNotification, object: nil)

        return true
    }

NOTIFICATIONS (IN APP DELEGATE)

As I understand this is what is suppouse that I will receive the data of the notification

func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject],
                     fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
        // If you are receiving a notification message while your app is in the background,
        // this callback will not be fired till the user taps on the notification launching the application.
        // TODO: Handle data of notification

        // Print message ID.
        print("Message ID: \(userInfo["gcm.message_id"]!)")

        // Print full message.
        print("%@", userInfo)
    }

    func tokenRefreshNotification(notification:NSNotification) {
        let refreshedToken = FIRInstanceID.instanceID().token()
        print("InstanceID token: \(refreshedToken)")

        connectToFCM()
    }

    func connectToFCM() {
        FIRMessaging.messaging().connectWithCompletion { (error) in
            if error != nil {
                print("GMS ERROR: \(error)")
            }
            else {
                print("Connected to GMS")
            }
        }
    }

CALL TO FIREBASE NOTIFICATIONS

func sendNotification() {

        let notificationsParameters:[String:AnyObject] = [
            "to": "iphoneID",
            "content-available":true,
            "priority":"high",
            //            "notification" : [
            //                "body" : "great match!",
            //                "title" : "Portugal vs. Denmark",
            //                "icon" : "myicon"
            //            ],
            "data" : [
                "Nick" : "Mario",
                "Room" : "PortugalVSDenmark"
            ]
        ]

        let URL = NSURL(string: "https://fcm.googleapis.com/fcm/send")!
        let URLRequest = NSMutableURLRequest(URL: URL)

        URLRequest.HTTPMethod = "POST"

        URLRequest.setValue("key=\(Constants.Firebase.NotificationsKey)", forHTTPHeaderField: "Authorization")
        URLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")

        let encoding = Alamofire.ParameterEncoding.JSON

        let encoded = encoding.encode(URLRequest, parameters: (notificationsParameters)).0
        Alamofire.request(encoded)
    }

Any further information you need just let me know!

Body:
You were on the right track, but need an underscore instead of hyphen in the content_available parameter. No need to use the notification object if you want a data only (silent) notification using FCM.

Eg, in your FCM send request body:

{
    "to": "iPhoneID",
    "content_available": true,
    "priority": "high",
    "data": {
        "nick": "mario",
        "room": "PortugalVSDenmark"
    }
}


问:
how to use JQuery "toggle" with parameters?
I have a table like this:

```<code><table>
  <tr>
    <td><input type="button" title="Toggle" value="Show" id="btn534534" class="toggle" />    </td>
    <td>some data about ID 534534</td>
  </tr>
  <tr id="row534534" class="hiddenRow">
    <td colspan="2">some hidden data about ID 534534 that must show/hide with toggle</td>
  </tr>
  <tr>
    <td><input type="button" title="Toggle" value="Show" id="btn2423434" class="toggle" /></td>
    <td>some data about ID 2423434</td>
  </tr>
  <tr id="row2423434" class="hiddenRow">
    <td colspan="2">some hidden data about ID 2423434that must show/hide with toggle</td>
  </tr>
  <!-- many more rows here -->
</table>
</code>```

There are MANY "sets" of rows like the above.  One row of the table is visible for each "set" of rows.  The second row with class "hiddenRow" is hidden on page load by JQuery like this:

```<code>$("tr.hiddenRow").hide();
</code>```

Now I want each button to toggle visibility of the row immediately after it.  Note that the INPUT in the visible row, and the TR of the hidden row share a unique ID.  I want to have the button onclick call a JQuery function and pass the ID so that JQuery knows which row to toggle.

Any ideas?  I can't find any examples of this online.

答:
I prefer @Nathan's solution, but if the DOM relationship would become more complicated, you would do it like so:

```<code>$('#tableID input.toggle').click(function() {
    $('#row' + this.id.replace('btn', '')).toggle();
});
</code>```

Live demo: http://jsfiddle.net/pHKat/1/

Update: The same thing as above, but using event delegation:

```<code>$('#tableID').click(function(e) {
    if (!$(e.target).hasClass('toggle')) { return; }
    $('#row' + e.target.id.replace('btn', '')).toggle();
});
</code>```

This code has one additional line of code, but performance-wise, this code is better, since only one event handler is bound (to the table element). For comparison, my original solution (above) binds one event handler per each button.

Body:
I have a table like this:

    <input type="button" title="Toggle" value="Show" id="btn534534" class="toggle" />
    some data about ID 534534

    some hidden data about ID 534534 that must show/hide with toggle

    <input type="button" title="Toggle" value="Show" id="btn2423434" class="toggle" />
    some data about ID 2423434

    some hidden data about ID 2423434that must show/hide with toggle

There are MANY "sets" of rows like the above.  One row of the table is visible for each "set" of rows.  The second row with class "hiddenRow" is hidden on page load by JQuery like this:

$("tr.hiddenRow").hide();

Now I want each button to toggle visibility of the row immediately after it.  Note that the INPUT in the visible row, and the TR of the hidden row share a unique ID.  I want to have the button onclick call a JQuery function and pass the ID so that JQuery knows which row to toggle.

Any ideas?  I can't find any examples of this online.

Body:
I prefer @Nathan's solution, but if the DOM relationship would become more complicated, you would do it like so:

$('#tableID input.toggle').click(function() {
    $('#row' + this.id.replace('btn', '')).toggle();
});

Live demo: http://jsfiddle.net/pHKat/1/

Update: The same thing as above, but using event delegation:

$('#tableID').click(function(e) {
    if (!$(e.target).hasClass('toggle')) { return; }
    $('#row' + e.target.id.replace('btn', '')).toggle();
});

This code has one additional line of code, but performance-wise, this code is better, since only one event handler is bound (to the table element). For comparison, my original solution (above) binds one event handler per each button.


问:
Read from command line
I have a problem with reading dates. Task:

The goal is to write a program capable of constructing and printing a Huffman tree for a specific file. The program will receive the name of the file in the form of a single command-line argument, read all data from the input file and build the Huffman tree for this file...

Example:

```<code>$>program.exe simple.in
</code>```

My solution:

```<code>string FileName = Console.ReadLine();
fileBytes = File.ReadAllBytes(FileName);
</code>```

But this solution writes:

RE:Runtime error 102: Dereferencing null value

Thanks

答:
This should get you started for reading from the command line, but you will need to do some research on the rest of what you're trying to do and come back when you have a specific question:

```<code>private static void Main(string[] args)
{
    Console.WriteLine($"The command line arguments entered are: {string.Join(" ", args)}");

    if (args.Length > 0)
    {
        var filePath = args[0];

        if (!File.Exists(filePath))
        {
            Console.WriteLine($"The specified file was not found: {filePath}");
        }
        else
        {
            // Process the file here
            var fileBytes = File.ReadAllBytes(filePath);
        }
    }
    else
    {
        Console.WriteLine(
            "Error: Enter the full path to a file as the first command line argument");
    }

    Console.WriteLine("\nDone!\nPress any key to exit...");
    Console.ReadKey();
}
</code>```

Title: Read from command line

Body:
I have a problem with reading dates. Task:

The goal is to write a program capable of constructing and printing a Huffman tree for a specific file. The program will receive the name of the file in the form of a single command-line argument, read all data from the input file and build the Huffman tree for this file...

Example:

$>program.exe simple.in

My solution:

string FileName = Console.ReadLine();
fileBytes = File.ReadAllBytes(FileName);

But this solution writes:

RE:Runtime error 102: Dereferencing null value

Thanks

Body:
This should get you started for reading from the command line, but you will need to do some research on the rest of what you're trying to do and come back when you have a specific question:

private static void Main(string[] args)
{
    Console.WriteLine($"The command line arguments entered are: {string.Join(" ", args)}");

    if (args.Length > 0)
    {
        var filePath = args[0];

        if (!File.Exists(filePath))
        {
            Console.WriteLine($"The specified file was not found: {filePath}");
        }
        else
        {
            // Process the file here
            var fileBytes = File.ReadAllBytes(filePath);
        }
    }
    else
    {
        Console.WriteLine(
            "Error: Enter the full path to a file as the first command line argument");
    }

    Console.WriteLine("\nDone!\nPress any key to exit...");
    Console.ReadKey();
}


问:
Automatically import data into SQL Server
I am trying to import data from a .CSV file into SQL Server automatically. For example, if I have a set of .CSV files in a folder, I want the data from those .CSV files to be imported into SQL Server automatically, every time I add a new .CSV file to that folder.

答:
EDITED!! THIS IS FOR PHP

```<code>$filenames = glob($_SERVER['DOCUMENT_ROOT'] .'/filespath/*');
foreach($filenames as $filename){ // iterate files
    if(!file_exists($filename) || substr($filename,-3) == 'csv') continue;
    $file = fopen($filename, "r");
    $csv = array();
    while (($line = fgetcsv($file)) !== FALSE) {
      //$line is an array of the csv elements
      $csv[] = $line;
    }
    fclose($file);
    foreach ($csv as $key => $value) {
      //put your code here to work with $csv array.
    }
}
</code>```

You can use this code to get what you want. You also need cron to automate your code. You can get it in your host cpanel.

Body:
EDITED!! THIS IS FOR PHP

$filenames = glob($_SERVER['DOCUMENT_ROOT'] .'/filespath/*');
foreach($filenames as $filename){ // iterate files
    if(!file_exists($filename) || substr($filename,-3) == 'csv') continue;
    $file = fopen($filename, "r");
    $csv = array();
    while (($line = fgetcsv($file)) !== FALSE) {
      //$line is an array of the csv elements
      $csv[] = $line;
    }
    fclose($file);
    foreach ($csv as $key => $value) {
      //put your code here to work with $csv array.
    }
}

You can use this code to get what you want. You also need cron to automate your code. You can get it in your host cpanel.


问:
Inline HTML is escaped by Jekyll
I have a problem with inline HTML in a github page, where inline HTML bullet lists are escaped in tables. The rows of the following table:

```<code>| Name | Value                 |
|------|-----------------------|
| one  | <i>foo</i>            |
| two  | <ul><li>bar</li></ul> |
</code>```

is rendered as:

```<code><tr>
  <td>one</td>
  <td><i>foo</i></td>
</tr>
<tr>
  <td>two</td>
  <td><ul><li>bar</li></ul></td>
</tr>
</code>```

The bullet list is rendered as expected by the GitHub UI, but in gh-pages, the
 is escaped. Why?

答:
This is by design as implemented by Kramdown, which is the Markdown processor that renders Markdown in GitHub pages.

Kramdown treats each new line as a row and doesn't render Markdown bullet lists inside table cells, and instead of rendering HTML, it is escaped and outputted as a single line of text.

You can tell Kramdown to leave the HTML alone and output as is, with the nomarkdown extension. Just wrap the HTML code with {::nomarkdown} ... {:/}

e.g.

```<code>| Name | Value                                   |
|------|-----------------------------------------|
| one  | {::nomarkdown}<i>foo</i>{:/}            |
| two  | {::nomarkdown}<ul><li>bar</li></ul>{:/} |
</code>```

Title: Inline HTML is escaped by Jekyll

Body:
I have a problem with inline HTML in a github page, where inline HTML bullet lists are escaped in tables. The rows of the following table:

| Name | Value                 |
|------|-----------------------|
| one  | foo            |
| two  |

bar

 |

is rendered as:

  one
  foo

  two

bar

The bullet list is rendered as expected by the GitHub UI, but in gh-pages, the
 is escaped. Why?

Body:
This is by design as implemented by Kramdown, which is the Markdown processor that renders Markdown in GitHub pages.

Kramdown treats each new line as a row and doesn't render Markdown bullet lists inside table cells, and instead of rendering HTML, it is escaped and outputted as a single line of text.

You can tell Kramdown to leave the HTML alone and output as is, with the nomarkdown extension. Just wrap the HTML code with {::nomarkdown} ... {:/}

e.g.

| Name | Value                                   |
|------|-----------------------------------------|
| one  | {::nomarkdown}<i>foo</i>{:/}            |
| two  | {::nomarkdown}<ul><li>bar</li></ul>{:/} |


问:
High-Quality Text-To-Speech engine for personal use
I'm looking for a high-quality TTS engine that I can afford (let's say less than 1000$). So far, I've tried flite and festival with default voices. However, while the results are certainly understandable, technical texts are hard to follow.

Commercial TTS solutions from Loquendo and Readspeaker sound way better. However, these companies don't seem to be willing to sell their product to mere mortals - I can't find a price on either's homepage.

So, what are good TTS solutions for personal use?

答:
I was always impressed by Ivona http://www.ivona.com/?set_lang=en
They have a cheap personal version called expressivo (add .com - can't post more links) which is just $45. I know people who watch movies with Expressivo reading the subtitles, so it's actually very very good.</p>


问:
What is DialogModule.BeginLifeTimeScope in Microsoft Bot Framework C#?
I am trying to understand the Proactive bot sample, where we create a scope, load the dialog stack, interrupt it in between and execute the interrupted one.
Can somebody explain me what are scopes in Dependency Injection. I am
 new to dependency injection and Autofac in C#.

1) What does DialogModule.BeginLifetimeScope(Conversation.Container do?

2) What does var stack = scope.Resolve<IDialogStack>(); do?

3) What does await stack.PollAsync(CancellationToken.None); do?

4) What does await botData.FlushAsync(CancellationToken.None); do?

```<code>// Create a scope that can be used to work with state from bot framework.
    using (var scope = DialogModule.BeginLifetimeScope(Conversation.Container, message))
    {
        var botData = scope.Resolve<IBotData>();
        await botData.LoadAsync(CancellationToken.None);

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

        // Create the new dialog and add it to the stack.
        var dialog =new SurveyDialog();
        stack.Call(dialog.Void<object, IMessageActivity>(), null);
        await stack.PollAsync(CancellationToken.None);

        // Flush the dialog stack back to its state store.
        await botData.FlushAsync(CancellationToken.None);
    }
</code>```

答:
Scope relates to visibility and lifetime.  In a multi-threaded application, there are some objects that can be used across threads and others that should be disposed of when processing completes. The bot framework sdk allows for processing multiple messages at once.  Some objects used by the bot builder to process messages are scoped to conversation id, and only one activity keyed on conversation id can be processed at a time.

1) What does DialogModule.BeginLifetimeScope(Conversation.Container do?

BeginSlifetimeScope can be found here: github:/Microsoft.Bot.Builder.Autofac/Dialogs/DialogModule.cs#L62 Basically, this line is using autofac to control the creation, scope, and lifetime of services used by the Bot Framework.  Please see here: http://autofaccn.readthedocs.io/en/latest/lifetime/ for more information on autofac lifetime.

2) What does var stack = scope.Resolve<IDialogStack>(); do?

Autofac will resolve this to the registered IDialogTaskManager.DialogTasks[0] see here:
github:/Microsoft.Bot.Builder.Autofac/Dialogs/DialogModule.cs#L223

3) What does await stack.PollAsync(CancellationToken.None); do?

This is an internal BotFramework method on IEventLoop. This implementation (on DialogTask) can be found here: github:/Microsoft.Bot.Builder/Dialogs/DialogTask.cs#L308  This method relates to processing work within the bot framework's internal event system.

4) What does await botData.FlushAsync(CancellationToken.None); do?

IBotData implementations are responsible for ensuring data is persisted to the store when .FlushAsync is called.

Body:
I am trying to understand the Proactive bot sample, where we create a scope, load the dialog stack, interrupt it in between and execute the interrupted one.
Can somebody explain me what are scopes in Dependency Injection. I am
 new to dependency injection and Autofac in C#.

1) What does DialogModule.BeginLifetimeScope(Conversation.Container do?

2) What does var stack = scope.Resolve<IDialogStack>(); do?

3) What does await stack.PollAsync(CancellationToken.None); do?

4) What does await botData.FlushAsync(CancellationToken.None); do?

// Create a scope that can be used to work with state from bot framework.
    using (var scope = DialogModule.BeginLifetimeScope(Conversation.Container, message))
    {
        var botData = scope.Resolve<IBotData>();
        await botData.LoadAsync(CancellationToken.None);

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

        // Create the new dialog and add it to the stack.
        var dialog =new SurveyDialog();
        stack.Call(dialog.Void<object, IMessageActivity>(), null);
        await stack.PollAsync(CancellationToken.None);

        // Flush the dialog stack back to its state store.
        await botData.FlushAsync(CancellationToken.None);
    }


问:
TensorFlow CNN with 3D input is too slow to train

Problem

I am building a TensorFlow CNN in Python 2.7 to classify 40x40x40 3D images into one of the two categories. The training data is stored in a HDF5 file as a (5000,40,40,40,1) array (5000 training images, 1 color channel). However, when I am training the network, each iteration of a batch of 32 images takes about a minute to complete. Through Activity Monitor I see that there are about 6GB data written to the disk in each iteration. The HDF5 itself is only about 500MB. What is happening?

This is the code I used to load data:

```<code>f = h5py.File(file_name, 'r')
images = f.get('key_name')
images = np.array(images)
images = images.astype(np.float32)
images = np.multiply(images, 1.0 / 100.0)
</code>```

I also tried to directly use a HDF5 object for each iteration, instead of loading all the data into memory at once. But the problem remains:

```<code>f = h5py.File(file_name, 'r')
images = np.array(f.get('key_name')[:batch_size])
</code>```

CNN Structure

The CNN I built has two 3D convolution layer, one flatten layer, one fully connected layer and one output layer. Here is the complete code for the structure:

```<code>num_channels = 1
filter_size_conv1 = 5
filter_size_conv2 = 5
num_filters_conv1 = 32
num_filters_conv2 = 64
fc_layer_size = 64

x = tf.placeholder(tf.float32, shape=[None, img_size, img_size, img_size, num_channels], name='x')
y_true = tf.placeholder(tf.float32, shape=[None, num_classes], name='y_true')
y_true_cls = tf.argmax(y_true, dimension=1)

def create_weights(shape):
    return tf.Variable(tf.truncated_normal(shape, stddev=0.05))

def create_biases(size):
    return tf.Variable(tf.constant(0.05,shape=[size]))

def create_convolutional_layer(input,
               num_input_channels,
               conv_filter_size,
               num_filters):
    weights = create_weights(shape=[
        conv_filter_size, conv_filter_size, conv_filter_size, num_input_channels, num_filters])
    biases = create_biases(num_filters)
    layer = tf.nn.conv3d(input=input,
                     filter=weights,
                     strides=[1, 1, 1, 1, 1],
                     padding='SAME')
    layer += biases
    layer = tf.nn.max_pool3d(input=layer,
                            ksize=[1, 4, 4, 4, 1],
                            strides=[1, 4, 4, 4, 1],
                            padding='SAME')
    layer = tf.nn.relu(layer)
    return layer

def create_flatten_layer(layer):
    layer_shape = layer.get_shape()
    num_features = layer_shape[1:5].num_elements()
    layer = tf.reshape(layer, [-1, num_features])
    return layer

def create_fc_layer(input,
             num_inputs,
             num_outputs,
             use_relu=True):
    weights = create_weights(shape=[num_inputs, num_outputs])
    biases = create_biases(num_outputs)
    layer = tf.matmul(input, weights) + biases
    if use_relu:
        layer = tf.nn.relu(layer)
    return layer

layer_conv1 = create_convolutional_layer(input=x,
               num_input_channels=num_channels,
               conv_filter_size=filter_size_conv1,
               num_filters=num_filters_conv1)

layer_conv2 = create_convolutional_layer(input=layer_conv1,
               num_input_channels=num_filters_conv1,
               conv_filter_size=filter_size_conv2,
               num_filters=num_filters_conv2)

layer_flat = create_flatten_layer(layer_conv2)

layer_fc1 = create_fc_layer(input=layer_flat,
                     num_inputs=layer_flat.get_shape()[1:5].num_elements(),
                     num_outputs=fc_layer_size,
                     use_relu=True)

layer_fc2 = create_fc_layer(input=layer_fc1,
                     num_inputs=fc_layer_size,
                     num_outputs=num_classes,
                     use_relu=False)
</code>```

Any help would be appreciated. Thank you so much!

答: I actually found the same problem here. I'm using conv3d and it takes like forever to finish. Probably related to the optimization of conv3d</p>

Body:
Problem

I am building a TensorFlow CNN in Python 2.7 to classify 40x40x40 3D images into one of the two categories. The training data is stored in a HDF5 file as a (5000,40,40,40,1) array (5000 training images, 1 color channel). However, when I am training the network, each iteration of a batch of 32 images takes about a minute to complete. Through Activity Monitor I see that there are about 6GB data written to the disk in each iteration. The HDF5 itself is only about 500MB. What is happening?

This is the code I used to load data:

f = h5py.File(file_name, 'r')
images = f.get('key_name')
images = np.array(images)
images = images.astype(np.float32)
images = np.multiply(images, 1.0 / 100.0)

I also tried to directly use a HDF5 object for each iteration, instead of loading all the data into memory at once. But the problem remains:

f = h5py.File(file_name, 'r')
images = np.array(f.get('key_name')[:batch_size])

CNN Structure

The CNN I built has two 3D convolution layer, one flatten layer, one fully connected layer and one output layer. Here is the complete code for the structure:

num_channels = 1
filter_size_conv1 = 5
filter_size_conv2 = 5
num_filters_conv1 = 32
num_filters_conv2 = 64
fc_layer_size = 64

x = tf.placeholder(tf.float32, shape=[None, img_size, img_size, img_size, num_channels], name='x')
y_true = tf.placeholder(tf.float32, shape=[None, num_classes], name='y_true')
y_true_cls = tf.argmax(y_true, dimension=1)

def create_weights(shape):
    return tf.Variable(tf.truncated_normal(shape, stddev=0.05))

def create_biases(size):
    return tf.Variable(tf.constant(0.05,shape=[size]))

def create_convolutional_layer(input,
               num_input_channels,
               conv_filter_size,
               num_filters):
    weights = create_weights(shape=[
        conv_filter_size, conv_filter_size, conv_filter_size, num_input_channels, num_filters])
    biases = create_biases(num_filters)
    layer = tf.nn.conv3d(input=input,
                     filter=weights,
                     strides=[1, 1, 1, 1, 1],
                     padding='SAME')
    layer += biases
    layer = tf.nn.max_pool3d(input=layer,
                            ksize=[1, 4, 4, 4, 1],
                            strides=[1, 4, 4, 4, 1],
                            padding='SAME')
    layer = tf.nn.relu(layer)
    return layer

def create_flatten_layer(layer):
    layer_shape = layer.get_shape()
    num_features = layer_shape[1:5].num_elements()
    layer = tf.reshape(layer, [-1, num_features])
    return layer

def create_fc_layer(input,
             num_inputs,
             num_outputs,
             use_relu=True):
    weights = create_weights(shape=[num_inputs, num_outputs])
    biases = create_biases(num_outputs)
    layer = tf.matmul(input, weights) + biases
    if use_relu:
        layer = tf.nn.relu(layer)
    return layer

layer_conv1 = create_convolutional_layer(input=x,
               num_input_channels=num_channels,
               conv_filter_size=filter_size_conv1,
               num_filters=num_filters_conv1)

layer_conv2 = create_convolutional_layer(input=layer_conv1,
               num_input_channels=num_filters_conv1,
               conv_filter_size=filter_size_conv2,
               num_filters=num_filters_conv2)

layer_flat = create_flatten_layer(layer_conv2)

layer_fc1 = create_fc_layer(input=layer_flat,
                     num_inputs=layer_flat.get_shape()[1:5].num_elements(),
                     num_outputs=fc_layer_size,
                     use_relu=True)

layer_fc2 = create_fc_layer(input=layer_fc1,
                     num_inputs=fc_layer_size,
                     num_outputs=num_classes,
                     use_relu=False)

Any help would be appreciated. Thank you so much!


问:
jQuery: hasClass logic issue
I'm building a dropdown menu and checking for classes etc. I'm having an issue where a condition is false, but it's being treated as true.

With the below code snippet, follow these instructions:

Click on "item 1"

Click on the plus icon above "more"

Click on "item 1" again

You'll notice that if you try to reopen the menu by clicking on "item 1" the menu does not open. Why? Those list items do NOT have a class of "show"... so those should open, irregardless of the second submenu, correct?

I'm not understanding what's wrong with my logic. I don't think this is a syntax error because there are no errors in console.

See below:

$(function() {
  // main expansion element
  $(".expander").click(function() {
    var subShown = $("ul > li", this).hasClass("show");
    if (!subShown) {
      $(".indented", this).slideDown('100').addClass("show");
      $(".caret", this).addClass("reversedCaret");
    } else {
      $(".indented", this).slideUp('100').removeClass("show");
      $(".caret", this).removeClass("reversedCaret");
    }
  });

  // sub expansion element
  $(".sub-expander").click(function() {
    var subSelectText = $(".more-or-less").text();
    if (subSelectText != "More") {
      $(".indented--sub").slideUp('100').removeClass("show");
      $(".sub-caret").removeClass("reversedCaret");
      $(".more-or-less").text("More");
    } else {
      $(".indented--sub").slideDown('100').addClass("show");
      $(".sub-caret").addClass("reversedCaret");
      $(".more-or-less").text("Show Less");
    }
  });

  // stop propagation on the link element within .expander class
  $(".indented").click(function(event) {
    event.stopPropagation();
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.expander:hover {
  cursor: pointer;
}

.sub-expander--indented {
  padding: 0 0 0 23px;
}

.sub-caret {
  margin-right: 75px;
}

.indented,
.indented--sub {
  display: none;
}

.show {
  display: block;
}</code>```

  +

Item 1

Item 2

Item 3

Chapter 5

Chapter 6

Chapter 7

        +

More

```

答: Your code don't work because you didn't remove class show in li  with class indented--sub

Title: jQuery: hasClass logic issue

Body:
I'm building a dropdown menu and checking for classes etc. I'm having an issue where a condition is false, but it's being treated as true.

With the below code snippet, follow these instructions:

Click on "item 1"

Click on the plus icon above "more"

Click on "item 1" again

You'll notice that if you try to reopen the menu by clicking on "item 1" the menu does not open. Why? Those list items do NOT have a class of "show"... so those should open, irregardless of the second submenu, correct?

I'm not understanding what's wrong with my logic. I don't think this is a syntax error because there are no errors in console.

See below:

$(function() {
  // main expansion element
  $(".expander").click(function() {
    var subShown = $("ul > li", this).hasClass("show");
    if (!subShown) {
      $(".indented", this).slideDown('100').addClass("show");
      $(".caret", this).addClass("reversedCaret");
    } else {
      $(".indented", this).slideUp('100').removeClass("show");
      $(".caret", this).removeClass("reversedCaret");
    }
  });

  // sub expansion element
  $(".sub-expander").click(function() {
    var subSelectText = $(".more-or-less").text();
    if (subSelectText != "More") {
      $(".indented--sub").slideUp('100').removeClass("show");
      $(".sub-caret").removeClass("reversedCaret");
      $(".more-or-less").text("More");
    } else {
      $(".indented--sub").slideDown('100').addClass("show");
      $(".sub-caret").addClass("reversedCaret");
      $(".more-or-less").text("Show Less");
    }
  });

  // stop propagation on the link element within .expander class
  $(".indented").click(function(event) {
    event.stopPropagation();
  });
});

.expander:hover {
  cursor: pointer;
}

.sub-expander--indented {
  padding: 0 0 0 23px;
}

.sub-caret {
  margin-right: 75px;
}

.indented,
.indented--sub {
  display: none;
}

.show {
  display: block;
}

  +

Item 1

Item 2

Item 3

Chapter 5

Chapter 6

Chapter 7

        +

More


问:
PowerShell: detecting errors in script functions
What is the best way to detect if an error occurs in a script function?  I'm looking for a consistent way to indicate error/success status similar to $? (which only works on cmdlets, not script functions).

Given a particular function might return a value to be used by the caller, we can't indicate success by returning a boolean.  A function could use a [ref] parameter and set the value appropriately inside the function and check after the call, but this is more overhead than I'd like.  Is there something built-in to PowerShell that we can use?

The best I can come up with is:

In the function use Write-Error to
put ErrorRecord objects in the error
stream;

call the function with an
ErrorVariable parameter;

check if the ErrorVariable parameter
is not null after the call.

For example:

```<code>function MyFun {
  [CmdletBinding()]    # must be an advanced function or this
  param ()             # will not work as ErrorVariable will not exist
  process {
    # code here....
    if ($SomeErrorCondition) {
      Write-Error -Message "Error occurred; details..."
      return
    }
    # more code here....
  }
}

# call the function
$Err = $null
MyFun -ErrorVariable Err
# this check would be similar to checking if $? -eq $false
if ($Err -ne $null) {
  "An error was detected"
  # handle error, log/email contents of $Err, etc.
}
</code>```

Is there something better?  Is there a way of using $? in our script functions?  I'd rather not throw exceptions or ErrorRecord objects and have tons of try/catch blocks all over the place.  I'd also rather not use $Error as would require checking the count before making the function call as there could be other errors in there before the call - and I don't want to Clear() and lose them.

答:
Most of this made a lovely whooshing sound as it went right over my head... ಠ_ಠ

I am with  Dan. PS Logging is a complete mess and seems like it will more than double the size of the code I am writing...

Frankly, I would be happy if I could just capture console output directly to logs, warts and all...

The Try/Catch block is so ... so ... crappy, I can smell it and it has made my eyes turn brown.

The $? is very interesting, but you guys actually know what you are doing, as where I am at the point where I have realized I know nothing (last week I thought I knew at least something, but noooooo).

Why the %$#@%$ isn't there something like the 2> in cli ...

Ok so here is what I am trying to do (you've read this far, so why not?):

```<code>    Function MyFunc($Param1, $Param2){
Do{
  $Var = Get-Something | Select Name, MachineName, Status
 $NotherVar = Read-Host -Prompt "Do you want to Stop or Start or check the $Var (1 to Start, 2 to stop, 3 to check, 4 to continue)?"
    If ($SetState -eq 1)
     {
      Do Stuff
    }
    ElseIf ($Var -eq 2)
       {
      Do Stuff
    }
    ElseIf ($Var -eq 3)
       {
      Do Stuff
    }
  }
    Until ($Var -eq 4)
Do other stuff
}
</code>```

Did it work? Yes, fine... Log it and continue. No? Then catch the error, log it and continue the script...

I am tempted to just ask for user input, add-content and continue...

Incidentally, I did find a module PSLogging that seems like it would be pretty cool, but I am not sure how to get it working... The documentation is a bit Spartan. Seems like folks are getting it working without too much trouble, so I kinda feel like I am a corner sitting pointy hat kind of person...

Body:
What is the best way to detect if an error occurs in a script function?  I'm looking for a consistent way to indicate error/success status similar to $? (which only works on cmdlets, not script functions).

Given a particular function might return a value to be used by the caller, we can't indicate success by returning a boolean.  A function could use a [ref] parameter and set the value appropriately inside the function and check after the call, but this is more overhead than I'd like.  Is there something built-in to PowerShell that we can use?

The best I can come up with is:

In the function use Write-Error to
put ErrorRecord objects in the error
stream;

call the function with an
ErrorVariable parameter;

check if the ErrorVariable parameter
is not null after the call.

For example:

function MyFun {
  [CmdletBinding()]    # must be an advanced function or this
  param ()             # will not work as ErrorVariable will not exist
  process {
    # code here....
    if ($SomeErrorCondition) {
      Write-Error -Message "Error occurred; details..."
      return
    }
    # more code here....
  }
}

# call the function
$Err = $null
MyFun -ErrorVariable Err
# this check would be similar to checking if $? -eq $false
if ($Err -ne $null) {
  "An error was detected"
  # handle error, log/email contents of $Err, etc.
}

Is there something better?  Is there a way of using $? in our script functions?  I'd rather not throw exceptions or ErrorRecord objects and have tons of try/catch blocks all over the place.  I'd also rather not use $Error as would require checking the count before making the function call as there could be other errors in there before the call - and I don't want to Clear() and lose them.

Body:
Most of this made a lovely whooshing sound as it went right over my head... ಠ_ಠ

I am with  Dan. PS Logging is a complete mess and seems like it will more than double the size of the code I am writing...

Frankly, I would be happy if I could just capture console output directly to logs, warts and all...

The Try/Catch block is so ... so ... crappy, I can smell it and it has made my eyes turn brown.

The $? is very interesting, but you guys actually know what you are doing, as where I am at the point where I have realized I know nothing (last week I thought I knew at least something, but noooooo).

Why the %$#@%$ isn't there something like the 2> in cli ...

Ok so here is what I am trying to do (you've read this far, so why not?):

    Function MyFunc($Param1, $Param2){
Do{
  $Var = Get-Something | Select Name, MachineName, Status
 $NotherVar = Read-Host -Prompt "Do you want to Stop or Start or check the $Var (1 to Start, 2 to stop, 3 to check, 4 to continue)?"
    If ($SetState -eq 1)
     {
      Do Stuff
    }
    ElseIf ($Var -eq 2)
       {
      Do Stuff
    }
    ElseIf ($Var -eq 3)
       {
      Do Stuff
    }
  }
    Until ($Var -eq 4)
Do other stuff
}

Did it work? Yes, fine... Log it and continue. No? Then catch the error, log it and continue the script...

I am tempted to just ask for user input, add-content and continue...

Incidentally, I did find a module PSLogging that seems like it would be pretty cool, but I am not sure how to get it working... The documentation is a bit Spartan. Seems like folks are getting it working without too much trouble, so I kinda feel like I am a corner sitting pointy hat kind of person...


问:
Pass Powershell parameters within Task Scheduler
```<code>function ServiceRestart
{
    Param
    (
        $ErrorLog,
        $Services,
        $MaxSize
    )

    $Time = Get-Date -Format 'yyyy:MM:dd HH:mm:ss'
    $Result = (Get-Item $ErrorLog).length

    if($Result -gt $MaxSize)
    {
        Clear-Content $ErrorLog
    }

    Try
    {
        Foreach($Service in $Services)
        {
            Restart-Service -DisplayName $Service -ErrorAction Stop
        }
    } Catch
      {
        "ERROR: $Service could not be restarted $Time" | Add-Content $ErrorLog
      }
}

ServiceRestart -ErrorLog -Services -MaxSize
</code>```

I need to pass in the following parameters from Task Scheduler

 - Errorlog

 - Services

-  MaxSize

I currently have my Task Scheduler setup like this

Program/script: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe

Add arguments(optional):
 -Command "& \ServerName\C$\Users*****\Documents\Scripts\Scheduled-ServiceRestart.ps1
 -ErrorLog 'ServerName\C$\Users*****\Documents\log\ScriptErrors.txt'
 -Services 'foo1' , 'foo2'
 -MaxSize '5MB'"

When I run the scheduled task nothing happens, what could be going wrong.

答:
As far as a literal answer to the question: Likely you need to add single quotes to surround your script location, otherwise it will try to interpret special characters/backslashes as escapes.

Ex:

```<code>-Command "& '\ServerName\C$\Users*****\Documents\Scripts\Scheduled-ServiceRestart.ps1' ...
</code>```

You could also add some basic logging in your powershell script to ensure that it is actually starting.

I use the "-Command &" style in production Powershell scheduled tasks & they work fine provided the strings are formatted properly.

Body:
function ServiceRestart
{
    Param
    (
        $ErrorLog,
        $Services,
        $MaxSize
    )

    $Time = Get-Date -Format 'yyyy:MM:dd HH:mm:ss'
    $Result = (Get-Item $ErrorLog).length

    if($Result -gt $MaxSize)
    {
        Clear-Content $ErrorLog
    }

    Try
    {
        Foreach($Service in $Services)
        {
            Restart-Service -DisplayName $Service -ErrorAction Stop
        }
    } Catch
      {
        "ERROR: $Service could not be restarted $Time" | Add-Content $ErrorLog
      }
}

ServiceRestart -ErrorLog -Services -MaxSize

I need to pass in the following parameters from Task Scheduler

 - Errorlog

 - Services

-  MaxSize

I currently have my Task Scheduler setup like this

Program/script: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe

Add arguments(optional):
 -Command "& \ServerName\C$\Users*****\Documents\Scripts\Scheduled-ServiceRestart.ps1
 -ErrorLog 'ServerName\C$\Users*****\Documents\log\ScriptErrors.txt'
 -Services 'foo1' , 'foo2'
 -MaxSize '5MB'"

When I run the scheduled task nothing happens, what could be going wrong.

Body:
As far as a literal answer to the question: Likely you need to add single quotes to surround your script location, otherwise it will try to interpret special characters/backslashes as escapes.

Ex:

-Command "& '\ServerName\C$\Users*****\Documents\Scripts\Scheduled-ServiceRestart.ps1' ...

You could also add some basic logging in your powershell script to ensure that it is actually starting.

I use the "-Command &" style in production Powershell scheduled tasks & they work fine provided the strings are formatted properly.


问:
What is the drush command to change a theme in Drupal 7?
What is the drush command to change a theme in Drupal 7?

```<code>drush theme disable theme_name
drush theme enable theme_name
</code>```

does not work.

答:
Take a look at the comment at http://drupal.org/node/530780#comment-2513534 which has the latest commands related to themes (actually, as of 3.0, but they seem to work with Drush 4.x as well).

Disable theme: drush -l http://example.com/ pm-disable theme_name

Enable theme: drush -l http://example.com/ pm-enable theme_name

Change theme: drush -l http://example.com/ vset theme_default theme_name

Change admin theme: drush -l http://example.com/ vset admin_theme theme_name

Body:
What is the drush command to change a theme in Drupal 7?

drush theme disable theme_name
drush theme enable theme_name

does not work.


问:
RecyclerView inside of Fragment only gets populated if adapter and RecyclerView are setup in onCreate
I have a custom DialogFragment that has it's own RecyclerView, and for some reason the data does not get populated unless the adapter/recyclerView logic is performed in onCreate.  Nothing will happen if it is called in onCreateView or onViewCreated, which is where I want all of this logic to happen.  Here is the version that works in onCreate:

```<code>@Override public void onCreate(@Nullable Bundle savedInstanceState) {
    root = (ViewGroup) getLayoutInflater().inflate(R.layout.dialog_content, null);

    ButterKnife.bind(this, root);

    MyAdapter adapter = new MenuOptionsAdapter(getContext(), this);
    adapter.setData(getData());
    rv.setAdapter(adapter);
    rv.setLayoutManager(new LinearLayoutManager(getContext()));

}
</code>```

And here is my try in onCreateView:

```<code>@Nullable
  @Override
  public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
      @Nullable Bundle savedInstanceState) {
    root = (ViewGroup) inflater.inflate(R.layout.dialog_content, container, false);
    ButterKnife.bind(this, root);

    // 'this' in the initialization of MyAdapter represents a custom interface, don't worry about it
    MyAdapter adapter = new MenuOptionsAdapter(getContext(), this);
    adapter.setData(getData());
    rv.setAdapter(adapter);
    rv.setLayoutManager(new LinearLayoutManager(getContext()));
}
</code>```

I tried to initialize root like this as well in onCreateView: root = (ViewGroup) getLayoutInflater().inflate(R.layout.dialog_content, null);
But no dice.

Does anyone know what could be a possible reason for this? I also tried adding the same exact code in onViewCreated, but again, no luck.

PS - I also tried adding adapter.notifyDataSetChanged() after setting the data and also tried it after rv.setData.

答:
Do the following:</p>

```<code>@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {

    root = (ViewGroup) LayoutInflater.from(getActivity()).inflate(R.layout.dialog_content, null, false);
    ButterKnife.bind(this, root);

    // 'this' in the initialization of MyAdapter represents a custom interface, don't worry about it
    MyAdapter adapter = new MenuOptionsAdapter(getContext(), this);
    adapter.setData(getData());
    rv.setAdapter(adapter);
    rv.setLayoutManager(new LinearLayoutManager(getContext()));

    return new AlertDialog.Builder(getActivity())
        .setView(root)
        .show();
}
</code>```

Body:
I have a custom DialogFragment that has it's own RecyclerView, and for some reason the data does not get populated unless the adapter/recyclerView logic is performed in onCreate.  Nothing will happen if it is called in onCreateView or onViewCreated, which is where I want all of this logic to happen.  Here is the version that works in onCreate:

@Override public void onCreate(@Nullable Bundle savedInstanceState) {
    root = (ViewGroup) getLayoutInflater().inflate(R.layout.dialog_content, null);

    ButterKnife.bind(this, root);

    MyAdapter adapter = new MenuOptionsAdapter(getContext(), this);
    adapter.setData(getData());
    rv.setAdapter(adapter);
    rv.setLayoutManager(new LinearLayoutManager(getContext()));

}

And here is my try in onCreateView:

@Nullable
  @Override
  public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
      @Nullable Bundle savedInstanceState) {
    root = (ViewGroup) inflater.inflate(R.layout.dialog_content, container, false);
    ButterKnife.bind(this, root);

    // 'this' in the initialization of MyAdapter represents a custom interface, don't worry about it
    MyAdapter adapter = new MenuOptionsAdapter(getContext(), this);
    adapter.setData(getData());
    rv.setAdapter(adapter);
    rv.setLayoutManager(new LinearLayoutManager(getContext()));
}

I tried to initialize root like this as well in onCreateView: root = (ViewGroup) getLayoutInflater().inflate(R.layout.dialog_content, null);
But no dice.

Does anyone know what could be a possible reason for this? I also tried adding the same exact code in onViewCreated, but again, no luck.

PS - I also tried adding adapter.notifyDataSetChanged() after setting the data and also tried it after rv.setData.

Body:
Do the following:

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {

    root = (ViewGroup) LayoutInflater.from(getActivity()).inflate(R.layout.dialog_content, null, false);
    ButterKnife.bind(this, root);

    // 'this' in the initialization of MyAdapter represents a custom interface, don't worry about it
    MyAdapter adapter = new MenuOptionsAdapter(getContext(), this);
    adapter.setData(getData());
    rv.setAdapter(adapter);
    rv.setLayoutManager(new LinearLayoutManager(getContext()));

    return new AlertDialog.Builder(getActivity())
        .setView(root)
        .show();
}


问:
How to extract closed caption transcript from YouTube video?
Is it possible to extract the closed caption transcript from YouTube videos?

We have over 200 webcasts on YouTube and each is at least one hour long. YouTube has closed caption for all videos but it seems users have no way to get it.

I tried the URL in this blog but it does not work with our videos.

http://googlesystem.blogspot.com/2010/10/download-youtube-captions.html

答:
Choose Open Transcript from the ... dropdown to the right of the vote up/down and share links.

This will open a Transcript scrolling div on the right side.

You can then use Copy. Note that you cannot use Select All but need to click the top line, then scroll to the bottom using the scroll thumb, and then shift-click on the last line.

Note that you can also search within this text using the normal web page search.

ContentLicense: CC BY-SA 4.0


问:
Run an Angular 4 Script via a scheduled CRON
We have an APP we built in Angular for Android phones. Part of the logic has become very complex, and we would like to move it to our server and run it every hours as a CRON instead of in the Phone APP. I have searched and keep finding how to schedule CRON's via Angular, but not how to run an Angular file via a Linux CRON. Don't need help with CRON's, but don't fully understand Angular and how to execute via the command line...</p>

答:
OK thanks the comments are helpful. So the answer is I need to be able to run something called NODE.JS which has a command line interface. In researching there is a serve install, then I can execute java script files via the command line.

UPDATE: Installed NODE.JS and now can run the Angular code via the command line, very good.


问:
django auto filling some data based on model attribute
am working on a concept in which I want to capture certain information when a model is saved. To understand the full picture, I have a app core with the following model

core/models.py

```<code>from django.db import models
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
from transmeta import TransMeta
from django.utils.translation import ugettext_lazy as _

import signals

class Audit(models.Model):
    ## TODO: Document
    # Polymorphic model using generic relation through DJANGO content type
    operation  = models.CharField(_('Operation'), max_length=40)
    operation_at = models.DateTimeField(_('Operation At'), auto_now_add=True)
    operation_by = models.ForeignKey(User, null=True, blank=True, related_name="%(app_label)s_%(class)s_y+")
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey('content_type', 'object_id')
</code>```

Audit model is a generic content type, am currently attaching it with other apps such as in blog

blog/models.py

```<code>from django.db import models
from django.contrib.contenttypes import generic
from django.contrib.contenttypes.models import ContentType
from django.template.defaultfilters import slugify
from django.utils.translation import ugettext_lazy as _
# Create your models here.

    class Meta:
        verbose_name_plural = "Categories"

class article(models.Model):
    title            = models.CharField(max_length=100)
    slug             = models.SlugField(editable=False, unique_for_year=True)
    content          = models.TextField()
    is_active        = models.BooleanField()
    published_at     = models.DateTimeField('Publish at',auto_now=True)
    related_articles = models.ManyToManyField('self', null=True, blank=True)
    audit_obj        = generic.GenericRelation('core.Audit', editable=False, null=True, blank=True)
</code>```

My first attempt was, I made a post_save signal in which I was checking if the instance passed containing audit_obj attribute and then saving a record in using article.audit_obj.create().save().

Unfortunately, this did not entirely work out for me since I cannot pass the request nor I can access the request to retrieve the user information.

So, I was thinking to create a custom signal and override the form_save method (if there is such a thing) and then using arguments to pass the request object as well as the model object.

Any advice on how I can do that?

Regards,

EDIT (20th of Jan, 2011):

Thanks @Yuji for your time. Well, what am trying to achieve is to keep my code as DRY as possible. What I want to do ultimately, every time I create new model, I will only create an additional attribute and name it audit_obj and I will create a single piece of code, either a signal or to override the save method inside the django core itself. The peiece of code will always check if an attribute with the following name exists and therefore creates a record in aduti table.

答:
I'd just create a function in my model class or Manager and call it from my form save (wherever yours might be)</p>

```<code>class AuditManager(models.Manager):
    def save_from_object(self, request, obj):
        audit = Audit()
        audit.object_id = obj.id
        audit.operation_by = request.user
        # ...

        audit.save()

class Audit(models.Model):
    ## TODO: Document
    # Polymorphic model using generic relation through DJANGO content type
    operation  = models.CharField(_('Operation'), max_length=40)
    operation_at = models.DateTimeField(_('Operation At'), auto_now_add=True)
    operation_by = models.ForeignKey(User, null=True, blank=True, related_name="%(app_label)s_%(class)s_y+")
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey('content_type', 'object_id')

    objects = AuditManager()

class MyBlogForm(forms.ModelForm):
    class Meta:
        model = article # btw I'd use Capital Letters For Classes

    def save(self, *args, **kwargs):
        super(MyBlogForm, self).save(*args, **kwargs)
        Audit.objects.save_from_object(request, self.instance)
</code>```

Body:
am working on a concept in which I want to capture certain information when a model is saved. To understand the full picture, I have a app core with the following model

core/models.py

from django.db import models
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
from transmeta import TransMeta
from django.utils.translation import ugettext_lazy as _

import signals

class Audit(models.Model):
    ## TODO: Document
    # Polymorphic model using generic relation through DJANGO content type
    operation  = models.CharField(_('Operation'), max_length=40)
    operation_at = models.DateTimeField(_('Operation At'), auto_now_add=True)
    operation_by = models.ForeignKey(User, null=True, blank=True, related_name="%(app_label)s_%(class)s_y+")
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey('content_type', 'object_id')

Audit model is a generic content type, am currently attaching it with other apps such as in blog

blog/models.py

from django.db import models
from django.contrib.contenttypes import generic
from django.contrib.contenttypes.models import ContentType
from django.template.defaultfilters import slugify
from django.utils.translation import ugettext_lazy as _
# Create your models here.

    class Meta:
        verbose_name_plural = "Categories"

class article(models.Model):
    title            = models.CharField(max_length=100)
    slug             = models.SlugField(editable=False, unique_for_year=True)
    content          = models.TextField()
    is_active        = models.BooleanField()
    published_at     = models.DateTimeField('Publish at',auto_now=True)
    related_articles = models.ManyToManyField('self', null=True, blank=True)
    audit_obj        = generic.GenericRelation('core.Audit', editable=False, null=True, blank=True)

My first attempt was, I made a post_save signal in which I was checking if the instance passed containing audit_obj attribute and then saving a record in using article.audit_obj.create().save().

Unfortunately, this did not entirely work out for me since I cannot pass the request nor I can access the request to retrieve the user information.

So, I was thinking to create a custom signal and override the form_save method (if there is such a thing) and then using arguments to pass the request object as well as the model object.

Any advice on how I can do that?

Regards,

EDIT (20th of Jan, 2011):

Thanks @Yuji for your time. Well, what am trying to achieve is to keep my code as DRY as possible. What I want to do ultimately, every time I create new model, I will only create an additional attribute and name it audit_obj and I will create a single piece of code, either a signal or to override the save method inside the django core itself. The peiece of code will always check if an attribute with the following name exists and therefore creates a record in aduti table.

Body:
I'd just create a function in my model class or Manager and call it from my form save (wherever yours might be)

class AuditManager(models.Manager):
    def save_from_object(self, request, obj):
        audit = Audit()
        audit.object_id = obj.id
        audit.operation_by = request.user
        # ...

        audit.save()

class Audit(models.Model):
    ## TODO: Document
    # Polymorphic model using generic relation through DJANGO content type
    operation  = models.CharField(_('Operation'), max_length=40)
    operation_at = models.DateTimeField(_('Operation At'), auto_now_add=True)
    operation_by = models.ForeignKey(User, null=True, blank=True, related_name="%(app_label)s_%(class)s_y+")
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey('content_type', 'object_id')

    objects = AuditManager()

class MyBlogForm(forms.ModelForm):
    class Meta:
        model = article # btw I'd use Capital Letters For Classes

    def save(self, *args, **kwargs):
        super(MyBlogForm, self).save(*args, **kwargs)
        Audit.objects.save_from_object(request, self.instance)


问:
Finding number of days between two dates in javascript/redux
```<code>    let oneDay = 24*60*60*1000;
    let firstDate = new Date();
    let secondDate = this.props.eventData.date
    let finalSecDate = new Date(secondDate)
    var timeDiff = Math.abs(firstDate.getTime() - finalSecDate.getTime());
    var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
</code>```

I am trying to calculate the number of days between two dates using javascript in a redux project. (My second date variable above is based on the date that a user enters and then I am changing it into a new Date format.) The above code works but when the event has passed the the number of days until the event is still coming up as positive number of days. Can someone please help me distinguish whether or not the date has passed so I can get the negative number of days.

I appreciate any help you can give, thank you !

答:
I would recommend using Moment.js, since they have a number of date functions that will become useful as you play around with dates more.

Here's what it would look like if you wanted to find the difference between two dates:

```<code>var present = moment();
var end = this.props.eventData.date;
present.diff(end, 'days') // 5
</code>```

The diff function finds the difference between the two dates. It also solves your problem of returning a negative value if the date already passed.

```<code>var present = moment();
var past = moment('2014-02-03 12:53:12');
past.diff(present, 'days') // -1379
</code>```

Body:
    let oneDay = 24*60*60*1000;
    let firstDate = new Date();
    let secondDate = this.props.eventData.date
    let finalSecDate = new Date(secondDate)
    var timeDiff = Math.abs(firstDate.getTime() - finalSecDate.getTime());
    var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));

I am trying to calculate the number of days between two dates using javascript in a redux project. (My second date variable above is based on the date that a user enters and then I am changing it into a new Date format.) The above code works but when the event has passed the the number of days until the event is still coming up as positive number of days. Can someone please help me distinguish whether or not the date has passed so I can get the negative number of days.

I appreciate any help you can give, thank you !

Body:
I would recommend using Moment.js, since they have a number of date functions that will become useful as you play around with dates more.

Here's what it would look like if you wanted to find the difference between two dates:

var present = moment();
var end = this.props.eventData.date;
present.diff(end, 'days') // 5

The diff function finds the difference between the two dates. It also solves your problem of returning a negative value if the date already passed.

var present = moment();
var past = moment('2014-02-03 12:53:12');
past.diff(present, 'days') // -1379


问:
VBA Multiple Passwords excel
Afternoon, first off, VBA noob here so take it easy on me and please spell out answers or provide full code as I am not familiar enough to just insert chunks as needed. I need a little more context.

What I am trying to do, is have multiple correct passwords but each password will do something different. This is as far as I have gotten and its current operation is as follows:

```<code>    Sub zebra()

Dim MyPassword As String
    MyPassword = "Zebra" ' Change this to alter password
    If InputBox("Please enter password to continue.", "Enter Password") <> MyPassword Then

    Dim Ans As Boolean
    Const Pword As String = "Zebra" ' This should match password

    Ans = False

    Do While Ans = False
        If InputBox("Please enter password to continue.", "Enter Password") = Pword Then
            Ans = True
        End If
    Loop
Exit Sub
End If

       Sheets("Level 3").Visible = True ' This selects what sheet should become visible

    End Sub
</code>```

Essentially, pop-up window, enter Zebra password, loop if wrong, unlock sheet "level 3 if correct". What I would like is if it could have the password Zebra unlock Level 3 but another password such as "Tiger" would unlock another sheet such as "Level 2".

In the end, what ever the password is, I need a specific and basically unique answer but am unsure how to code multiple passwords.
PLEASE NOTE: I would like to avoid writing multiple codes because the user interface needs to be simple enough for any level of proficiency to click a button, enter a password, and receive the correct information with ALL other information being hidden as it is highly confidential.

答:
First off all, the way you are trying to apply "security" is not the appropriate, so I suggest to find another alternatives to secure your file.

An alternative to what you are trying to do is to use Case Statement.
An example:

```<code>Select Case MyPassword
   Case "Zebra"
      Sheets("Level 3").Visible = True
   Case "Tiger"
      Sheets("Level 3").Visible = False
      Sheets("Level 2").Visible = True
   Case "Elephant"
      AnotherAction
   Case ""
      Msgbox "Password can not be empty."
   Case Else
      Msgbox "Wrong password."
End Select
</code>```

Hope it helps.

Title: VBA Multiple Passwords excel

Body:
Afternoon, first off, VBA noob here so take it easy on me and please spell out answers or provide full code as I am not familiar enough to just insert chunks as needed. I need a little more context.

What I am trying to do, is have multiple correct passwords but each password will do something different. This is as far as I have gotten and its current operation is as follows:

    Sub zebra()

Dim MyPassword As String
    MyPassword = "Zebra" ' Change this to alter password
    If InputBox("Please enter password to continue.", "Enter Password") <> MyPassword Then

    Dim Ans As Boolean
    Const Pword As String = "Zebra" ' This should match password

    Ans = False

    Do While Ans = False
        If InputBox("Please enter password to continue.", "Enter Password") = Pword Then
            Ans = True
        End If
    Loop
Exit Sub
End If

       Sheets("Level 3").Visible = True ' This selects what sheet should become visible

    End Sub

Essentially, pop-up window, enter Zebra password, loop if wrong, unlock sheet "level 3 if correct". What I would like is if it could have the password Zebra unlock Level 3 but another password such as "Tiger" would unlock another sheet such as "Level 2".

In the end, what ever the password is, I need a specific and basically unique answer but am unsure how to code multiple passwords.
PLEASE NOTE: I would like to avoid writing multiple codes because the user interface needs to be simple enough for any level of proficiency to click a button, enter a password, and receive the correct information with ALL other information being hidden as it is highly confidential.

Body:
First off all, the way you are trying to apply "security" is not the appropriate, so I suggest to find another alternatives to secure your file.

An alternative to what you are trying to do is to use Case Statement.
An example:

Select Case MyPassword
   Case "Zebra"
      Sheets("Level 3").Visible = True
   Case "Tiger"
      Sheets("Level 3").Visible = False
      Sheets("Level 2").Visible = True
   Case "Elephant"
      AnotherAction
   Case ""
      Msgbox "Password can not be empty."
   Case Else
      Msgbox "Wrong password."
End Select

Hope it helps.


问:
Regex adding undesired line break between backreference and literal in Notepad++
I have a text file with a list of elements separated by line-breaks, like this:

```<code>alpha
beta
gamma
...
</code>```

I want to get it into this format:

```<code>(alpha),
(beta),
(gamma),
...
</code>```

So I am using following regular expressions in Notepad++ for replacing those lines:

```<code>Find: ([^\n]+)
Replace: \($1\),
</code>```

but the output now strangely has another line-break for each line into it:

```<code>(alpha
),
(beta
),
(gamma
),
...
</code>```

I have no clue how this is happening. When I solely use $1 or \), apart for replacement it works just fine, but everytime I put a literal after the backreference it puts a line-break in between. I know that I can work around that with another regular expression afterwards, but could anybody explain to me why exactly this is happening?

答:
Instead of [^\n] (=any char but an LF, line feed, \n) you should use . that only matches any char other than line break chars. Use the following regex to match a non-empty line:

```<code>^.+$
</code>```

Replace with \($0\), where $0 replacement backreference (also called placeholder) stands for the whole match and the parentheses are escaped (since parentheses are special metacharacters inside Boost replacement patterns used to define conditional replacement patterns).

No need to use the m modifier here since ^ and $ anchors match start and end of the line respectively by default in Notepad++.

See the NPP S&R settings:

Body:
I have a text file with a list of elements separated by line-breaks, like this:

alpha
beta
gamma
...

I want to get it into this format:

(alpha),
(beta),
(gamma),
...

So I am using following regular expressions in Notepad++ for replacing those lines:

Find: ([^\n]+)
Replace: \($1\),

but the output now strangely has another line-break for each line into it:

(alpha
),
(beta
),
(gamma
),
...

I have no clue how this is happening. When I solely use $1 or \), apart for replacement it works just fine, but everytime I put a literal after the backreference it puts a line-break in between. I know that I can work around that with another regular expression afterwards, but could anybody explain to me why exactly this is happening?

Body:
Instead of [^\n] (=any char but an LF, line feed, \n) you should use . that only matches any char other than line break chars. Use the following regex to match a non-empty line:

^.+$

Replace with \($0\), where $0 replacement backreference (also called placeholder) stands for the whole match and the parentheses are escaped (since parentheses are special metacharacters inside Boost replacement patterns used to define conditional replacement patterns).

No need to use the m modifier here since ^ and $ anchors match start and end of the line respectively by default in Notepad++.

See the NPP S&R settings:


问:
SQL Concatenation using case statement
I have a table which looks like this:

```<code>**ID    col1  col2  col3  col4  col5**
1       abc   NULL  NULL  NULL  NULL
2       ght   cde   NULL  NULL  NULL
3       atr   dgf   aft   NULL  NULL
4       asd   rty   tyu   xyz   NULL
5       abc   pqr   xyz   rst   rty
6       qwe   rty   ghj   rty   tyu
</code>```

I want it change in this form:

```<code>**ID    NewCol**
1   abc
2   ght/cde
3   atr/dgf/aft
4   asd/rty/tyu/xyz
5   abc/pqr/xyz/rst/rty
6   qwe/rty/ghj/rty/tyu
</code>```

The query I wrote is:

```<code>     SELECT ID,
    NewCol = CASE WHEN col1 IS NOT NULL AND col2 IS NULL THEN col1
                WHEN col1 IS NOT NULL  AND col3 IS NULL THEN col1+'/' + col2
                WHEN col1 IS NOT NULL AND col4 IS  NULL THEN col1+'/'+ col2 + '/' + col3
                WHEN col1 IS NOT NULL AND col5 IS NULL THEN col1+'/' + col2 + '/' + col3+ '/' + col4
                WHEN col1 IS NOT NULL AND col5 IS not NULL THEN col1+'/' + col2 + '/' + col3+ '/' + col4 + '/' + col5
                ELSE NULL
  END
   FROM dbo.Temp
</code>```

If we have like 10 columns then I thought may be this is not an efficient way to write this.

Can you help me find a better solution to this one?

Thanks.

答:
You could use

```<code>col1 + concat('/' + col2, '/' + col3, '/' + col4, '/' + col5)
</code>```

If on 2012 or later  version

Title: SQL Concatenation using case statement

Body:
I have a table which looks like this:

**ID    col1  col2  col3  col4  col5**
1       abc   NULL  NULL  NULL  NULL
2       ght   cde   NULL  NULL  NULL
3       atr   dgf   aft   NULL  NULL
4       asd   rty   tyu   xyz   NULL
5       abc   pqr   xyz   rst   rty
6       qwe   rty   ghj   rty   tyu

I want it change in this form:

**ID    NewCol**
1   abc
2   ght/cde
3   atr/dgf/aft
4   asd/rty/tyu/xyz
5   abc/pqr/xyz/rst/rty
6   qwe/rty/ghj/rty/tyu

The query I wrote is:

     SELECT ID,
    NewCol = CASE WHEN col1 IS NOT NULL AND col2 IS NULL THEN col1
                WHEN col1 IS NOT NULL  AND col3 IS NULL THEN col1+'/' + col2
                WHEN col1 IS NOT NULL AND col4 IS  NULL THEN col1+'/'+ col2 + '/' + col3
                WHEN col1 IS NOT NULL AND col5 IS NULL THEN col1+'/' + col2 + '/' + col3+ '/' + col4
                WHEN col1 IS NOT NULL AND col5 IS not NULL THEN col1+'/' + col2 + '/' + col3+ '/' + col4 + '/' + col5
                ELSE NULL
  END
   FROM dbo.Temp

If we have like 10 columns then I thought may be this is not an efficient way to write this.

Can you help me find a better solution to this one?

Thanks.

Body:
You could use

col1 + concat('/' + col2, '/' + col3, '/' + col4, '/' + col5)

If on 2012 or later  version


问:
Is design now a subset of refactoring?
Looking at the cool new principles of software development:

Agile

You Ain't Gonna Need It

Less As A Competitive Advantage

Behaviour-Driven Development

The Evils Of Premature Optimization

The New Way seems to be to dive in and write what you need to achieve the first iteration of scope objectives, and refactor as necessary to have elegant solutions. Your codebase grows incrementally, and never has a big planning/hierarchical design stage. That, to me, suggests that software design (worthy though it is) has been subsumed into refactoring, because that's where the elegant code comes from, not the incremental additions to functionality.

Am I wrong?

答:
Let's see if we can get a definition. I'm going to suggest that there may be a book we could reference. How about the one by Martin Fowler?

"Refactoring: Improving the Design of Existing Code"

Now let's take as an example the TDD mantra:

until done do

Red (we wrote a test and it failed because there was nothing that could pass it)

Green (we designed and wrote some code and the test now succeeds)

Refactor (we need to integrate the design we did with everything else)

end

I know the Agile books tend to just say "write enough code to pass the test", but there's design implicit in that statement. By necessity. Choosing a variable name is a design decision. Not a big one, but a decision nonetheless. naming a function or method is a slightly bigger one, and so on up the food chain.

There's nothing in Agile that can ensure you always make good design decisions. Nothing in waterfall or any other process either. Agile does assert that you can't figure it all out upfront and tries - with some success in my experience - to give you a set of tools to help you make better decisions throughout the whole exercise.

OwnerDisplayName: Phil H

Title: Is design now a subset of refactoring?

LastEditorDisplayName: Phil H

OwnerDisplayName: Mike Woodhouse


问:
Is it possible to clear the ASP.NET application Cache without resetting the AppDomain?
I would like to reset/clear an item in the Cache, but without resetting the application or writing a specialized page just for this.  ie, a non-programmatic solution.  Is this possible?</p>

答:
```<code>            Dim CacheKeys As New List(Of String)
            For Each CacheItem As DictionaryEntry In Cache
                CacheKeys.Add(CacheItem.Key)
            Next

            For Each Key As String In CacheKeys
                Cache.Remove(Key)
            Next
</code>```

This appears to go through the cache and clear the items but it does not clear the Response cache.  If you login to a webpage using FormsAuthentication, goto a webpage, logout, then just type that URL into the address bar it return you to that page.  When you click on anything it return you to the login page because you are not authenticated but the page still displays from the cache even though the cache is cleared when the logout button is clicked.  Setting the Cachability to NoCache does not work because all GridViews that use DataBound event show as expired when using the back button.  I am still looking for a proper cache clearing solution for this case.

Body:
            Dim CacheKeys As New List(Of String)
            For Each CacheItem As DictionaryEntry In Cache
                CacheKeys.Add(CacheItem.Key)
            Next

            For Each Key As String In CacheKeys
                Cache.Remove(Key)
            Next

This appears to go through the cache and clear the items but it does not clear the Response cache.  If you login to a webpage using FormsAuthentication, goto a webpage, logout, then just type that URL into the address bar it return you to that page.  When you click on anything it return you to the login page because you are not authenticated but the page still displays from the cache even though the cache is cleared when the logout button is clicked.  Setting the Cachability to NoCache does not work because all GridViews that use DataBound event show as expired when using the back button.  I am still looking for a proper cache clearing solution for this case.


问:
Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https
I'm facing this issue with chrome and IE. I have developed  HTML player in that i used XML to load the data inside that player. all pages have been accessed through XML.it work fine when I use any server to load that data inside player.I use WAMP server now. But now I'm thinking about making it as an offline version and write it inside CD. but when I open my player.html file directly without having server, the XML data not going to load.it showing following error in the console.

XMLHttpRequest cannot load file:///C:/wamp/www/TTT_BR/english.xml. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

答: for testing/development purposes, the simplest solution is to use firefox browser. </p>