问:
In golang, why does `a := []int32("hello")` work but not `a := []int("hello")`?
The tile is my question. In Go, why does a := []int32("hello") work but not a := []int("hello")?

答:
Because the spec allows converting a string value to a rune slice ([]rune), and rune is an alias to int32 (they are one and the same). This is what the first conversion
 does:

Converting a value of a string type to a slice of runes type yields a slice containing the individual Unicode code points of the string.

Basically a string => []rune conversion decodes the UTF-8 bytes of the text (this is how Go stores strings in memory) to Unicode code points (runes).

And the spec does not allow converting a string to an int slice, so the second is a compile-time error.


来源: stackexchange

问:
Scrapy: connecto to MySQL
I am writing a Scrapy crawler, and I want it to send the data to a database. But I can't make it work, maybe because the pipeline. Here is my spider:

```<code>from scrapy.contrib.spiders import CrawlSpider
from scrapy.selector import Selector
from scrapy.http import Request

class YourCrawler(CrawlSpider):
    name = "bookstore"
    start_urls = [
    'https://example.com/materias/?novedades=LC&p',
    ]
    allowed_domains = ["example.com"]

    def parse(self, response):
        # go to the urls in the list
        s = Selector(response)
        page_list_urls = s.xpath('///*[@id="results"]/ul/li/div[1]/h4/a[2]/@href').extract()
        for url in page_list_urls:
            yield Request(response.urljoin(url), callback=self.parse_following_urls, dont_filter=True)

        # Return back and go to bext page in div#paginat ul li.next a::attr(href) and begin again
        next_page = response.css('div#paginat ul li.next a::attr(href)').extract_first()
        if next_page is not None:
            next_page = response.urljoin(next_page)
            yield Request(next_page, callback=self.parse)

    #Dont know if this has to go here
    if not s.select('//*[@id="logo"]/a/img'):
        yield Request(url=response.url, dont_filter=True)

    # For the urls in the list, go inside, and in div#main, take the div.ficha > div.caracteristicas > ul > li
    def parse_following_urls(self, response):
        #Parsing rules go here
        for each_book in response.css('div#main'):
            yield {
                'book_isbn': each_book.css('div.ficha > div.caracteristicas > ul > li').extract(),
            }
    custom_settings = {
        "DOWNLOAD_DELAY": 5,
        "CONCURRENT_REQUESTS_PER_DOMAIN": 2
    }
</code>```

And I want it to send the data to a database, so in pypelines.py I have

```<code>import pymysql
from scrapy.exceptions import DropItem
from scrapy.http import Request

class to_mysql(object):
    def __init__(self):
        self.connection = pymysql.connect("***","***","***","***", charset="utf8", use_unicode=True)
        self.cursor = self.connection.cursor()

    def process_item(self, item, spider):
        self.cursor.execute("INSERT INTO _b (book_isbn) VALUES (%s)", (item['book_isbn'].encode('utf-8')))
        self.connection.commit()
        return item

    def close_spider(self, spider):
        self.cursor.close()
        self.connection.close()
</code>```

And in settings.py

```<code>ITEM_PIPELINES = {
   'bookstore.pipelines.BookstorePipeline': 300,
   'bookstore.pipelines.to_mysql': 300,
}
</code>```

If I activate the pipeline «to_mysql» in settings.py it doesn't work, and returns this traceback:

```<code>Traceback (most recent call last):
  File "/usr/local/lib/python2.7/site-packages/twisted/internet/defer.py", line 653, in _runCallbacks
    current.result = callback(current.result, *args, **kw)
  File "/Users/***/scrapy/bookstore/bookstore/pipelines.py", line 27, in process_item
    self.cursor.execute("INSERT INTO _b (book_isbn) VALUES (%s)", (item['book_isbn'].encode('utf-8')))
AttributeError: 'list' object has no attribute 'encode'
2017-07-09 16:19:48 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://example.com/book/?id=9788416495412> (referer: https://example.com/materias/?novedades=LC&p)
2017-07-09 16:19:48 [scrapy.core.scraper] ERROR: Error processing {'book_isbn': [u'<li>Editorial: <a href="/search/avanzada/?go=1&editorial=Galaxia%20Gutenberg">Galaxia Gutenberg</a></li>', u'<li>P\xe1ginas: 325</li>', u'<li>A\xf1o: 2017</li>', u'<li>Precio: 21.90 \u20ac</li>', u'<li>Traductor: Pablo Moreno</li>', u'<li>EAN: 9788416495412</li>']}
</code>```

Any idea about why is this happening?

答:
this is because you are returning a list value on the book_isbn field, because .extract() returns a list and a list can't be encoded into an sql query.

You'll have to make serialize that value, or maybe you didn't want a list, in that case use extract_first().

ContentLicense: CC BY-SA 3.0

Title: Scrapy: connecto to MySQL

Body:
I am writing a Scrapy crawler, and I want it to send the data to a database. But I can't make it work, maybe because the pipeline. Here is my spider:

from scrapy.contrib.spiders import CrawlSpider
from scrapy.selector import Selector
from scrapy.http import Request

class YourCrawler(CrawlSpider):
    name = "bookstore"
    start_urls = [
    'https://example.com/materias/?novedades=LC&p',
    ]
    allowed_domains = ["example.com"]

    def parse(self, response):
        # go to the urls in the list
        s = Selector(response)
        page_list_urls = s.xpath('///*[@id="results"]/ul/li/div[1]/h4/a[2]/@href').extract()
        for url in page_list_urls:
            yield Request(response.urljoin(url), callback=self.parse_following_urls, dont_filter=True)

        # Return back and go to bext page in div#paginat ul li.next a::attr(href) and begin again
        next_page = response.css('div#paginat ul li.next a::attr(href)').extract_first()
        if next_page is not None:
            next_page = response.urljoin(next_page)
            yield Request(next_page, callback=self.parse)

    #Dont know if this has to go here
    if not s.select('//*[@id="logo"]/a/img'):
        yield Request(url=response.url, dont_filter=True)

    # For the urls in the list, go inside, and in div#main, take the div.ficha > div.caracteristicas > ul > li
    def parse_following_urls(self, response):
        #Parsing rules go here
        for each_book in response.css('div#main'):
            yield {
                'book_isbn': each_book.css('div.ficha > div.caracteristicas > ul > li').extract(),
            }
    custom_settings = {
        "DOWNLOAD_DELAY": 5,
        "CONCURRENT_REQUESTS_PER_DOMAIN": 2
    }

And I want it to send the data to a database, so in pypelines.py I have

import pymysql
from scrapy.exceptions import DropItem
from scrapy.http import Request

class to_mysql(object):
    def __init__(self):
        self.connection = pymysql.connect("***","***","***","***", charset="utf8", use_unicode=True)
        self.cursor = self.connection.cursor()

    def process_item(self, item, spider):
        self.cursor.execute("INSERT INTO _b (book_isbn) VALUES (%s)", (item['book_isbn'].encode('utf-8')))
        self.connection.commit()
        return item

    def close_spider(self, spider):
        self.cursor.close()
        self.connection.close()

And in settings.py

ITEM_PIPELINES = {
   'bookstore.pipelines.BookstorePipeline': 300,
   'bookstore.pipelines.to_mysql': 300,
}

If I activate the pipeline «to_mysql» in settings.py it doesn't work, and returns this traceback:

Traceback (most recent call last):
  File "/usr/local/lib/python2.7/site-packages/twisted/internet/defer.py", line 653, in _runCallbacks
    current.result = callback(current.result, *args, **kw)
  File "/Users/***/scrapy/bookstore/bookstore/pipelines.py", line 27, in process_item
    self.cursor.execute("INSERT INTO _b (book_isbn) VALUES (%s)", (item['book_isbn'].encode('utf-8')))
AttributeError: 'list' object has no attribute 'encode'
2017-07-09 16:19:48 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://example.com/book/?id=9788416495412> (referer: https://example.com/materias/?novedades=LC&p)
2017-07-09 16:19:48 [scrapy.core.scraper] ERROR: Error processing {'book_isbn': [u'
Editorial: Galaxia Gutenberg
', u'
P\xe1ginas: 325
', u'
A\xf1o: 2017
', u'
Precio: 21.90 \u20ac
', u'
Traductor: Pablo Moreno
', u'
EAN: 9788416495412
']}

Any idea about why is this happening?


问:
draft state/publish changes on save in angular 2
I'm using angular 4 in my application and currently the user is able to make changes over multiple components(drag and drop, remove items, add items and etc...).

Now, for every user action there is a http requests via the relevant service that persist the changes on the DB.

There is a requirement that the user will be able to make this changes and only persist them once he done changing and pressed save. (it can be 10-50 actions from different types.)

How would you suggest refactoring the code in order to support that ? to make an array of user actions, and on save iterate over the array and make the relevant actions one by one, write some http middleware to hold all http calls until 'save' is pressed?

答: You should look into redux. This would allow a MVP programming model and works just fine with Angular. ng2-redux</p>


问:
Convert List<V> in Map<K,V> with stream Java 8
I have a these model classes:

```<code>public class Student extends Person;

public class Professor extends Person;

public class University {
    private long id;
    private String name;
    private List<Person> employers;
....
}
</code>```

I have a List of University and I want to convert it into a Map; Person is an abstract class and has implemented hashCode and equals method.
This is an implementation with a for iteration:

```<code>Map<Person, University> mapList = new HashMap<Person, University>();
for (University u : universities) {
    for (Person p : u.getEmployers()) {
       mapList.put(p,u);
    }
}
mapList.forEach((k,v) -> System.out.println(k.toString() + v.getName()));
</code>```

I am not so familiar with Java 8 stream, but how can I covert this code with lambda expression?

答:
The other answers might be literally the same as your Java 7 version, and in this case with the built-in stream stuff it might be more succinct to use the forEach approach, but I'd like to show how to do with with purely FP style operations so that you can expand your comfort with streams.

You can use lambdas, but you don't need to for most functions as you can use Method references:

```<code>universities.stream()
// create maps for each university
    .map(u -> u.getEmployer().stream()
                .collect(Collectors.toMap(Function.identity(), p -> u))
// You need the entry set to turn back into a stream
    .map(Map::entrySet)
// flatten the entry sets into a single stream
    .flatMap(Set::stream)
// finally collect into the final map
    .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue))
</code>```

This could be simplified if you have a library with Tuples as you could skip the intermediate maps. You can also use the buil-in implementations of Map.Entry, but I find them much too verbose to be worth it.

Streams can be cleaner and more readable if you static import stuff like toMap, toList, etc.

Body:
I have a these model classes:

public class Student extends Person;

public class Professor extends Person;

public class University {
    private long id;
    private String name;
    private List<Person> employers;
....
}

I have a List of University and I want to convert it into a Map; Person is an abstract class and has implemented hashCode and equals method.
This is an implementation with a for iteration:

Map<Person, University> mapList = new HashMap<Person, University>();
for (University u : universities) {
    for (Person p : u.getEmployers()) {
       mapList.put(p,u);
    }
}
mapList.forEach((k,v) -> System.out.println(k.toString() + v.getName()));

I am not so familiar with Java 8 stream, but how can I covert this code with lambda expression?

Body:
The other answers might be literally the same as your Java 7 version, and in this case with the built-in stream stuff it might be more succinct to use the forEach approach, but I'd like to show how to do with with purely FP style operations so that you can expand your comfort with streams.

You can use lambdas, but you don't need to for most functions as you can use Method references:

universities.stream()
// create maps for each university
    .map(u -> u.getEmployer().stream()
                .collect(Collectors.toMap(Function.identity(), p -> u))
// You need the entry set to turn back into a stream
    .map(Map::entrySet)
// flatten the entry sets into a single stream
    .flatMap(Set::stream)
// finally collect into the final map
    .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue))

This could be simplified if you have a library with Tuples as you could skip the intermediate maps. You can also use the buil-in implementations of Map.Entry, but I find them much too verbose to be worth it.

Streams can be cleaner and more readable if you static import stuff like toMap, toList, etc.


问:
Set button color in jQuery mobile?
I have a jQuery Mobile app. This application has a single button that I need to give a special color.

In other words, there is only one button in this entire app that uses this color. I need to set it via CSS.

Currently, I have the following:

```<code><input type="button" value="My Button" style="background-color:#00ff21;" />
</code>```

This approach changes the color of the button. However, the color is faded. I didn't believe it at first, so I tried:

```<code><input type="button" value="My Button" style="background-color:yellow;" />
</code>```

It's very clear that the button color is faded. How do I set the color of a button so that it doesn't appear faded?

答: add a style background-color:yellow !important

Title: Set button color in jQuery mobile?

Body:
I have a jQuery Mobile app. This application has a single button that I need to give a special color.

In other words, there is only one button in this entire app that uses this color. I need to set it via CSS.

Currently, I have the following:

<input type="button" value="My Button" style="background-color:#00ff21;" />

This approach changes the color of the button. However, the color is faded. I didn't believe it at first, so I tried:

<input type="button" value="My Button" style="background-color:yellow;" />

It's very clear that the button color is faded. How do I set the color of a button so that it doesn't appear faded?


问:
How to attach file while sending email in laravel?
I tried to send email using laravel smtp,

```<code> Mail::send('mail', $data, function($message)  use ($request){
     $message->to($request->input('email'), 'Than Htut')->subject
        ($request->input('subject'));
     $message->attach($request->input('resume'));
     $message->from('myemail@gmail.com','My Name');
  });
  echo "HTML Email Sent. Check your inbox.";
</code>```

the problem is showing like this

Swift_IoException
  Unable to open file for reading

But if i use attachData like this

```<code>  Mail::send('mail', $data, function($message)  use ($request){
     $message->to($request->input('email'), 'Than Htut')->subject
        ($request->input('subject'));
     $message->attachData($request->input('resume'), "haha.pdf");
     $message->from('myemail@gmail.com','My Name');
  });
  echo "HTML Email Sent. Check your inbox.";
</code>```

its work, but cant open file. ,

Here is my fronend part,

```<code><form class="uk-form-stacked" action="{{ url('jobseekers/send') }}" method="post" id="cv_mail_data">
                    <input type="hidden" name="_token" value="{{ csrf_token() }}">
                    <input type="hidden" name="cv_no" value="{{ $jobseekers->id }}">

  <input type="text" placeholder="To" name="email" class="md-input" multiple>
  <input type="text" placeholder="To" name="subject" class="md-input" multiple>
  <input type="file" name="resume" accept="application/pdf,application/vnd.ms-excel" />

                             <div class="uk-grid" data-uk-grid-margin>
                                <div class="uk-width-medium-1-1 parsley-row">
                                    <textarea id="wysiwyg_tinymce" name="cover_letter" cols="30"
                                              rows="20"></textarea>
                                </div>
                            </div>
                             <button type="submit" class="btn btn-primary">
                                Create
                            </button>
</code>```

please guide me, thanks.

答:
First of all, where's your enctype="multipart/form-data" attribute in your form?
And second, for retrieving files on laravel you use the file method $request->file('your-file');.

Body:
I tried to send email using laravel smtp,

 Mail::send('mail', $data, function($message)  use ($request){
     $message->to($request->input('email'), 'Than Htut')->subject
        ($request->input('subject'));
     $message->attach($request->input('resume'));
     $message->from('myemail@gmail.com','My Name');
  });
  echo "HTML Email Sent. Check your inbox.";

the problem is showing like this

Swift_IoException
  Unable to open file for reading

But if i use attachData like this

  Mail::send('mail', $data, function($message)  use ($request){
     $message->to($request->input('email'), 'Than Htut')->subject
        ($request->input('subject'));
     $message->attachData($request->input('resume'), "haha.pdf");
     $message->from('myemail@gmail.com','My Name');
  });
  echo "HTML Email Sent. Check your inbox.";

its work, but cant open file. ,

Here is my fronend part,

<form class="uk-form-stacked" action="{{ url('jobseekers/send') }}" method="post" id="cv_mail_data">
                    <input type="hidden" name="_token" value="{{ csrf_token() }}">
                    <input type="hidden" name="cv_no" value="{{ $jobseekers->id }}">

  <input type="text" placeholder="To" name="email" class="md-input" multiple>
  <input type="text" placeholder="To" name="subject" class="md-input" multiple>
  <input type="file" name="resume" accept="application/pdf,application/vnd.ms-excel" />

                                    <textarea id="wysiwyg_tinymce" name="cover_letter" cols="30"
                                              rows="20"></textarea>

                             <button type="submit" class="btn btn-primary">
                                Create
                            </button>

please guide me, thanks.


问:
Remove Time and Timezone from String Dates
I would like to get the date (without timezone or time) from differently formatted strings that are passed into my function. The problem I am having is that the dates are not processing correctly due to the timezone I am in. Here is the current function I have:

```<code>function pgFormatDate(date) {
    /* Via http://stackoverflow.com/questions/3605214/javascript-add-leading-zeroes-to-date */
    function zeroPad(d) {
        return ("0" + d).slice(-2)
    }

    if (date) {
        var parsed = new Date(date)
        return [parsed.getUTCFullYear(), zeroPad(parsed.getMonth() + 1), zeroPad(parsed.getDate())].join("-");
    } else {
        return null;
    }
}
</code>```

And here is the makeshift test harness I have created for it (all "tests" should log true if the function is working.

```<code>var test1Result = dateConvertsCorrectly("Fri Jul 07 2017 22:10:08 GMT-0500 (CDT)", "2017-07-07"); // Currently working and logging true, but break when I try to fix the others
var test2Result = dateConvertsCorrectly("Fri Jul 07 2017 02:10:08 GMT-0500 (CDT)", "2017-07-07"); // Currently working and logging true, but break when I try to fix the others
var test3Result = dateConvertsCorrectly("2017-07-07", "2017-07-07"); // Currently not working and logging false
var test4Result = dateConvertsCorrectly("Fri Jul 06 2017 22:10:08 GMT-0500 (CDT)", "2017-07-06"); // Currently working and logging true, but break when I try to fix the others
var test5Result = dateConvertsCorrectly("2017-07-06T02:59:12.037Z", "2017-07-06"); // Currently not working and logging false
var test6Result = dateConvertsCorrectly("2017-06-07", "2017-06-07"); // Currently not working and logging false

console.log('test 1 passed:', test1Result);
console.log('test 2 passed:', test2Result);
console.log('test 3 passed:', test3Result);
console.log('test 4 passed:', test4Result);
console.log('test 5 passed:', test5Result);
console.log('test 6 passed:', test6Result);

function pgFormatDate(date) {
    /* Via http://stackoverflow.com/questions/3605214/javascript-add-leading-zeroes-to-date */
    function zeroPad(d) {
        return ("0" + d).slice(-2)
    }

    if (date) {
        var parsed = new Date(date)
        return [parsed.getUTCFullYear(), zeroPad(parsed.getMonth() + 1), zeroPad(parsed.getDate())].join("-");
    } else {
        return null;
    }
}

function dateConvertsCorrectly (input, expectedOutput) {
    return pgFormatDate(input) === expectedOutput;
}
</code>```

Tests 3, 5, and 6 are all failing in the CDT timezone. But I would like the code to work regardless of timezone (I really just want to keep the year, month, and day that are submitted). Using moment hasn't worked because the dates don't fit into the accepted date types allowed by moment and I get an error, so I would like to be able to do this with vanilla javascript.

Here is the jsFiddle: https://jsfiddle.net/lukeschlangen/bkyquu7j/

答:
Big thanks to Máté Solymosi for the suggestion of custom moment date formats. I did end up using moment and here is what I got working:</p>

```<code>function pgFormatDate(date) {
    if (date) {
        if (moment(date.substring(4,15), 'MMM DD YYYY').isValid() && date.substring(4,15).length === 11) {
            return moment(date.substring(4,15), 'MMM DD YYYY').format('YYYY-MM-DD');
        } else if (moment(date.substring(0,10), "YYYY-MM-DD").isValid() && date.substring(0,10).length === 10) {
            return date.substring(0,10);
        } else {
            throw 'Date not formatted correctly';
        }
    } else {
        throw 'Date must exist for formatting to occur'
    }
}
</code>```

Body:
I would like to get the date (without timezone or time) from differently formatted strings that are passed into my function. The problem I am having is that the dates are not processing correctly due to the timezone I am in. Here is the current function I have:

function pgFormatDate(date) {
    /* Via http://stackoverflow.com/questions/3605214/javascript-add-leading-zeroes-to-date */
    function zeroPad(d) {
        return ("0" + d).slice(-2)
    }

    if (date) {
        var parsed = new Date(date)
        return [parsed.getUTCFullYear(), zeroPad(parsed.getMonth() + 1), zeroPad(parsed.getDate())].join("-");
    } else {
        return null;
    }
}

And here is the makeshift test harness I have created for it (all "tests" should log true if the function is working.

var test1Result = dateConvertsCorrectly("Fri Jul 07 2017 22:10:08 GMT-0500 (CDT)", "2017-07-07"); // Currently working and logging true, but break when I try to fix the others
var test2Result = dateConvertsCorrectly("Fri Jul 07 2017 02:10:08 GMT-0500 (CDT)", "2017-07-07"); // Currently working and logging true, but break when I try to fix the others
var test3Result = dateConvertsCorrectly("2017-07-07", "2017-07-07"); // Currently not working and logging false
var test4Result = dateConvertsCorrectly("Fri Jul 06 2017 22:10:08 GMT-0500 (CDT)", "2017-07-06"); // Currently working and logging true, but break when I try to fix the others
var test5Result = dateConvertsCorrectly("2017-07-06T02:59:12.037Z", "2017-07-06"); // Currently not working and logging false
var test6Result = dateConvertsCorrectly("2017-06-07", "2017-06-07"); // Currently not working and logging false

console.log('test 1 passed:', test1Result);
console.log('test 2 passed:', test2Result);
console.log('test 3 passed:', test3Result);
console.log('test 4 passed:', test4Result);
console.log('test 5 passed:', test5Result);
console.log('test 6 passed:', test6Result);

function pgFormatDate(date) {
    /* Via http://stackoverflow.com/questions/3605214/javascript-add-leading-zeroes-to-date */
    function zeroPad(d) {
        return ("0" + d).slice(-2)
    }

    if (date) {
        var parsed = new Date(date)
        return [parsed.getUTCFullYear(), zeroPad(parsed.getMonth() + 1), zeroPad(parsed.getDate())].join("-");
    } else {
        return null;
    }
}

function dateConvertsCorrectly (input, expectedOutput) {
    return pgFormatDate(input) === expectedOutput;
}

Tests 3, 5, and 6 are all failing in the CDT timezone. But I would like the code to work regardless of timezone (I really just want to keep the year, month, and day that are submitted). Using moment hasn't worked because the dates don't fit into the accepted date types allowed by moment and I get an error, so I would like to be able to do this with vanilla javascript.

Here is the jsFiddle: https://jsfiddle.net/lukeschlangen/bkyquu7j/

Body:
Big thanks to Máté Solymosi for the suggestion of custom moment date formats. I did end up using moment and here is what I got working:

function pgFormatDate(date) {
    if (date) {
        if (moment(date.substring(4,15), 'MMM DD YYYY').isValid() && date.substring(4,15).length === 11) {
            return moment(date.substring(4,15), 'MMM DD YYYY').format('YYYY-MM-DD');
        } else if (moment(date.substring(0,10), "YYYY-MM-DD").isValid() && date.substring(0,10).length === 10) {
            return date.substring(0,10);
        } else {
            throw 'Date not formatted correctly';
        }
    } else {
        throw 'Date must exist for formatting to occur'
    }
}


问:
JavaScript - How do I get the URL of script being called?
I include myscript.js in the file http://site1.com/index.html like this:

```<code><script src=http://site2.com/myscript.js></script>
</code>```

Inside "myscript.js", I want to get access to the URL "http://site2.com/myscript.js".  I'd like to have something like this:

```<code>function getScriptURL() {
    // something here
    return s
}

alert(getScriptURL());
</code>```

Which would alert "http://site2.com/myscript.js" if called from the index.html mentioned above.

答:
Simple and straightforward solution that work very well :

If it not IE you can use document.currentScript

For IE you can do document.querySelector('script[src*="myscript.js"]')

so :

```<code>function getScriptURL(){
 var script =  document.currentScript || document.querySelector('script[src*="myscript.js"]')
 return script.src
}
</code>```

update

In a module script, you can use:

```<code> import.meta.url
</code>```

as describe in mdn

Body:
I include myscript.js in the file http://site1.com/index.html like this:

Inside "myscript.js", I want to get access to the URL "http://site2.com/myscript.js".  I'd like to have something like this:

function getScriptURL() {
    // something here
    return s
}

alert(getScriptURL());

Which would alert "http://site2.com/myscript.js" if called from the index.html mentioned above.

Body:
Simple and straightforward solution that work very well :

If it not IE you can use document.currentScript

For IE you can do document.querySelector('script[src*="myscript.js"]')

so :

function getScriptURL(){
 var script =  document.currentScript || document.querySelector('script[src*="myscript.js"]')
 return script.src
}

update

In a module script, you can use:

 import.meta.url

as describe in mdn

ContentLicense: CC BY-SA 4.0


问:
Error installig pjproject on Ubuntu Linux
I'm installing pjproject on Ubuntu Linux. I'm trying to install the pjproject using this article:
https://trac.pjsip.org/repos/wiki/Python_SIP/Build_Install
 Everything looks fine up through make dep .so files when I run make dep and make , i receive this error:

```<code>../src/pjmedia-audiodev/alsa_dev.c:37:28: fatal error: alsa/asoundlib.h: No such file or directory
 #include <alsa/asoundlib.h>
                            ^
compilation terminated.
/home/wissam/Downloads/pjproject-master/build/rules.mak:163: recipe for target 'output/pjmedia-audiodev-x86_64-unknown-linux-gnu/alsa_dev.o' failed
make[2]: *** [output/pjmedia-audiodev-x86_64-unknown-linux-gnu/alsa_dev.o] Error 1
make[2]: Leaving directory '/home/wissam/Downloads/pjproject-master/pjmedia/build'
Makefile:230: recipe for target 'libpjmedia-audiodev-x86_64-unknown-linux-gnu.a' failed
make[1]: *** [libpjmedia-audiodev-x86_64-unknown-linux-gnu.a] Error 2
make[1]: Leaving directory '/home/wissam/Downloads/pjproject-master/pjmedia/build'
Makefile:14: recipe for target 'all' failed
make: *** [all] Error 1
</code>```

Can anyone help me diagnose this error and resolve it?

答:
To build on @mkiever's comment, you're missing a library needed to compile the C language component. In C, in order to reference libraries, a line like #include <alsa/asoundlib.h> is included.

If you know you've installed this in the past, check your installation and path variables.  If not, the written instruction don't seem to do it for you.

In Ubuntu, the package you want can be installed with sudo apt install libasound2-dev.  After this installation, you should be able to install as expected.

Body:
I'm installing pjproject on Ubuntu Linux. I'm trying to install the pjproject using this article:
https://trac.pjsip.org/repos/wiki/Python_SIP/Build_Install
 Everything looks fine up through make dep .so files when I run make dep and make , i receive this error:

../src/pjmedia-audiodev/alsa_dev.c:37:28: fatal error: alsa/asoundlib.h: No such file or directory
 #include <alsa/asoundlib.h>
                            ^
compilation terminated.
/home/wissam/Downloads/pjproject-master/build/rules.mak:163: recipe for target 'output/pjmedia-audiodev-x86_64-unknown-linux-gnu/alsa_dev.o' failed
make[2]: *** [output/pjmedia-audiodev-x86_64-unknown-linux-gnu/alsa_dev.o] Error 1
make[2]: Leaving directory '/home/wissam/Downloads/pjproject-master/pjmedia/build'
Makefile:230: recipe for target 'libpjmedia-audiodev-x86_64-unknown-linux-gnu.a' failed
make[1]: *** [libpjmedia-audiodev-x86_64-unknown-linux-gnu.a] Error 2
make[1]: Leaving directory '/home/wissam/Downloads/pjproject-master/pjmedia/build'
Makefile:14: recipe for target 'all' failed
make: *** [all] Error 1

Can anyone help me diagnose this error and resolve it?


问:
ComponentScan excludeFilters Not Working In Spring 4.0.6.RELEASE
I have a class which I want to exclude while component scanning. I am using the below code to do that but that doesn't seem to work although everything seems to be right

```<code>@ComponentScan(basePackages = { "common", "adapter", "admin"}, excludeFilters = { @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = ServiceImpl.class) })
</code>```

Actually I want have "ServiceImpl" class, which implements "Service" interface, is being used in my rest api logic and while doing the integration test of an api I want to exclude this implmentation and load the mocked implementation. But this doesn't seem to happen as even after using the above I am getting the below error

```<code>No qualifying bean of type [admin.Service] is defined: expected single matching bean but found 2: ServiceMockImpl,ServiceImpl
</code>```

I spent too much of time on this but nothing works.

Any help is appreciated.

答:
I had an issue when using @Configuration, @EnableAutoConfiguration and @ComponentScan when trying to exclude specific configuration classes, but it didn't work!

Eventually I solved the problem by using @SpringBootApplication, which according to Spring documentation does the same functionality as the three above in one annotation.

Another Tip is to try first without refining your package scan (without the basePackages filter).

```<code>@SpringBootApplication(exclude= {Foo.class})
public class MySpringConfiguration {}
</code>```

Body:
I have a class which I want to exclude while component scanning. I am using the below code to do that but that doesn't seem to work although everything seems to be right

@ComponentScan(basePackages = { "common", "adapter", "admin"}, excludeFilters = { @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = ServiceImpl.class) })

Actually I want have "ServiceImpl" class, which implements "Service" interface, is being used in my rest api logic and while doing the integration test of an api I want to exclude this implmentation and load the mocked implementation. But this doesn't seem to happen as even after using the above I am getting the below error

No qualifying bean of type [admin.Service] is defined: expected single matching bean but found 2: ServiceMockImpl,ServiceImpl

I spent too much of time on this but nothing works.

Any help is appreciated.

Body:
I had an issue when using @Configuration, @EnableAutoConfiguration and @ComponentScan when trying to exclude specific configuration classes, but it didn't work!

Eventually I solved the problem by using @SpringBootApplication, which according to Spring documentation does the same functionality as the three above in one annotation.

Another Tip is to try first without refining your package scan (without the basePackages filter).

@SpringBootApplication(exclude= {Foo.class})
public class MySpringConfiguration {}


问:
Access the powershell console (package manager console) of visual studio programmatically in an extension
I am trying to develop a visual studio extension to automate parts of our entity framework migration process.  I checked to add migration programmatically but after looking at entity framework source, a lot is done in powershell scripts, so I would like to get a hook on the package manager console (nuget) and send a command there and read the result from the console if possible.

How do I access the package manager console programmatically in a visual studio extension?

For example I would like to send the following command to the package manager console.

```<code>add-migration migration01
</code>```

答:
The best way for running a script in package manager console is parameter passing into it.</p>

```<code>EnvDTE.DTE _ObjDTE;
_ObjDTE = (DTE)System.Runtime.InteropServices.Marshal.GetActiveObject("VisualStudio.DTE");
var script = "function global:SaveAll {write-host \"All files saved.\"} SaveAll";
_ObjDTE.ExecuteCommand("View.PackageManagerConsole", script);
</code>```

Body:
I am trying to develop a visual studio extension to automate parts of our entity framework migration process.  I checked to add migration programmatically but after looking at entity framework source, a lot is done in powershell scripts, so I would like to get a hook on the package manager console (nuget) and send a command there and read the result from the console if possible.

How do I access the package manager console programmatically in a visual studio extension?

For example I would like to send the following command to the package manager console.

add-migration migration01

Body:
The best way for running a script in package manager console is parameter passing into it.

EnvDTE.DTE _ObjDTE;
_ObjDTE = (DTE)System.Runtime.InteropServices.Marshal.GetActiveObject("VisualStudio.DTE");
var script = "function global:SaveAll {write-host \"All files saved.\"} SaveAll";
_ObjDTE.ExecuteCommand("View.PackageManagerConsole", script);


问:
In jupyter notebook the kernel dies immediately
I just started jupyter notebook and the the kernel just died, the errors were

```<code>   [I 18:14:40.316 NotebookApp] Serving notebooks from local directory: C:\Users\brick
[I 18:14:40.316 NotebookApp] 0 active kernels
[I 18:14:40.316 NotebookApp] The Jupyter Notebook is running at: http://localhost:8888/?token=da23fdd55f08aadd32334cf72b57034f19637b3016b93520
[I 18:14:40.316 NotebookApp] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation).
[C 18:14:40.332 NotebookApp]

    Copy/paste this URL into your browser when you connect for the first time,
    to login with a token:
        http://localhost:8888/?token=da23fdd55f08aadd32334cf72b57034f19637b3016b93520
[I 18:14:41.346 NotebookApp] Accepting one-time-token-authenticated connection from ::1
[I 18:14:50.920 NotebookApp] Creating new notebook in
[I 18:14:54.477 NotebookApp] Kernel started: c867db6f-d2a4-4ddb-9c25-d811e1f2d532
Could not import runpy module
Traceback (most recent call last):
  File "C:\Users\brick\Miniconda3\lib\runpy.py", line 14, in <module>
    import importlib.machinery # importlib first so we can test #15386 via -m
  File "C:\Users\brick\Miniconda3\lib\importlib\__init__.py", line 57, in <module>
    import types
  File "C:\Users\brick\Miniconda3\lib\types.py", line 171, in <module>
    import functools as _functools
  File "C:\Users\brick\Miniconda3\lib\functools.py", line 21, in <module>
    from collections import namedtuple
ImportError: bad magic number in 'collections': b'\x16\r\r\n'
[I 18:14:57.297 NotebookApp] KernelRestarter: restarting kernel (1/5)
Could not import runpy module
Traceback (most recent call last):
  File "C:\Users\brick\Miniconda3\lib\runpy.py", line 14, in <module>
    import importlib.machinery # importlib first so we can test #15386 via -m
  File "C:\Users\brick\Miniconda3\lib\importlib\__init__.py", line 57, in <module>
    import types
  File "C:\Users\brick\Miniconda3\lib\types.py", line 171, in <module>
    import functools as _functools
  File "C:\Users\brick\Miniconda3\lib\functools.py", line 21, in <module>
    from collections import namedtuple
ImportError: bad magic number in 'collections': b'\x16\r\r\n'
[I 18:15:00.340 NotebookApp] KernelRestarter: restarting kernel (2/5)
Could not import runpy module
Traceback (most recent call last):
  File "C:\Users\brick\Miniconda3\lib\runpy.py", line 14, in <module>
    import importlib.machinery # importlib first so we can test #15386 via -m
  File "C:\Users\brick\Miniconda3\lib\importlib\__init__.py", line 57, in <module>
    import types
  File "C:\Users\brick\Miniconda3\lib\types.py", line 171, in <module>
    import functools as _functools
  File "C:\Users\brick\Miniconda3\lib\functools.py", line 21, in <module>
    from collections import namedtuple
ImportError: bad magic number in 'collections': b'\x16\r\r\n'
[I 18:15:03.359 NotebookApp] KernelRestarter: restarting kernel (3/5)
Could not import runpy module
Traceback (most recent call last):
  File "C:\Users\brick\Miniconda3\lib\runpy.py", line 14, in <module>
    import importlib.machinery # importlib first so we can test #15386 via -m
  File "C:\Users\brick\Miniconda3\lib\importlib\__init__.py", line 57, in <module>
    import types
  File "C:\Users\brick\Miniconda3\lib\types.py", line 171, in <module>
    import functools as _functools
  File "C:\Users\brick\Miniconda3\lib\functools.py", line 21, in <module>
    from collections import namedtuple
ImportError: bad magic number in 'collections': b'\x16\r\r\n'
[W 18:15:04.589 NotebookApp] Timeout waiting for kernel_info reply from c867db6f-d2a4-4ddb-9c25-d811e1f2d532
[I 18:15:06.378 NotebookApp] KernelRestarter: restarting kernel (4/5)
WARNING:root:kernel c867db6f-d2a4-4ddb-9c25-d811e1f2d532 restarted
Could not import runpy module
Traceback (most recent call last):
  File "C:\Users\brick\Miniconda3\lib\runpy.py", line 14, in <module>
    import importlib.machinery # importlib first so we can test #15386 via -m
  File "C:\Users\brick\Miniconda3\lib\importlib\__init__.py", line 57, in <module>
    import types
  File "C:\Users\brick\Miniconda3\lib\types.py", line 171, in <module>
    import functools as _functools
  File "C:\Users\brick\Miniconda3\lib\functools.py", line 21, in <module>
    from collections import namedtuple
ImportError: bad magic number in 'collections': b'\x16\r\r\n'
[W 18:15:09.406 NotebookApp] KernelRestarter: restart failed
[W 18:15:09.406 NotebookApp] Kernel c867db6f-d2a4-4ddb-9c25-d811e1f2d532 died, removing from map.
ERROR:root:kernel c867db6f-d2a4-4ddb-9c25-d811e1f2d532 restarted failed!
[W 18:15:09.468 NotebookApp] Kernel deleted before session
[W 18:15:09.472 NotebookApp] 410 DELETE /api/sessions/4c861646-dd4c-45f9-9863-7ec1f4dec185 (::1) 7.99ms referer=http://localhost:8888/notebooks/Untitled4.ipynb?kernel_name=python3
[I 18:16:54.961 NotebookApp] Saving file at /Untitled4.ipynb
[I 21:29:10.617 NotebookApp] Kernel started: 64d63304-b152-4869-8cff-92612086b891
Could not import runpy module
Traceback (most recent call last):
  File "C:\Users\brick\Miniconda3\lib\runpy.py", line 14, in <module>
    import importlib.machinery # importlib first so we can test #15386 via -m
  File "C:\Users\brick\Miniconda3\lib\importlib\__init__.py", line 57, in <module>
    import types
  File "C:\Users\brick\Miniconda3\lib\types.py", line 171, in <module>
    import functools as _functools
  File "C:\Users\brick\Miniconda3\lib\functools.py", line 21, in <module>
    from collections import namedtuple
ImportError: bad magic number in 'collections': b'\x16\r\r\n'
[I 21:29:13.230 NotebookApp] KernelRestarter: restarting kernel (1/5)
Could not import runpy module
Traceback (most recent call last):
  File "C:\Users\brick\Miniconda3\lib\runpy.py", line 14, in <module>
    import importlib.machinery # importlib first so we can test #15386 via -m
  File "C:\Users\brick\Miniconda3\lib\importlib\__init__.py", line 57, in <module>
    import types
  File "C:\Users\brick\Miniconda3\lib\types.py", line 171, in <module>
    import functools as _functools
  File "C:\Users\brick\Miniconda3\lib\functools.py", line 21, in <module>
    from collections import namedtuple
ImportError: bad magic number in 'collections': b'\x16\r\r\n'
[I 21:29:16.263 NotebookApp] KernelRestarter: restarting kernel (2/5)
Could not import runpy module
Traceback (most recent call last):
  File "C:\Users\brick\Miniconda3\lib\runpy.py", line 14, in <module>
    import importlib.machinery # importlib first so we can test #15386 via -m
  File "C:\Users\brick\Miniconda3\lib\importlib\__init__.py", line 57, in <module>
    import types
  File "C:\Users\brick\Miniconda3\lib\types.py", line 171, in <module>
    import functools as _functools
  File "C:\Users\brick\Miniconda3\lib\functools.py", line 21, in <module>
    from collections import namedtuple
ImportError: bad magic number in 'collections': b'\x16\r\r\n'
[I 21:29:19.295 NotebookApp] KernelRestarter: restarting kernel (3/5)
Could not import runpy module
Traceback (most recent call last):
  File "C:\Users\brick\Miniconda3\lib\runpy.py", line 14, in <module>
    import importlib.machinery # importlib first so we can test #15386 via -m
  File "C:\Users\brick\Miniconda3\lib\importlib\__init__.py", line 57, in <module>
    import types
  File "C:\Users\brick\Miniconda3\lib\types.py", line 171, in <module>
    import functools as _functools
  File "C:\Users\brick\Miniconda3\lib\functools.py", line 21, in <module>
    from collections import namedtuple
ImportError: bad magic number in 'collections': b'\x16\r\r\n'
[W 21:29:21.159 NotebookApp] Timeout waiting for kernel_info reply from 64d63304-b152-4869-8cff-92612086b891
[I 21:29:22.312 NotebookApp] KernelRestarter: restarting kernel (4/5)
WARNING:root:kernel 64d63304-b152-4869-8cff-92612086b891 restarted
[E 21:29:22.317 NotebookApp] KernelRestarter: restart callback <bound method ZMQChannelsHandler.on_kernel_restarted of ZMQChannelsHandler(64d63304-b152-4869-8cff-92612086b891)> failed
    Traceback (most recent call last):
      File "C:\Users\brick\Miniconda3\lib\site-packages\jupyter_client\restarter.py", line 81, in _fire_callbacks
        callback()
      File "C:\Users\brick\Miniconda3\lib\site-packages\notebook\services\kernels\handlers.py", line 435, in on_kernel_restarted
        self._send_status_message('restarting')
      File "C:\Users\brick\Miniconda3\lib\site-packages\notebook\services\kernels\handlers.py", line 431, in _send_status_message
        self.write_message(json.dumps(msg, default=date_default))
      File "C:\Users\brick\Miniconda3\lib\site-packages\tornado\websocket.py", line 249, in write_message
        raise WebSocketClosedError()
    tornado.websocket.WebSocketClosedError
Could not import runpy module
Traceback (most recent call last):
  File "C:\Users\brick\Miniconda3\lib\runpy.py", line 14, in <module>
    import importlib.machinery # importlib first so we can test #15386 via -m
  File "C:\Users\brick\Miniconda3\lib\importlib\__init__.py", line 57, in <module>
    import types
  File "C:\Users\brick\Miniconda3\lib\types.py", line 171, in <module>
    import functools as _functools
  File "C:\Users\brick\Miniconda3\lib\functools.py", line 21, in <module>
    from collections import namedtuple
ImportError: bad magic number in 'collections': b'\x16\r\r\n'
[W 21:29:25.552 NotebookApp] KernelRestarter: restart failed
[W 21:29:25.552 NotebookApp] Kernel 64d63304-b152-4869-8cff-92612086b891 died, removing from map.
ERROR:root:kernel 64d63304-b152-4869-8cff-92612086b891 restarted failed!
[E 21:29:25.567 NotebookApp] KernelRestarter: dead callback <bound method ZMQChannelsHandler.on_restart_failed of ZMQChannelsHandler(64d63304-b152-4869-8cff-92612086b891)> failed
    Traceback (most recent call last):
      File "C:\Users\brick\Miniconda3\lib\site-packages\jupyter_client\restarter.py", line 81, in _fire_callbacks
        callback()
      File "C:\Users\brick\Miniconda3\lib\site-packages\notebook\services\kernels\handlers.py", line 439, in on_restart_failed
        self._send_status_message('dead')
      File "C:\Users\brick\Miniconda3\lib\site-packages\notebook\services\kernels\handlers.py", line 431, in _send_status_message
        self.write_message(json.dumps(msg, default=date_default))
      File "C:\Users\brick\Miniconda3\lib\site-packages\tornado\websocket.py", line 249, in write_message
        raise WebSocketClosedError()
    tornado.websocket.WebSocketClosedError
[I 23:11:45.347 NotebookApp] Interrupted...
[I 23:11:45.394 NotebookApp] Shutting down kernels
</code>```

I am using python 3.6.1, and used Miniconda3 to acquire jupyter notebook please help me the kernel also failed to restart.
Thanks!

I hope this will finally help me

答:
The "bad magic number" b'\x16\r\r\n' is used in .pyc files up to Python 3.5.2. Python broke the world when the magic number got updated to \x17 recently. This may be unrelated to your problem, but my guess is that your interpreter is >= 3.5.3 and your IPython kernel is <= 3.5.2, trying to use the same module-path.

The cause of this error are .pyc files, cached python modules "compiled" by a previous version of Python on your computer, that the interpreter IPython is now using can't unpickle.

The solution is to re-install everything, that is, getting a matching interpreter and IPython. You might get away with simply deleting all .pyc files; they are regenerated automatically.

Body:
I just started jupyter notebook and the the kernel just died, the errors were

   [I 18:14:40.316 NotebookApp] Serving notebooks from local directory: C:\Users\brick
[I 18:14:40.316 NotebookApp] 0 active kernels
[I 18:14:40.316 NotebookApp] The Jupyter Notebook is running at: http://localhost:8888/?token=da23fdd55f08aadd32334cf72b57034f19637b3016b93520
[I 18:14:40.316 NotebookApp] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation).
[C 18:14:40.332 NotebookApp]

    Copy/paste this URL into your browser when you connect for the first time,
    to login with a token:
        http://localhost:8888/?token=da23fdd55f08aadd32334cf72b57034f19637b3016b93520
[I 18:14:41.346 NotebookApp] Accepting one-time-token-authenticated connection from ::1
[I 18:14:50.920 NotebookApp] Creating new notebook in
[I 18:14:54.477 NotebookApp] Kernel started: c867db6f-d2a4-4ddb-9c25-d811e1f2d532
Could not import runpy module
Traceback (most recent call last):
  File "C:\Users\brick\Miniconda3\lib\runpy.py", line 14, in <module>
    import importlib.machinery # importlib first so we can test #15386 via -m
  File "C:\Users\brick\Miniconda3\lib\importlib\__init__.py", line 57, in <module>
    import types
  File "C:\Users\brick\Miniconda3\lib\types.py", line 171, in <module>
    import functools as _functools
  File "C:\Users\brick\Miniconda3\lib\functools.py", line 21, in <module>
    from collections import namedtuple
ImportError: bad magic number in 'collections': b'\x16\r\r\n'
[I 18:14:57.297 NotebookApp] KernelRestarter: restarting kernel (1/5)
Could not import runpy module
Traceback (most recent call last):
  File "C:\Users\brick\Miniconda3\lib\runpy.py", line 14, in <module>
    import importlib.machinery # importlib first so we can test #15386 via -m
  File "C:\Users\brick\Miniconda3\lib\importlib\__init__.py", line 57, in <module>
    import types
  File "C:\Users\brick\Miniconda3\lib\types.py", line 171, in <module>
    import functools as _functools
  File "C:\Users\brick\Miniconda3\lib\functools.py", line 21, in <module>
    from collections import namedtuple
ImportError: bad magic number in 'collections': b'\x16\r\r\n'
[I 18:15:00.340 NotebookApp] KernelRestarter: restarting kernel (2/5)
Could not import runpy module
Traceback (most recent call last):
  File "C:\Users\brick\Miniconda3\lib\runpy.py", line 14, in <module>
    import importlib.machinery # importlib first so we can test #15386 via -m
  File "C:\Users\brick\Miniconda3\lib\importlib\__init__.py", line 57, in <module>
    import types
  File "C:\Users\brick\Miniconda3\lib\types.py", line 171, in <module>
    import functools as _functools
  File "C:\Users\brick\Miniconda3\lib\functools.py", line 21, in <module>
    from collections import namedtuple
ImportError: bad magic number in 'collections': b'\x16\r\r\n'
[I 18:15:03.359 NotebookApp] KernelRestarter: restarting kernel (3/5)
Could not import runpy module
Traceback (most recent call last):
  File "C:\Users\brick\Miniconda3\lib\runpy.py", line 14, in <module>
    import importlib.machinery # importlib first so we can test #15386 via -m
  File "C:\Users\brick\Miniconda3\lib\importlib\__init__.py", line 57, in <module>
    import types
  File "C:\Users\brick\Miniconda3\lib\types.py", line 171, in <module>
    import functools as _functools
  File "C:\Users\brick\Miniconda3\lib\functools.py", line 21, in <module>
    from collections import namedtuple
ImportError: bad magic number in 'collections': b'\x16\r\r\n'
[W 18:15:04.589 NotebookApp] Timeout waiting for kernel_info reply from c867db6f-d2a4-4ddb-9c25-d811e1f2d532
[I 18:15:06.378 NotebookApp] KernelRestarter: restarting kernel (4/5)
WARNING:root:kernel c867db6f-d2a4-4ddb-9c25-d811e1f2d532 restarted
Could not import runpy module
Traceback (most recent call last):
  File "C:\Users\brick\Miniconda3\lib\runpy.py", line 14, in <module>
    import importlib.machinery # importlib first so we can test #15386 via -m
  File "C:\Users\brick\Miniconda3\lib\importlib\__init__.py", line 57, in <module>
    import types
  File "C:\Users\brick\Miniconda3\lib\types.py", line 171, in <module>
    import functools as _functools
  File "C:\Users\brick\Miniconda3\lib\functools.py", line 21, in <module>
    from collections import namedtuple
ImportError: bad magic number in 'collections': b'\x16\r\r\n'
[W 18:15:09.406 NotebookApp] KernelRestarter: restart failed
[W 18:15:09.406 NotebookApp] Kernel c867db6f-d2a4-4ddb-9c25-d811e1f2d532 died, removing from map.
ERROR:root:kernel c867db6f-d2a4-4ddb-9c25-d811e1f2d532 restarted failed!
[W 18:15:09.468 NotebookApp] Kernel deleted before session
[W 18:15:09.472 NotebookApp] 410 DELETE /api/sessions/4c861646-dd4c-45f9-9863-7ec1f4dec185 (::1) 7.99ms referer=http://localhost:8888/notebooks/Untitled4.ipynb?kernel_name=python3
[I 18:16:54.961 NotebookApp] Saving file at /Untitled4.ipynb
[I 21:29:10.617 NotebookApp] Kernel started: 64d63304-b152-4869-8cff-92612086b891
Could not import runpy module
Traceback (most recent call last):
  File "C:\Users\brick\Miniconda3\lib\runpy.py", line 14, in <module>
    import importlib.machinery # importlib first so we can test #15386 via -m
  File "C:\Users\brick\Miniconda3\lib\importlib\__init__.py", line 57, in <module>
    import types
  File "C:\Users\brick\Miniconda3\lib\types.py", line 171, in <module>
    import functools as _functools
  File "C:\Users\brick\Miniconda3\lib\functools.py", line 21, in <module>
    from collections import namedtuple
ImportError: bad magic number in 'collections': b'\x16\r\r\n'
[I 21:29:13.230 NotebookApp] KernelRestarter: restarting kernel (1/5)
Could not import runpy module
Traceback (most recent call last):
  File "C:\Users\brick\Miniconda3\lib\runpy.py", line 14, in <module>
    import importlib.machinery # importlib first so we can test #15386 via -m
  File "C:\Users\brick\Miniconda3\lib\importlib\__init__.py", line 57, in <module>
    import types
  File "C:\Users\brick\Miniconda3\lib\types.py", line 171, in <module>
    import functools as _functools
  File "C:\Users\brick\Miniconda3\lib\functools.py", line 21, in <module>
    from collections import namedtuple
ImportError: bad magic number in 'collections': b'\x16\r\r\n'
[I 21:29:16.263 NotebookApp] KernelRestarter: restarting kernel (2/5)
Could not import runpy module
Traceback (most recent call last):
  File "C:\Users\brick\Miniconda3\lib\runpy.py", line 14, in <module>
    import importlib.machinery # importlib first so we can test #15386 via -m
  File "C:\Users\brick\Miniconda3\lib\importlib\__init__.py", line 57, in <module>
    import types
  File "C:\Users\brick\Miniconda3\lib\types.py", line 171, in <module>
    import functools as _functools
  File "C:\Users\brick\Miniconda3\lib\functools.py", line 21, in <module>
    from collections import namedtuple
ImportError: bad magic number in 'collections': b'\x16\r\r\n'
[I 21:29:19.295 NotebookApp] KernelRestarter: restarting kernel (3/5)
Could not import runpy module
Traceback (most recent call last):
  File "C:\Users\brick\Miniconda3\lib\runpy.py", line 14, in <module>
    import importlib.machinery # importlib first so we can test #15386 via -m
  File "C:\Users\brick\Miniconda3\lib\importlib\__init__.py", line 57, in <module>
    import types
  File "C:\Users\brick\Miniconda3\lib\types.py", line 171, in <module>
    import functools as _functools
  File "C:\Users\brick\Miniconda3\lib\functools.py", line 21, in <module>
    from collections import namedtuple
ImportError: bad magic number in 'collections': b'\x16\r\r\n'
[W 21:29:21.159 NotebookApp] Timeout waiting for kernel_info reply from 64d63304-b152-4869-8cff-92612086b891
[I 21:29:22.312 NotebookApp] KernelRestarter: restarting kernel (4/5)
WARNING:root:kernel 64d63304-b152-4869-8cff-92612086b891 restarted
[E 21:29:22.317 NotebookApp] KernelRestarter: restart callback <bound method ZMQChannelsHandler.on_kernel_restarted of ZMQChannelsHandler(64d63304-b152-4869-8cff-92612086b891)> failed
    Traceback (most recent call last):
      File "C:\Users\brick\Miniconda3\lib\site-packages\jupyter_client\restarter.py", line 81, in _fire_callbacks
        callback()
      File "C:\Users\brick\Miniconda3\lib\site-packages\notebook\services\kernels\handlers.py", line 435, in on_kernel_restarted
        self._send_status_message('restarting')
      File "C:\Users\brick\Miniconda3\lib\site-packages\notebook\services\kernels\handlers.py", line 431, in _send_status_message
        self.write_message(json.dumps(msg, default=date_default))
      File "C:\Users\brick\Miniconda3\lib\site-packages\tornado\websocket.py", line 249, in write_message
        raise WebSocketClosedError()
    tornado.websocket.WebSocketClosedError
Could not import runpy module
Traceback (most recent call last):
  File "C:\Users\brick\Miniconda3\lib\runpy.py", line 14, in <module>
    import importlib.machinery # importlib first so we can test #15386 via -m
  File "C:\Users\brick\Miniconda3\lib\importlib\__init__.py", line 57, in <module>
    import types
  File "C:\Users\brick\Miniconda3\lib\types.py", line 171, in <module>
    import functools as _functools
  File "C:\Users\brick\Miniconda3\lib\functools.py", line 21, in <module>
    from collections import namedtuple
ImportError: bad magic number in 'collections': b'\x16\r\r\n'
[W 21:29:25.552 NotebookApp] KernelRestarter: restart failed
[W 21:29:25.552 NotebookApp] Kernel 64d63304-b152-4869-8cff-92612086b891 died, removing from map.
ERROR:root:kernel 64d63304-b152-4869-8cff-92612086b891 restarted failed!
[E 21:29:25.567 NotebookApp] KernelRestarter: dead callback <bound method ZMQChannelsHandler.on_restart_failed of ZMQChannelsHandler(64d63304-b152-4869-8cff-92612086b891)> failed
    Traceback (most recent call last):
      File "C:\Users\brick\Miniconda3\lib\site-packages\jupyter_client\restarter.py", line 81, in _fire_callbacks
        callback()
      File "C:\Users\brick\Miniconda3\lib\site-packages\notebook\services\kernels\handlers.py", line 439, in on_restart_failed
        self._send_status_message('dead')
      File "C:\Users\brick\Miniconda3\lib\site-packages\notebook\services\kernels\handlers.py", line 431, in _send_status_message
        self.write_message(json.dumps(msg, default=date_default))
      File "C:\Users\brick\Miniconda3\lib\site-packages\tornado\websocket.py", line 249, in write_message
        raise WebSocketClosedError()
    tornado.websocket.WebSocketClosedError
[I 23:11:45.347 NotebookApp] Interrupted...
[I 23:11:45.394 NotebookApp] Shutting down kernels

I am using python 3.6.1, and used Miniconda3 to acquire jupyter notebook please help me the kernel also failed to restart.
Thanks!

I hope this will finally help me


问:
php: file_get_contents not working into if-statement
I have this code:

```<code>//A
if(condition1)
   {
   //B
   if(condition2)
      {
      //C
      }
   }
</code>```

and a file_get_contents($url). I want this file_get_contents to run in "//C", but I notice this: in A works properly, but the same instruction, if put in "//B" or "//C", doesn't work, and "condition1" and "condition2" are both verified (when putting other instrution in B or C they work). I also tried this try/catch statement but without success:

```<code>try {
$content = file_get_contents($url);

if ($content === false) {
    // THIS is always verified
}
} catch (Exception $e) {
// NEVER RUNS
}
</code>```

What can I do?

答:
It never goes into catch because there is no RUNTIME ERROR to report, function ran succesfully without a crash.

```<code>try {
$content = file_get_contents($url);

    if ($content === false) {
       AREA 1
    }else{
       AREA 2
    }

} catch (Exception $e) {
   AREA 3
}
</code>```

If file is read succesfully -> AREA2

If FOR ANY REASON file couldnt be read (permissions, file not found,  anything) -> AREA1

If a RUNTIME ERROR occurs during file_get_contents execution -> AREA 3

Body:
I have this code:

//A
if(condition1)
   {
   //B
   if(condition2)
      {
      //C
      }
   }

and a file_get_contents($url). I want this file_get_contents to run in "//C", but I notice this: in A works properly, but the same instruction, if put in "//B" or "//C", doesn't work, and "condition1" and "condition2" are both verified (when putting other instrution in B or C they work). I also tried this try/catch statement but without success:

try {
$content = file_get_contents($url);

if ($content === false) {
    // THIS is always verified
}
} catch (Exception $e) {
// NEVER RUNS
}

What can I do?

Body:
It never goes into catch because there is no RUNTIME ERROR to report, function ran succesfully without a crash.

try {
$content = file_get_contents($url);

    if ($content === false) {
       AREA 1
    }else{
       AREA 2
    }

} catch (Exception $e) {
   AREA 3
}

If file is read succesfully -> AREA2

If FOR ANY REASON file couldnt be read (permissions, file not found,  anything) -> AREA1

If a RUNTIME ERROR occurs during file_get_contents execution -> AREA 3


问:
Laravel 5 - NGINX Server Config Issue with URL Query Strings
Laravel is not receiving any $_GET variables from the URL query string.  The $_GET and Input::all() are empty.

Example:

example.app/ex/login.php?country=US

The "country=US" never shows up in my $_GET variable

After much research and trying many different NGINX configurations, I can now only produce results when this example is used.

Example:

example.app/index.php/ex/login.php?country=US

The $_GET variable now shows the country name value pair.

What is the proper configuration to allow query strings within the URL?

My current sites-enabled configuration for my "example.app" is...

```<code>server {
listen 80;
server_name example.app;
root /home/vagrant/Code/public;

index index.html index.htm index.php;

charset utf-8;

location / {
   #try_files $uri $uri/ /index.php?$query_string;
}

location = /favicon.ico { access_log off; log_not_found off; }
location = /robots.txt  { access_log off; log_not_found off; }

access_log off;
error_log  /var/log/nginx/registration.app-error.log error;

error_page 404 /index.php;

sendfile off;

location ~ \.php$ {
    fastcgi_split_path_info ^(.+\.php)(/.+)$;
    fastcgi_pass unix:/var/run/php5-fpm.sock;
    fastcgi_index index.php;
    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_intercept_errors on;
    fastcgi_buffer_size 16k;
    fastcgi_buffers 4 16k;
}

location ~ /\.ht {
    deny all;
}
</code>```

}

答:
For me it worked only by changing
            try_files $uri $uri/ /index.php?$query_string; to
try_files $uri $uri/ /index.php?$args inside location / block on ubuntu (14.04) nginx

Body:
Laravel is not receiving any $_GET variables from the URL query string.  The $_GET and Input::all() are empty.

Example:

example.app/ex/login.php?country=US

The "country=US" never shows up in my $_GET variable

After much research and trying many different NGINX configurations, I can now only produce results when this example is used.

Example:

example.app/index.php/ex/login.php?country=US

The $_GET variable now shows the country name value pair.

What is the proper configuration to allow query strings within the URL?

My current sites-enabled configuration for my "example.app" is...

server {
listen 80;
server_name example.app;
root /home/vagrant/Code/public;

index index.html index.htm index.php;

charset utf-8;

location / {
   #try_files $uri $uri/ /index.php?$query_string;
}

location = /favicon.ico { access_log off; log_not_found off; }
location = /robots.txt  { access_log off; log_not_found off; }

access_log off;
error_log  /var/log/nginx/registration.app-error.log error;

error_page 404 /index.php;

sendfile off;

location ~ \.php$ {
    fastcgi_split_path_info ^(.+\.php)(/.+)$;
    fastcgi_pass unix:/var/run/php5-fpm.sock;
    fastcgi_index index.php;
    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_intercept_errors on;
    fastcgi_buffer_size 16k;
    fastcgi_buffers 4 16k;
}

location ~ /\.ht {
    deny all;
}

}


问:
Failed query in mysql Database
Good afternoon,
I dont get to see any error in my code and i have been getting Mysql Errors along the line.

My code looks like this

```<code><?php
include 'account_numgen.php';
require_once('inc/config.php');

$con = mysqli_connect($host,$user,$pass, $db)or die ('Cannot Connect :'.mysqli_error());

$account_number = mysqli_real_escape_string($con,$_POST['account_number']);
$first_name = mysqli_real_escape_string($con,$_POST['first_name']);
$mi = mysqli_real_escape_string($con,$_POST['mi']);
$last_name = mysqli_real_escape_string($con,$_POST['last_name']);
$address = mysqli_real_escape_string($con,$_POST['address']);
$address2 = mysqli_real_escape_string($con,$_POST['address2']);
$city = mysqli_real_escape_string($con,$_POST['city']);
$tel = mysqli_real_escape_string($con,$_POST['tel']);
$email = mysqli_real_escape_string($con,$_POST['email']);
$nok_1 = mysqli_real_escape_string($con,$_POST['nok_1']);
$nok1_address = mysqli_real_escape_string($con,$_POST['nok1_address']);
$nok1_address2 = mysqli_real_escape_string($con,$_POST['nok1_address2']);
$nok1_city = mysqli_real_escape_string($con,$_POST['nok1_city']);
$nok_2 = mysqli_real_escape_string($con,$_POST['nok_2']);
$nok2_address = mysqli_real_escape_string($con,$_POST['nok2_address']);
$nok2_address2 = mysqli_real_escape_string($con,$_POST['nok2_address2']);
$nok2_city = mysqli_real_escape_string($con,$_POST['nok2_city']);
$id_type = mysqli_real_escape_string($con,$_POST['id_type']);
$id_number = mysqli_real_escape_string($con,$_POST['id_number']);
$open_bal = mysqli_real_escape_string($con,$_POST['open_bal']);
$passport_name = $_FILES['passport']['name'];
$passport_size = $_FILES['passport']['size'];
$passport_type = $_FILES['passport']['type'];
$passporttmp_name = $_FILES['passport']['tmp_name'];

$signature_name = $_FILES['signature']['name'];
$signature_size = $_FILES['signature']['size'];
$signature_type = $_FILES['signature']['type'];
$signaturetmp_name = $_FILES['signature']['tmp_name'];

$sql = "insert into bank_details(account_number,first_name,mi,last_name,address,address2,city,tel,email,nok_1,nok1_address,nok1_address2,nok1_city,nok_2,nok2_address,nok2_address2,nok2_city,id_type,id_number,open_bal,passport_name,passport_size,passport_type,passporttmp_name,signature_name,signature_size,signature_type,signaturetmp_name) values ('".$account_number."','".$first_name."','".$mi."','".$last_name."','".$address."','".$address2."','".$city."','".$tel."','".$email."','".$nok_1."','".$nok1_address."','".$nok1_address2."','".$nok1_city."','".$nok_2."','".$nok2_address."','".$nok2_address2."','".$nok2_city."','".$id_type."','".$id_number."','".$open_bal."','".$passport_name."','".$passport_size."','".$passport_type."','".$passporttmp_name."','".$signature_name."','".$signature_size."','".$signature_type."','".$signaturetmp_name."')";
mysqli_query($con,$sql) or die ('Failed Query: '.mysqli_error($con));

$passport_dir = 'passport/';
$signature_dir = 'signature/';

$filePath1 = $passport_dir . $passport_name;
$filePath2 = $signature_dir . $signature_name;

$result1 = move_uploaded_file($passporttmp_name,$filePath1);
$result2 = move_uploaded_file($signaturetmp_name,$filePath2);

echo ('
<SCRIPT LANGUAGE="JavaScript">
   window.alert("Account Information \n Account Number: '.$account_number.'\n First Name: '.$first_name.'\n Last Name: '.$last_name.'\n Last Name: '.$open_bal.'")
   window.location.href="index.html";
</SCRIPT>
');

?>
</code>```

Now i get this Error

```<code>Failed Query: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 's_Signature.png','78716','image/png','C:\xampp\tmp\phpD784.tmp')' at line 1
</code>```

Why is this so? i dont get to see any errors in My code, How ever it has stopped posting to the database on My Local host.

Edit

When i add mysqli_real_escape_string($con, $_FILES[....]) it works fine, but it doesnt send the images from the application to the localhost server what exactly can be the case?

答:
Use mysqli_real_escape_string on '$signature_name ' - it has an apostrophe in it.

```<code>$signature_name = mysqli_real_escape_string($con,$_FILES['signature']['name']);
</code>```

Title: Failed query in mysql Database

Body:
Good afternoon,
I dont get to see any error in my code and i have been getting Mysql Errors along the line.

My code looks like this

<?php
include 'account_numgen.php';
require_once('inc/config.php');

$con = mysqli_connect($host,$user,$pass, $db)or die ('Cannot Connect :'.mysqli_error());

$account_number = mysqli_real_escape_string($con,$_POST['account_number']);
$first_name = mysqli_real_escape_string($con,$_POST['first_name']);
$mi = mysqli_real_escape_string($con,$_POST['mi']);
$last_name = mysqli_real_escape_string($con,$_POST['last_name']);
$address = mysqli_real_escape_string($con,$_POST['address']);
$address2 = mysqli_real_escape_string($con,$_POST['address2']);
$city = mysqli_real_escape_string($con,$_POST['city']);
$tel = mysqli_real_escape_string($con,$_POST['tel']);
$email = mysqli_real_escape_string($con,$_POST['email']);
$nok_1 = mysqli_real_escape_string($con,$_POST['nok_1']);
$nok1_address = mysqli_real_escape_string($con,$_POST['nok1_address']);
$nok1_address2 = mysqli_real_escape_string($con,$_POST['nok1_address2']);
$nok1_city = mysqli_real_escape_string($con,$_POST['nok1_city']);
$nok_2 = mysqli_real_escape_string($con,$_POST['nok_2']);
$nok2_address = mysqli_real_escape_string($con,$_POST['nok2_address']);
$nok2_address2 = mysqli_real_escape_string($con,$_POST['nok2_address2']);
$nok2_city = mysqli_real_escape_string($con,$_POST['nok2_city']);
$id_type = mysqli_real_escape_string($con,$_POST['id_type']);
$id_number = mysqli_real_escape_string($con,$_POST['id_number']);
$open_bal = mysqli_real_escape_string($con,$_POST['open_bal']);
$passport_name = $_FILES['passport']['name'];
$passport_size = $_FILES['passport']['size'];
$passport_type = $_FILES['passport']['type'];
$passporttmp_name = $_FILES['passport']['tmp_name'];

$signature_name = $_FILES['signature']['name'];
$signature_size = $_FILES['signature']['size'];
$signature_type = $_FILES['signature']['type'];
$signaturetmp_name = $_FILES['signature']['tmp_name'];

$sql = "insert into bank_details(account_number,first_name,mi,last_name,address,address2,city,tel,email,nok_1,nok1_address,nok1_address2,nok1_city,nok_2,nok2_address,nok2_address2,nok2_city,id_type,id_number,open_bal,passport_name,passport_size,passport_type,passporttmp_name,signature_name,signature_size,signature_type,signaturetmp_name) values ('".$account_number."','".$first_name."','".$mi."','".$last_name."','".$address."','".$address2."','".$city."','".$tel."','".$email."','".$nok_1."','".$nok1_address."','".$nok1_address2."','".$nok1_city."','".$nok_2."','".$nok2_address."','".$nok2_address2."','".$nok2_city."','".$id_type."','".$id_number."','".$open_bal."','".$passport_name."','".$passport_size."','".$passport_type."','".$passporttmp_name."','".$signature_name."','".$signature_size."','".$signature_type."','".$signaturetmp_name."')";
mysqli_query($con,$sql) or die ('Failed Query: '.mysqli_error($con));

$passport_dir = 'passport/';
$signature_dir = 'signature/';

$filePath1 = $passport_dir . $passport_name;
$filePath2 = $signature_dir . $signature_name;

$result1 = move_uploaded_file($passporttmp_name,$filePath1);
$result2 = move_uploaded_file($signaturetmp_name,$filePath2);

echo ('

');

?>

Now i get this Error

Failed Query: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 's_Signature.png','78716','image/png','C:\xampp\tmp\phpD784.tmp')' at line 1

Why is this so? i dont get to see any errors in My code, How ever it has stopped posting to the database on My Local host.

Edit

When i add mysqli_real_escape_string($con, $_FILES[....]) it works fine, but it doesnt send the images from the application to the localhost server what exactly can be the case?

Body:
Use mysqli_real_escape_string on '$signature_name ' - it has an apostrophe in it.

$signature_name = mysqli_real_escape_string($con,$_FILES['signature']['name']);


问:
Transforming xml to xml using xslt encoded hierarchy problem xslt v1
In my input xml file I have got encoded hierarchy in elements attribute "lp":

```<code><element lp="1"/>
<element lp="1.1"/>
<element lp="2"/>
<element lp="3"/>
<element lp="3.1" />
<element lp="3.2" />
<element lp="3.2.1" />
</code>```

How to transform this xml data to

```<code><element lp="1">
   <element lp="1.1"/>
</element>
<element lp="2"/>
<element lp="3">
   <element lp="3.1"/>
   <element lp="3.2">
      <element lp="3.2.1">
   </element>
</element>
</code>```

答:
I think this was answer before... This stylesheet:

```<code><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="root">
        <result>
            <xsl:apply-templates select="element[not(contains(@lp,'.'))]"/>
        </result>
    </xsl:template>
    <xsl:template match="element">
    <xsl:variable name="vLevel" select="concat(@lp,'.')"/>
        <xsl:copy>
            <xsl:copy-of select="@*"/>
            <xsl:apply-templates
                 select="../element[starts-with(@lp,$vLevel)]
                                   [not(contains(substring-after(@lp,$vLevel),
                                                 '.'))]"/>
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>
</code>```

Output:

```<code><result>
    <element lp="1">
        <element lp="1.1"></element>
    </element>
    <element lp="2"></element>
    <element lp="3">
        <element lp="3.1"></element>
        <element lp="3.2">
            <element lp="3.2.1"></element>
        </element>
    </element>
</result>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
In my input xml file I have got encoded hierarchy in elements attribute "lp":

<element lp="1"/>
<element lp="1.1"/>
<element lp="2"/>
<element lp="3"/>
<element lp="3.1" />
<element lp="3.2" />
<element lp="3.2.1" />

How to transform this xml data to

<element lp="1">
   <element lp="1.1"/>
</element>
<element lp="2"/>
<element lp="3">
   <element lp="3.1"/>
   <element lp="3.2">
      <element lp="3.2.1">
   </element>
</element>

Body:
I think this was answer before... This stylesheet:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="root">
        <result>
            <xsl:apply-templates select="element[not(contains(@lp,'.'))]"/>
        </result>
    </xsl:template>
    <xsl:template match="element">
    <xsl:variable name="vLevel" select="concat(@lp,'.')"/>
        <xsl:copy>
            <xsl:copy-of select="@*"/>
            <xsl:apply-templates
                 select="../element[starts-with(@lp,$vLevel)]
                                   [not(contains(substring-after(@lp,$vLevel),
                                                 '.'))]"/>
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>

Output:

<result>
    <element lp="1">
        <element lp="1.1"></element>
    </element>
    <element lp="2"></element>
    <element lp="3">
        <element lp="3.1"></element>
        <element lp="3.2">
            <element lp="3.2.1"></element>
        </element>
    </element>
</result>


问:
Dictionary without generics
I'm learning C# and I have an exercise with these three classes:

```<code>public abstract BaseClass<T> Where T : BaseClass<T>

public class Class1

public class Class2 : BaseClass<Class2>
</code>```

On the exercise there is this:

```<code>var dictionary = new Dictionary { [class1] = class1, [class2] = class2 };
</code>```

I think that here, Dictionary is a shortcut for Dictionary<object, object>
; so I have added this class to the project:

```<code>public class Dictionary : Dictionary<object, object>
</code>```

My problem here is that I'm not sure if I have declared correctly Dictionary. Now the exercise works perfectly but maybe there is another option to declare Dictionary. By the way, I have used dynamic instead of object and it also works.

My question is:

In the exercise, is Dictionary a custom class or is another class from .NET Framework or whatever that I don't know?

答:
The line

```<code>var dictionary = new Dictionary { [class1] = class1, [class2] = class2 };
</code>```

uses an object initializer to initialize the indexer of the Dictionary class. This syntax is supported from C# Version 6 (see C# 6.0 Language Specification under section §7.6.11.2 Object initializers).

As you correctly found out, one way to get a class that allows such an behavoir is to derive a class from Dictionary<T,K>. Another way is to write a Dictionary class that uses an indexer. The simplest class that exhibits such a behavior is:

```<code>public class Dictionary
{
    public object this[object index] {
        get {return null;}
        set {}
    }
}

static void Main()
{
    Class1 class1 = new Class1();
    Class2 class2 = new Class2();
    var dictionary = new Dictionary
    {
        [class1] = class1,
        [class2] = class2
    };
}
</code>```

Which does not do anything, obviously, but it shows where the initialization syntax comes from.

Title: Dictionary without generics

Body:
I'm learning C# and I have an exercise with these three classes:

public abstract BaseClass<T> Where T : BaseClass<T>

public class Class1

public class Class2 : BaseClass<Class2>

On the exercise there is this:

var dictionary = new Dictionary { [class1] = class1, [class2] = class2 };

I think that here, Dictionary is a shortcut for Dictionary<object, object>
; so I have added this class to the project:

public class Dictionary : Dictionary<object, object>

My problem here is that I'm not sure if I have declared correctly Dictionary. Now the exercise works perfectly but maybe there is another option to declare Dictionary. By the way, I have used dynamic instead of object and it also works.

My question is:

In the exercise, is Dictionary a custom class or is another class from .NET Framework or whatever that I don't know?

Body:
The line

var dictionary = new Dictionary { [class1] = class1, [class2] = class2 };

uses an object initializer to initialize the indexer of the Dictionary class. This syntax is supported from C# Version 6 (see C# 6.0 Language Specification under section §7.6.11.2 Object initializers).

As you correctly found out, one way to get a class that allows such an behavoir is to derive a class from Dictionary<T,K>. Another way is to write a Dictionary class that uses an indexer. The simplest class that exhibits such a behavior is:

public class Dictionary
{
    public object this[object index] {
        get {return null;}
        set {}
    }
}

static void Main()
{
    Class1 class1 = new Class1();
    Class2 class2 = new Class2();
    var dictionary = new Dictionary
    {
        [class1] = class1,
        [class2] = class2
    };
}

Which does not do anything, obviously, but it shows where the initialization syntax comes from.