问:
How to use Clojure's PersistentQueue?
In https://stackoverflow.com/a/2495105/261952 somebody claims it works like this:

```<code>(-> (clojure.lang.PersistentQueue/EMPTY)
      (conj 1 2 3)
      pop)
(2 3)
</code>```

However when I try this in my REPL, I get this result:

```<code>=> #object[clojure.lang.PersistentQueue 0x11f5966 "clojure.lang.PersistentQueue@402"]
</code>```

Since that post is 7 years old, behaviour may have changed.
How cat I get it working today (Clojure 1.8)?

答:
It still works. Add seq to the threading to see what there is:

```<code>(-> (clojure.lang.PersistentQueue/EMPTY)
    (conj 1 2 3)
    pop
    seq)
;(2 3)
</code>```

Title: How to use Clojure's PersistentQueue?

Body:
In https://stackoverflow.com/a/2495105/261952 somebody claims it works like this:

(-> (clojure.lang.PersistentQueue/EMPTY)
      (conj 1 2 3)
      pop)
(2 3)

However when I try this in my REPL, I get this result:

=> #object[clojure.lang.PersistentQueue 0x11f5966 "clojure.lang.PersistentQueue@402"]

Since that post is 7 years old, behaviour may have changed.
How cat I get it working today (Clojure 1.8)?

Body:
It still works. Add seq to the threading to see what there is:

(-> (clojure.lang.PersistentQueue/EMPTY)
    (conj 1 2 3)
    pop
    seq)
;(2 3)


来源: stackexchange

问:
Get Information from one page to another with angular routing
Image a page, that page is called "dashboard". In the dashboard, there is a drop-down menu, with items, which are listed by the PHP script, and their count varies on the number of results from a database.

Now, when a user clicks one of the items from the menu, it should redirect him to the configuration page, with some data (id, type). Sounds simple, but the redirecting method used is made with angular, so it uses URL hashing, without refreshing the site. URL of configuration page then looks like:

https://www.example.com/index.php#/configure

...and I want to get there some data. The site we see there is just a blank site, which, in the file tree, is named "configuration.php", but you don't see it in the URL, because of angular code in "configure.module.js.php", which simply redirects the user, gives them the right site with:

```<code>(function () {
  'use strict';

  angular.module('BlurAdmin.pages.configure', [])
      .config(routeConfig);

  /** @ngInject */
  function routeConfig($stateProvider) {
    $stateProvider
        .state('configure', {
          url: '/configure',
          title: 'Configuration',
          templateUrl: 'app/pages/configure/configure.php',
          controller: 'addCtrl',
        });
  }

})();
</code>```

So I assume, that if I want to get the data to my site, I need some kind of a GET request. I figured out, that it will work if I use the GET request like so:

```<code>https://www.example.com/index.php?something=works&omg=itWorks#/configure
</code>```

So my index.php will work with the GET data and write them to a SESSION, which can then be used in configuration.php!

Well, it works, kinda... But the main thing is, that it is all angular, so NO SITE REFRESH AT ALL! That means none of my files will be refreshed, so after I click the button again, the site will not get the GET request again, it will simply redirect me to configuration.php, without dealing with the new data... It will keep the first GET parameters and SESSION.

So there goes my question. how to make it? I really need that one click to send that data to configuration.php, without refreshing the site, but, working and updating.

答:
In html you add ui-sref to like this

```<code>ui-sref="configure/({id: valueid})
</code>```

in file config

```<code>url:'/configure/:id'
</code>```

in your controller add $stateParams like this

```<code> function addCtrl($scope,$http,$stateParams)
</code>```

and use ajax to GET

```<code>   var params = $.param({'id':$stateParams.id})

        $http({
                    method:'GET',
                    url:'yoururl?id=' + $stateParams.id,
                    data:params,
                    headers : { 'Content-Type': 'application/x-www-form-urlencoded' }

                }).then(onSuccess);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Image a page, that page is called "dashboard". In the dashboard, there is a drop-down menu, with items, which are listed by the PHP script, and their count varies on the number of results from a database.

Now, when a user clicks one of the items from the menu, it should redirect him to the configuration page, with some data (id, type). Sounds simple, but the redirecting method used is made with angular, so it uses URL hashing, without refreshing the site. URL of configuration page then looks like:

https://www.example.com/index.php#/configure

...and I want to get there some data. The site we see there is just a blank site, which, in the file tree, is named "configuration.php", but you don't see it in the URL, because of angular code in "configure.module.js.php", which simply redirects the user, gives them the right site with:

(function () {
  'use strict';

  angular.module('BlurAdmin.pages.configure', [])
      .config(routeConfig);

  /** @ngInject */
  function routeConfig($stateProvider) {
    $stateProvider
        .state('configure', {
          url: '/configure',
          title: 'Configuration',
          templateUrl: 'app/pages/configure/configure.php',
          controller: 'addCtrl',
        });
  }

})();

So I assume, that if I want to get the data to my site, I need some kind of a GET request. I figured out, that it will work if I use the GET request like so:

https://www.example.com/index.php?something=works&omg=itWorks#/configure

So my index.php will work with the GET data and write them to a SESSION, which can then be used in configuration.php!

Well, it works, kinda... But the main thing is, that it is all angular, so NO SITE REFRESH AT ALL! That means none of my files will be refreshed, so after I click the button again, the site will not get the GET request again, it will simply redirect me to configuration.php, without dealing with the new data... It will keep the first GET parameters and SESSION.

So there goes my question. how to make it? I really need that one click to send that data to configuration.php, without refreshing the site, but, working and updating.

Body:
In html you add ui-sref to like this

ui-sref="configure/({id: valueid})

in file config

url:'/configure/:id'

in your controller add $stateParams like this

 function addCtrl($scope,$http,$stateParams)

and use ajax to GET

   var params = $.param({'id':$stateParams.id})

        $http({
                    method:'GET',
                    url:'yoururl?id=' + $stateParams.id,
                    data:params,
                    headers : { 'Content-Type': 'application/x-www-form-urlencoded' }

                }).then(onSuccess);


问:
SQL JOIN COUNT then using that count value in where clause
I'm trying to select if a user rating (user.rating) is greater then 6 or if the user has more then 100 transactions (transaction table count). Basically count how many transactions the user has then where (transaction count >= 100 OR user rating >= 6).</p>

```<code>SELECT *
FROM   `user`
JOIN   (SELECT COUNT(*)
        FROM   transaction
        WHERE  transaction.user_id=user.id
        AND type='L'
        AND status='S') AS tcount
WHERE  (user.rating >= '6' OR tcount >= '100')
</code>```

答:
You can write that without the subquery, like this</p>

```<code>SELECT  u.id
FROM `user` u
JOIN `transaction` t
ON t.user_id=u.id
WHERE t.type = 'L' AND t.status = 'S'
GROUP BY u.id
HAVING sum(case when u.rating >= 6 then 1 end) > 0 OR count(*) >= 100
</code>```

Body:
I'm trying to select if a user rating (user.rating) is greater then 6 or if the user has more then 100 transactions (transaction table count). Basically count how many transactions the user has then where (transaction count >= 100 OR user rating >= 6).

SELECT *
FROM   `user`
JOIN   (SELECT COUNT(*)
        FROM   transaction
        WHERE  transaction.user_id=user.id
        AND type='L'
        AND status='S') AS tcount
WHERE  (user.rating >= '6' OR tcount >= '100')

Body:
You can write that without the subquery, like this

SELECT  u.id
FROM `user` u
JOIN `transaction` t
ON t.user_id=u.id
WHERE t.type = 'L' AND t.status = 'S'
GROUP BY u.id
HAVING sum(case when u.rating >= 6 then 1 end) > 0 OR count(*) >= 100


问:
Multiple selectors: identify the triggering one?
Here's a very small issue that I was unable to figure out. I'm sure someone can answer in no time:

Having multiple selectors like

```<code>$('a.button, span.xyz, a.another').click(function(e) {
   var clicked_element = ???;
});
</code>```

, how can I figure out which selector was actually clicked? I need to use it like $(clicked_element)....

Thanks.

答:
Using $(this) will get you the element that was clicked..  and using is() can help you determine what was clicked.

$('a.button, span.xyz, a.another').click(function(e) {
  if ($(this).is("a.button")) {
    alert("a.button was clicked");
  } else if ($(this).is("span.xyz")) {
    alert("span.xyz was clicked");
  } else if ($(this).is("a.another")) {
    alert("a.another was clicked");
  }
});
```
<hr />
<p><strong>Edited:</strong></p>
<p>As I wrote up this answer it seems there is a better approach.  Patrick DW's comment intrigued me and I wanted to know more.  His clarification is here jQuery - Issues with combining selectors in a single event handler</p>
<p>This would be a better approach</p>
<pre class="lang-js prettyprint-override"><code>$("a.button").click(function(e) { ... });
$("span.xyz").click(function(e) { ... });
$("a.another").click(function(e) { ... });
</code>```

As I understand it if your goal was to place common functionality in one spot then this is how it should be handled

function commonFunctionality(elementSelector) {
  // common code for all elements here or at the end

  switch (elementSelector) {
    case "a.button":
      //do stuff for a.button only;
      break;
    case "span.xyz":
      //do stuff for span.xyz only;
      break;
    case "a.another":
      //do stuff for a.another only;
      break;
  }

  // common code for all elements
}

$("a.button").click(function(e) { ... });
$("span.xyz").click(function(e) { ... });
$("a.another").click(function(e) { ... });
```

ContentLicense: CC BY-SA 2.5

Body:
Here's a very small issue that I was unable to figure out. I'm sure someone can answer in no time:

Having multiple selectors like

$('a.button, span.xyz, a.another').click(function(e) {
   var clicked_element = ???;
});

, how can I figure out which selector was actually clicked? I need to use it like $(clicked_element)....

Thanks.

Body:
Using $(this) will get you the element that was clicked..  and using is() can help you determine what was clicked.

$('a.button, span.xyz, a.another').click(function(e) {
  if ($(this).is("a.button")) {
    alert("a.button was clicked");
  } else if ($(this).is("span.xyz")) {
    alert("span.xyz was clicked");
  } else if ($(this).is("a.another")) {
    alert("a.another was clicked");
  }
});

Edited:

As I wrote up this answer it seems there is a better approach.  Patrick DW's comment intrigued me and I wanted to know more.  His clarification is here jQuery - Issues with combining selectors in a single event handler

This would be a better approach

$("a.button").click(function(e) { ... });
$("span.xyz").click(function(e) { ... });
$("a.another").click(function(e) { ... });

As I understand it if your goal was to place common functionality in one spot then this is how it should be handled

function commonFunctionality(elementSelector) {
  // common code for all elements here or at the end

  switch (elementSelector) {
    case "a.button":
      //do stuff for a.button only;
      break;
    case "span.xyz":
      //do stuff for span.xyz only;
      break;
    case "a.another":
      //do stuff for a.another only;
      break;
  }

  // common code for all elements
}

$("a.button").click(function(e) { ... });
$("span.xyz").click(function(e) { ... });
$("a.another").click(function(e) { ... });

ContentLicense: CC BY-SA 4.0


问:
Turning a string into a dictionary
Having had a python class behind me, I was presented with this question in the next class and I seem to be having a mental block on how to even get started.

"Write a python program that asks the user for a string,  then create the following dictionary: The values are the letters in the string, with the corresponding key being the place in the string. For example if the user entered the string “ABC123” then the dictionary would be: D = {‘A’:0, ‘B’:1, ‘C’:2, ‘1’:3, ‘2’:4, ‘3’:5}

I started with asking for the user input with something simple like

```<code>s = input('Enter string: ')
</code>```

however, I do not know how to proceed to the next step. Any help would be much appreciated.

答:
this?</p>

```<code>def dict():
    user_input = input("Please enter a string")
    dictionary = {}
    for i, j in enumerate(user_input):
        dictionary[j] = i
    print(dictionary)
dict("ABC123")
</code>```

Title: Turning a string into a dictionary

Body:
Having had a python class behind me, I was presented with this question in the next class and I seem to be having a mental block on how to even get started.

"Write a python program that asks the user for a string,  then create the following dictionary: The values are the letters in the string, with the corresponding key being the place in the string. For example if the user entered the string “ABC123” then the dictionary would be: D = {‘A’:0, ‘B’:1, ‘C’:2, ‘1’:3, ‘2’:4, ‘3’:5}

I started with asking for the user input with something simple like

s = input('Enter string: ')

however, I do not know how to proceed to the next step. Any help would be much appreciated.

Body:
this?

def dict():
    user_input = input("Please enter a string")
    dictionary = {}
    for i, j in enumerate(user_input):
        dictionary[j] = i
    print(dictionary)
dict("ABC123")


问:
make JSP Declaration stateless
Consider the following jsp:

```<code><%!
    private String firstName = "";
    private String lastName = "";

    private String formatName(){
        return lastName + ", " + firstName;
    }
%>
<%
    firstName = request.getParameter("FNAME");
    lastName = request.getParameter("LNAME");
    String formattedName = formatName();
    out.print(formattedName);
%>
</code>```

Is there a way to make the declaration section <%! (...) %> stateless? That is I want firstName and lastName to be unique to each page load. I am not concerned with performance or best practice, refactor is not an option right now. I'm looking for something like <%@ page persist="false" %>. Any suggestions?

答:
pvg is 100% correct that this shouldn't be done, and I probably won't use this solution, however I did come up with a solution that allows the methods to be moved without having them take new arguments. It may be useful for others to know that the following is possible, but not best practice.

```<code><%!
    public class MyHandler
    {
        public HttpServletRequest objRequest = null;
        public HttpSession objSession = null;
        public HttpServletResponse objResponse = null;
        public JspWriter objOut = null;

        private String firstName = "";
        private String lastName = "";
        private String formatName(){
            return lastName + ", " + firstName;
        }
        public void go()
        {
            firstName = objRequest.getParameter("FNAME");
            lastName = objRequest.getParameter("LNAME");
            String formattedName = formatName();
            objOut.print(formattedName);
        }
    }
%>
<%
    MyHandler myHandler = new MyHandler();
    myHandler.objRequest = request;
    myHandler.objSession = session;
    myHandler.objResponse = response;
    myHandler.objOut = out;
    myHandler.go();
%>
</code>```

Title: make JSP Declaration stateless

Body:
Consider the following jsp:

<%!
    private String firstName = "";
    private String lastName = "";

    private String formatName(){
        return lastName + ", " + firstName;
    }
%>
<%
    firstName = request.getParameter("FNAME");
    lastName = request.getParameter("LNAME");
    String formattedName = formatName();
    out.print(formattedName);
%>

Is there a way to make the declaration section <%! (...) %> stateless? That is I want firstName and lastName to be unique to each page load. I am not concerned with performance or best practice, refactor is not an option right now. I'm looking for something like <%@ page persist="false" %>. Any suggestions?

Body:
pvg is 100% correct that this shouldn't be done, and I probably won't use this solution, however I did come up with a solution that allows the methods to be moved without having them take new arguments. It may be useful for others to know that the following is possible, but not best practice.

<%!
    public class MyHandler
    {
        public HttpServletRequest objRequest = null;
        public HttpSession objSession = null;
        public HttpServletResponse objResponse = null;
        public JspWriter objOut = null;

        private String firstName = "";
        private String lastName = "";
        private String formatName(){
            return lastName + ", " + firstName;
        }
        public void go()
        {
            firstName = objRequest.getParameter("FNAME");
            lastName = objRequest.getParameter("LNAME");
            String formattedName = formatName();
            objOut.print(formattedName);
        }
    }
%>
<%
    MyHandler myHandler = new MyHandler();
    myHandler.objRequest = request;
    myHandler.objSession = session;
    myHandler.objResponse = response;
    myHandler.objOut = out;
    myHandler.go();
%>


问:
Sorting dictionary of lists in Python
I'm making an auction program and need to sort stored bids by price, and date. I'm trying to pull any bids that equal the reserve price, and find the earliest one. I've pulled the line below from another question, however I need to find the max bid (sorted in reverse to bring highest bid and then oldest bid if there are two of the same value).

```<code>sorted(stored_bids_1.items(), key=lambda e:e[1][2][3][4])
</code>```

The dictionary has the following info:

```<code>stored_bids_1 {bid_number : [cust_bid_price, bid_date_time, cust_num_seats, cust_name]}
</code>```

I'd like the bids to be ranked by bid price, then date&time.

Any help is much appreciated!

答:
I need to find the max bid (sorted in reverse to bring
  highest bid and then oldest bid if there are two of the same value).

This can be done by taking advantage of sort stability and doing two successive sorts:

```<code>bids.sort(key = lambda e: e[1])               # where e[1] is bid_date_time
bids.sort(key = lambda e: e[0], reverse=True) # where e[0] is cust_bid_price
</code>```

See the Python Sorting HowTo guide for more explanation and another example.

Title: Sorting dictionary of lists in Python

Body:
I'm making an auction program and need to sort stored bids by price, and date. I'm trying to pull any bids that equal the reserve price, and find the earliest one. I've pulled the line below from another question, however I need to find the max bid (sorted in reverse to bring highest bid and then oldest bid if there are two of the same value).

sorted(stored_bids_1.items(), key=lambda e:e[1][2][3][4])

The dictionary has the following info:

stored_bids_1 {bid_number : [cust_bid_price, bid_date_time, cust_num_seats, cust_name]}

I'd like the bids to be ranked by bid price, then date&time.

Any help is much appreciated!

Body:
I need to find the max bid (sorted in reverse to bring
  highest bid and then oldest bid if there are two of the same value).

This can be done by taking advantage of sort stability and doing two successive sorts:

bids.sort(key = lambda e: e[1])               # where e[1] is bid_date_time
bids.sort(key = lambda e: e[0], reverse=True) # where e[0] is cust_bid_price

See the Python Sorting HowTo guide for more explanation and another example.


问:
Can't create object with existing primary key value
I'm in my first steps of using Realm Mobile Database, and I would like to know if there is a way of handling the error caused by trying to add an object with the same primaryKey as one previously inserted, causing the following Can't create object with existing primary key value.

Here are my snippets:

```<code>class CategoryRLM: Object {
  dynamic var name: String = ""
  dynamic var desc: String = ""

  override static func primaryKey() -> String? {
    return "name"
  }
}

static func addCategory(category: CategoryRLM) -> Bool {
  let realm = try! Realm()
  do {
      try realm.write {
          realm.add(category)
      }

      return true
  }
  catch let error {
      print(error)
      return false
  }
}
</code>```

Using the previous function:

```<code>if !CategoryRLM.addCategory(category: newCategory) {
  // There was an error while adding the object
}
</code>```

The thing is that the error doesn't get handled by the do-catch.

答:
Attempting to add an object with a primary key that already exists is classed as programmer error (that is, misuse of the API), and as such it is not possible to handle this error at runtime.

In your case you should instead check if an object exists with that primary key prior to attempting to add the category to the Realm:

```<code>static func addCategory(category: CategoryRLM) -> Bool {
    let realm = try! Realm()
    if let existingCategory = realm.object(ofType: CategoryRLM.self, forPrimaryKey: category.name) {
        return false
    }
    try realm.write! {
        realm.add(category)
    }
    return true
}
</code>```

Body:
I'm in my first steps of using Realm Mobile Database, and I would like to know if there is a way of handling the error caused by trying to add an object with the same primaryKey as one previously inserted, causing the following Can't create object with existing primary key value.

Here are my snippets:

class CategoryRLM: Object {
  dynamic var name: String = ""
  dynamic var desc: String = ""

  override static func primaryKey() -> String? {
    return "name"
  }
}

static func addCategory(category: CategoryRLM) -> Bool {
  let realm = try! Realm()
  do {
      try realm.write {
          realm.add(category)
      }

      return true
  }
  catch let error {
      print(error)
      return false
  }
}

Using the previous function:

if !CategoryRLM.addCategory(category: newCategory) {
  // There was an error while adding the object
}

The thing is that the error doesn't get handled by the do-catch.

Body:
Attempting to add an object with a primary key that already exists is classed as programmer error (that is, misuse of the API), and as such it is not possible to handle this error at runtime.

In your case you should instead check if an object exists with that primary key prior to attempting to add the category to the Realm:

static func addCategory(category: CategoryRLM) -> Bool {
    let realm = try! Realm()
    if let existingCategory = realm.object(ofType: CategoryRLM.self, forPrimaryKey: category.name) {
        return false
    }
    try realm.write! {
        realm.add(category)
    }
    return true
}


问:
Where to fill JPA database with initially available values?
I have a Java EE 7 project with a web frontend and I'd like to present some lazily-initialized initial choice to the user which he_she can then complement. The @PostConstruct method of the EJB seemed like a good place, but it doesn't guarantee that a transaction is present.

I'm looking for the most elegant solution, eventually a place which has been foreseen for this task.

The @PostConstruct method of an @ApplicationScoped managed bean in the web frontend would be an option, but I'd still have to make a bogus call to get it initialized - it's way, but maybe not the most elegant one.

答:
Specify the javax.persistence.sql-load-script-source property in your persistence.xml file.

It points at a SQL script that will preload your database. This can be a resource embedded in your application or an external file URL.


问:
Using XPath with NSXMLDocument Objective-C
I have the following XML:

```<code><?xml version="1.0" encoding="UTF-8" ?>
<root>
    <total_count>6640</total_count>
    <song id="5075">
        <title><![CDATA["Babysitting Blues"]]></title>
        <name><![CDATA["Babysitting Blues"]]></name>
        <artist id="1547"><![CDATA[Albert Collins]]></artist>
        <album id="2097"><![CDATA[Adventures In Babysitting]]></album>
        <albumartist id="1546"><![CDATA[Michael Kamen]]></albumartist>
        <tag id="11" count="1" ><![CDATA[Pop Rock]]></tag>
        <filename><![CDATA[/Volumes/data/My Documents/My Music/iTunes Media/Music/Michael Kamen/Adventures In Babysitting/09 _Babysitting Blues_.mp3]]></filename>
        <track>9</track>
        <time>247</time>
        <year>1988</year>
        <bitrate>128000</bitrate>
        <rate>44100</rate>
        <mode>cbr</mode>
        <mime>audio/mpeg</mime>
        <url><![CDATA[http://phirestalker.strangled.net:5555/play/index.php?ssid=faec0117bac5875e1aeb8b15f1826bdf&type=song&oid=5075&uid=3&player=api&name=Albert%20Collins%20-%20-Babysitting%20Blues-.m4a]]></url>
        <size>4119468</size>
        <mbid>4a8b4607-0f7e-4e04-8c62-a9280bb1ff1e</mbid>
        <album_mbid>e80a4221-e21c-4505-af97-27fede6100f4</album_mbid>
        <artist_mbid>5ea2c7d2-cd9c-41ba-a1c2-42889e9c4584</artist_mbid>
        <albumartist_mbid>adcc6c98-0bf1-4d54-84aa-2249cf5e46bf</albumartist_mbid>
        <art><![CDATA[http://phirestalker.strangled.net:5555/image.php?object_id=2097&object_type=album&auth=faec0117bac5875e1aeb8b15f1826bdf]]></art>
        <preciserating>0</preciserating>
        <rating>0</rating>
        <averagerating>0</averagerating>
        <composer><![CDATA[]]></composer>
        <channels></channels>
        <comment><![CDATA[00000000 00000210 00000C24 0000000000A6884C 02000003 003C6398 00000000 00000000 00000000 00000000 00000000 00000000]]></comment>
        <publisher><![CDATA[Intrada]]></publisher>
        <language>eng</language>
        <replaygain_album_gain>0.000000</replaygain_album_gain>
        <replaygain_album_peak>0.000000</replaygain_album_peak>
        <replaygain_track_gain>-0.520000</replaygain_track_gain>
        <replaygain_track_peak>0.540040</replaygain_track_peak>
        <genre><![CDATA[Pop Rock]]></genre>
    </song>
    <song>
        ...
    </song>
    ...
</root>
</code>```

I am trying to use this code to get all <song> nodes(is that the right term?) that contain a certain title.

```<code>Return = [[NSXMLDocument alloc] initWithContentsOfURL:documentsURL options:(NSXMLDocumentTidyXML) error:&err];
if(err)
{
    NSLog(@"Error parsing xml file: %@",err);
    err = nil;
}
NSArray* results = [Return nodesForXPath:@"//root/song[@title='1-2-3']" error:&err];
if(err)
{
    NSLog(@"Error searching songs: %@",err);
    err = nil;
}
NSLog(@"we got this far\n%@",results);
if(results)
{
[results enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    NSXMLElement* node = (NSXMLElement *)obj;
    NSString *artist = [[node attributeForName:@"artist"] stringValue];
    NSString *album = [[node attributeForName:@"album"] stringValue];
    NSLog(@"artist:%@\talbum:%@",artist,album);
}];
}
</code>```

The problem is that the whole results array is empty, so my XPath query is not working at all. I have tried many sources to try to piece together how to make the query. I have even tried the specification for XPath 2.0 from W3C, but that was WAAAAAAY too complicated.

Can anyone tell me what I am doing wrong on the query?

答:
"I am trying to use this code to get all <song> nodes(is that the right term?) that contain a certain title."

@ used to reference XML attribute. Since title is an element, the correct XPath for your case would be :

```<code>//root/song[child::title='1-2-3']
</code>```

and since child is the default axis in XPath, it can be implied :

```<code>//root/song[title='1-2-3']
</code>```

Body:
I have the following XML:

<?xml version="1.0" encoding="UTF-8" ?>
<root>
    <total_count>6640</total_count>
    <song id="5075">
        <title><![CDATA["Babysitting Blues"]]></title>
        <name><![CDATA["Babysitting Blues"]]></name>
        <artist id="1547"><![CDATA[Albert Collins]]></artist>
        <album id="2097"><![CDATA[Adventures In Babysitting]]></album>
        <albumartist id="1546"><![CDATA[Michael Kamen]]></albumartist>
        <tag id="11" count="1" ><![CDATA[Pop Rock]]></tag>
        <filename><![CDATA[/Volumes/data/My Documents/My Music/iTunes Media/Music/Michael Kamen/Adventures In Babysitting/09 _Babysitting Blues_.mp3]]></filename>
        <track>9</track>
        <time>247</time>
        <year>1988</year>
        <bitrate>128000</bitrate>
        <rate>44100</rate>
        <mode>cbr</mode>
        <mime>audio/mpeg</mime>
        <url><![CDATA[http://phirestalker.strangled.net:5555/play/index.php?ssid=faec0117bac5875e1aeb8b15f1826bdf&type=song&oid=5075&uid=3&player=api&name=Albert%20Collins%20-%20-Babysitting%20Blues-.m4a]]></url>
        <size>4119468</size>
        <mbid>4a8b4607-0f7e-4e04-8c62-a9280bb1ff1e</mbid>
        <album_mbid>e80a4221-e21c-4505-af97-27fede6100f4</album_mbid>
        <artist_mbid>5ea2c7d2-cd9c-41ba-a1c2-42889e9c4584</artist_mbid>
        <albumartist_mbid>adcc6c98-0bf1-4d54-84aa-2249cf5e46bf</albumartist_mbid>
        <art><![CDATA[http://phirestalker.strangled.net:5555/image.php?object_id=2097&object_type=album&auth=faec0117bac5875e1aeb8b15f1826bdf]]></art>
        <preciserating>0</preciserating>
        <rating>0</rating>
        <averagerating>0</averagerating>
        <composer><![CDATA[]]></composer>
        <channels></channels>
        <comment><![CDATA[00000000 00000210 00000C24 0000000000A6884C 02000003 003C6398 00000000 00000000 00000000 00000000 00000000 00000000]]></comment>
        <publisher><![CDATA[Intrada]]></publisher>
        <language>eng</language>
        <replaygain_album_gain>0.000000</replaygain_album_gain>
        <replaygain_album_peak>0.000000</replaygain_album_peak>
        <replaygain_track_gain>-0.520000</replaygain_track_gain>
        <replaygain_track_peak>0.540040</replaygain_track_peak>
        <genre><![CDATA[Pop Rock]]></genre>
    </song>
    <song>
        ...
    </song>
    ...
</root>

I am trying to use this code to get all <song> nodes(is that the right term?) that contain a certain title.

Return = [[NSXMLDocument alloc] initWithContentsOfURL:documentsURL options:(NSXMLDocumentTidyXML) error:&err];
if(err)
{
    NSLog(@"Error parsing xml file: %@",err);
    err = nil;
}
NSArray* results = [Return nodesForXPath:@"//root/song[@title='1-2-3']" error:&err];
if(err)
{
    NSLog(@"Error searching songs: %@",err);
    err = nil;
}
NSLog(@"we got this far\n%@",results);
if(results)
{
[results enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    NSXMLElement* node = (NSXMLElement *)obj;
    NSString *artist = [[node attributeForName:@"artist"] stringValue];
    NSString *album = [[node attributeForName:@"album"] stringValue];
    NSLog(@"artist:%@\talbum:%@",artist,album);
}];
}

The problem is that the whole results array is empty, so my XPath query is not working at all. I have tried many sources to try to piece together how to make the query. I have even tried the specification for XPath 2.0 from W3C, but that was WAAAAAAY too complicated.

Can anyone tell me what I am doing wrong on the query?

Body:
"I am trying to use this code to get all <song> nodes(is that the right term?) that contain a certain title."

@ used to reference XML attribute. Since title is an element, the correct XPath for your case would be :

//root/song[child::title='1-2-3']

and since child is the default axis in XPath, it can be implied :

//root/song[title='1-2-3']


问:
Angular Queue Action From Directive To Service
I'm trying to get better understanding of how to code in Angular properly and am writing my own custom module to better understand how things are supposed to work.

I have an HTML markup consisting of images and a directive i.e.

```<code><img ng-if="!post.tooBig" mydirective resize="0" ng-src="/img/@{{post.Content}}">
</code>```

My directive is here:

```<code>.directive('mydirective', [
           '$animate','$mediaStack',
  function($animate,$mediaStack) {
  return {
    restrict: 'A',
    compile: function(tElement, tAttrs) {
        return loader;
    }
  };

    function loader(scope, element, attrs) {
      var source = attrs.ngSrc;
      var tooLoadBig = parseInt(attrs.resize);
      if(tooLoadBig){
        var bigImage = new Image();
        bigImage.src = source.replace("small.",".");
      }
      }
}])
</code>```

The idea is this: if the image has small appended to its filename, I know it is a thumbnail. I want to load it's big version (same file without the appended small) in the background so it is ready for a lightbox.

This works fine as is, but the problem is because I'm doing all the work in the compile, when I set bigImage.src = source.replace("small.","."); it fires off right away, and if I have many small images on the page, it causes the page to slow down because of all the loading that is going on.

I want to therefore use $q to make it so that it will load one image at a time.

So move

```<code> var bigImage = new Image();
 bigImage.src = source.replace("small.",".");
</code>```

Into a promise. Is it best practice to do this in the directive? My understanding is it wouldn't make sense to do so and that I should use a service, but I'm not sure how to do that. I could play around with it more but I was hoping someone with more experience could instruct me as to best-practices for something like this and a code sample of a similar workflow, thank you.

Edits:

Directive:

```<code>.directive('mydirective', [
           '$animate','$mediaStack',
  function($animate,$mediaStack) {
  return {
    restrict: 'A',
    compile: function(tElement, tAttrs) {
        return loader;
    }
  };

    function loader(scope, element, attrs) {
      var source = attrs.ngSrc;
      var tooLoadBig = parseInt(attrs.resize);
      if(tooLoadBig){
        /*var bigImage = new Image();
        bigImage.src = source.replace("small.",".");*/
        $mediaStack.load(source);
      }
      }
}])
</code>```

My service:

```<code>.factory('$mediaStack', [
             '$animate', '$timeout', '$document', '$compile', '$rootScope',
             '$q',
             '$injector',
    function($animate ,  $timeout ,  $document ,  $compile ,  $rootScope ,
              $q,
              $injector) {
      var OPENED_MEDIA_CLASS = 'media-open';
      var theImages = [];
      $mediaStack = {};
      $mediaStack.load = function(source){
          theImages.push(source);
      };
      $mediaStack.loadRequest   = function(theImages) {

                          deferred.resolve(function(){
                          var bigImage = new Image();
                          bigImage.src = theImages[0].replace("small.",".");
                          });
                          return deferred.promise;
                        }

                        /*var promise = asyncGreet('Robin Hood');
                        promise.then(function(greeting) {
                          alert('Success: ' + greeting);
                        }, function(reason) {
                          alert('Failed: ' + reason);
                        }, function(update) {
                          alert('Got notification: ' + update);
                        });*/
                        //above from docs
      }
      return $mediaStack;
    }])
</code>```

This works in that it gets the image urls into an array in the service, so I have all the images in the array, how do I use $q properly based off that array. I got started but most of the $mediaStack.loadRequest is based off the $q documentation, I'm not sure how to use it effectively in this case.

EDIT 2:

My service as is:

```<code>    .factory('$mediaStack', [
                 '$animate', '$timeout', '$document', '$compile', '$rootScope',
                 '$q',
                 '$injector',
        function($animate ,  $timeout ,  $document ,  $compile ,  $rootScope ,
                  $q,
                  $injector) {
           var OPENED_MEDIA_CLASS = 'media-open';
      var theImages = [];
      var theLoadedImages = [];
      var thePromises = [];
      var loading = false;
      $mediaStack = {};
      $mediaStack.load = function(source){
          theImages.push(source);
          var mainDeferred = $q.defer();
         if(loading)
         {
             thePromises.push(mainDeferred.promise);
             console.log(thePromises);
             $mediaStack.myRaceFn(thePromises).then(function() {
             console.log("Fire!");
             loading=true;
            $mediaStack.loadRequest(theImages[0]).then(function(bigImage){
          console.log(bigImage);
            theImages.shift();
            theLoadedImages.push(bigImage);
            loading = false;
          mainDeferred.resolve();
        });
      });
         }
         if(!loading)
         {
            loading = true;
            $mediaStack.loadRequest(theImages[0]).then(function(bigImage){
            console.log(bigImage);
            theImages.shift();
            theLoadedImages.push(bigImage);
            loading = false;
            mainDeferred.resolve();
            });

         }
           }
      $mediaStack.loadRequest = function(source){
                          var deferred = $q.defer();
                          var bigImage = new Image();
                          bigImage.src = source.replace("small.",".");
                          bigImage.onload = function() {
                          deferred.resolve(bigImage);
                          }
                           return deferred.promise;
      }
      //.race implementation in old angular
      $mediaStack.myRaceFn = function (promises){
   return $q(function(resolve, reject) {
     promises.forEach(function(promise) {
       console.log(promise);
       promise.then(resolve, reject);
     });
   });
}
//.race implementation in old angular
      return $mediaStack;
        }])
</code>```

I'm very close, I see an array of promises but I never get to the point of being able to fire them again, so I have 10 images, and I get an array of 9 promises. How do I fire them?

I expected it would happen around here:

```<code>$mediaStack.myRaceFn(thePromises).then(function() {
console.log("Fire!");
loading=true;
$mediaStack.loadRequest(theImages[0]).then(function(bigImage){
</code>```

But I never get that console.log().

Instead I get console messages in $mediaStack.myRaceFn() showing me each promise (9 at the end) but they just sit there? I'm missing something.

I think I may be resolving mainDeferred too early...

答:
I think, that your hunch is good. You need a service to handle requests for your images. Remember that browsers are limited to send multiple concurrent requests to single server/proxy (Max parallel http connections in a browser?)

In theory you could create a promise and expose it thru two way bindings or even drive loading with an attribute. Something like:

HTML:

```<code><img mydirective="booleanValue" />
</code>```

In mydirective:

```<code>$scope.$watch('mydirective', function (newVal, oldVal) {
  if (newVal === true) {
    //perform the load
  }
});
</code>```

But I think, that a service would be better. You could decide what and when to load, from that single point. It wouldn't be limited to UI component, you could load bigger images not only from directives context.
So in the service the essential code would be:

module.factory('$mediaStack', ['$q', function($q) { //first of all you don't need all of these dependencies, keep the list short
  var imgDict = {}; //Image dictionary where we're going to keep promises and loaded images
  var loadingNow = 0;

  function loadImage(img) {
    //Send request and return promise
    var deferred = $q.defer();
    var bigImage = new Image();

    bigImage.onload = function() {
      deferred.resolve(bigImage);
    }

    bigImage.src = source.replace("small.", ".");

    return deferred.promise;
  }

  var $mediaStack = function(img) {
    var deferred = $q.defer(); //the main deferred task

    if (loadingNow > 4) { //if we're loading 5 images or more, defer the task untill one of the Images is loaded
      var promises = []; //an array of promises, list of images which are loading now
      Object.keys(imgDict).forEach(function(key) {
        if (!(imgDict[key] instanceof Element)) { //Check if the item from dictionary is a promise or loaded image
          promises.push(imgDict[key]); //if it's a promise, add it to the list
        }
      });
      $q.race(promises).then(function() { //use the list, to create a race: when one of the promises resolves (image is loaded) we can fire our function again (we probably have less than 5 Images loading at the same time)
        $mediaStack(img).then(function(data) { //call the function again
          deferred.resolve(data); //as we return a promise form that function we have to resolve main deferred object
        });
      });
    }

    if (!(img in imgDict)) { //when the image is not loaded yet
      loadingNow++; //increase the number of images being loaded
      imgDict[img] = loadImage(img).then(function(imgDOM) { //and load the image
        imgDict[img] = imgDOM;
        deferred.resolve(imgDOM); //once it's loaded resolve the main deferred task
        loadingNow--;
      });
    } else {
      deferred.resolve(imgDict[img]);
    }

    return deferred.promise; //promise to the main deferred task
  }

  return $mediaStack;
}]);```

The general idea behind promises and deferred tasks:
Deferred object is a deferred task, which has a Promise parameter - a entry point of a callback, which is going to be invoked once the deferred task is completed.

Check $q docs for more: angular $q

And how to write a service: https://docs.angularjs.org/guide/services

What is Promise? The general idea and native API

Hope it helps.

Body:
I'm trying to get better understanding of how to code in Angular properly and am writing my own custom module to better understand how things are supposed to work.

I have an HTML markup consisting of images and a directive i.e.

My directive is here:

.directive('mydirective', [
           '$animate','$mediaStack',
  function($animate,$mediaStack) {
  return {
    restrict: 'A',
    compile: function(tElement, tAttrs) {
        return loader;
    }
  };

    function loader(scope, element, attrs) {
      var source = attrs.ngSrc;
      var tooLoadBig = parseInt(attrs.resize);
      if(tooLoadBig){
        var bigImage = new Image();
        bigImage.src = source.replace("small.",".");
      }
      }
}])

The idea is this: if the image has small appended to its filename, I know it is a thumbnail. I want to load it's big version (same file without the appended small) in the background so it is ready for a lightbox.

This works fine as is, but the problem is because I'm doing all the work in the compile, when I set bigImage.src = source.replace("small.","."); it fires off right away, and if I have many small images on the page, it causes the page to slow down because of all the loading that is going on.

I want to therefore use $q to make it so that it will load one image at a time.

So move

 var bigImage = new Image();
 bigImage.src = source.replace("small.",".");

Into a promise. Is it best practice to do this in the directive? My understanding is it wouldn't make sense to do so and that I should use a service, but I'm not sure how to do that. I could play around with it more but I was hoping someone with more experience could instruct me as to best-practices for something like this and a code sample of a similar workflow, thank you.

Edits:

Directive:

.directive('mydirective', [
           '$animate','$mediaStack',
  function($animate,$mediaStack) {
  return {
    restrict: 'A',
    compile: function(tElement, tAttrs) {
        return loader;
    }
  };

    function loader(scope, element, attrs) {
      var source = attrs.ngSrc;
      var tooLoadBig = parseInt(attrs.resize);
      if(tooLoadBig){
        /*var bigImage = new Image();
        bigImage.src = source.replace("small.",".");*/
        $mediaStack.load(source);
      }
      }
}])

My service:

.factory('$mediaStack', [
             '$animate', '$timeout', '$document', '$compile', '$rootScope',
             '$q',
             '$injector',
    function($animate ,  $timeout ,  $document ,  $compile ,  $rootScope ,
              $q,
              $injector) {
      var OPENED_MEDIA_CLASS = 'media-open';
      var theImages = [];
      $mediaStack = {};
      $mediaStack.load = function(source){
          theImages.push(source);
      };
      $mediaStack.loadRequest   = function(theImages) {

                          deferred.resolve(function(){
                          var bigImage = new Image();
                          bigImage.src = theImages[0].replace("small.",".");
                          });
                          return deferred.promise;
                        }

                        /*var promise = asyncGreet('Robin Hood');
                        promise.then(function(greeting) {
                          alert('Success: ' + greeting);
                        }, function(reason) {
                          alert('Failed: ' + reason);
                        }, function(update) {
                          alert('Got notification: ' + update);
                        });*/
                        //above from docs
      }
      return $mediaStack;
    }])

This works in that it gets the image urls into an array in the service, so I have all the images in the array, how do I use $q properly based off that array. I got started but most of the $mediaStack.loadRequest is based off the $q documentation, I'm not sure how to use it effectively in this case.

EDIT 2:

My service as is:

    .factory('$mediaStack', [
                 '$animate', '$timeout', '$document', '$compile', '$rootScope',
                 '$q',
                 '$injector',
        function($animate ,  $timeout ,  $document ,  $compile ,  $rootScope ,
                  $q,
                  $injector) {
           var OPENED_MEDIA_CLASS = 'media-open';
      var theImages = [];
      var theLoadedImages = [];
      var thePromises = [];
      var loading = false;
      $mediaStack = {};
      $mediaStack.load = function(source){
          theImages.push(source);
          var mainDeferred = $q.defer();
         if(loading)
         {
             thePromises.push(mainDeferred.promise);
             console.log(thePromises);
             $mediaStack.myRaceFn(thePromises).then(function() {
             console.log("Fire!");
             loading=true;
            $mediaStack.loadRequest(theImages[0]).then(function(bigImage){
          console.log(bigImage);
            theImages.shift();
            theLoadedImages.push(bigImage);
            loading = false;
          mainDeferred.resolve();
        });
      });
         }
         if(!loading)
         {
            loading = true;
            $mediaStack.loadRequest(theImages[0]).then(function(bigImage){
            console.log(bigImage);
            theImages.shift();
            theLoadedImages.push(bigImage);
            loading = false;
            mainDeferred.resolve();
            });

         }
           }
      $mediaStack.loadRequest = function(source){
                          var deferred = $q.defer();
                          var bigImage = new Image();
                          bigImage.src = source.replace("small.",".");
                          bigImage.onload = function() {
                          deferred.resolve(bigImage);
                          }
                           return deferred.promise;
      }
      //.race implementation in old angular
      $mediaStack.myRaceFn = function (promises){
   return $q(function(resolve, reject) {
     promises.forEach(function(promise) {
       console.log(promise);
       promise.then(resolve, reject);
     });
   });
}
//.race implementation in old angular
      return $mediaStack;
        }])

I'm very close, I see an array of promises but I never get to the point of being able to fire them again, so I have 10 images, and I get an array of 9 promises. How do I fire them?

I expected it would happen around here:

$mediaStack.myRaceFn(thePromises).then(function() {
console.log("Fire!");
loading=true;
$mediaStack.loadRequest(theImages[0]).then(function(bigImage){

But I never get that console.log().

Instead I get console messages in $mediaStack.myRaceFn() showing me each promise (9 at the end) but they just sit there? I'm missing something.

I think I may be resolving mainDeferred too early...

Body:
I think, that your hunch is good. You need a service to handle requests for your images. Remember that browsers are limited to send multiple concurrent requests to single server/proxy (Max parallel http connections in a browser?)

In theory you could create a promise and expose it thru two way bindings or even drive loading with an attribute. Something like:

HTML:

<img mydirective="booleanValue" />

In mydirective:

$scope.$watch('mydirective', function (newVal, oldVal) {
  if (newVal === true) {
    //perform the load
  }
});

But I think, that a service would be better. You could decide what and when to load, from that single point. It wouldn't be limited to UI component, you could load bigger images not only from directives context.
So in the service the essential code would be:

module.factory('$mediaStack', ['$q', function($q) { //first of all you don't need all of these dependencies, keep the list short
  var imgDict = {}; //Image dictionary where we're going to keep promises and loaded images
  var loadingNow = 0;

  function loadImage(img) {
    //Send request and return promise
    var deferred = $q.defer();
    var bigImage = new Image();

    bigImage.onload = function() {
      deferred.resolve(bigImage);
    }

    bigImage.src = source.replace("small.", ".");

    return deferred.promise;
  }

  var $mediaStack = function(img) {
    var deferred = $q.defer(); //the main deferred task

    if (loadingNow > 4) { //if we're loading 5 images or more, defer the task untill one of the Images is loaded
      var promises = []; //an array of promises, list of images which are loading now
      Object.keys(imgDict).forEach(function(key) {
        if (!(imgDict[key] instanceof Element)) { //Check if the item from dictionary is a promise or loaded image
          promises.push(imgDict[key]); //if it's a promise, add it to the list
        }
      });
      $q.race(promises).then(function() { //use the list, to create a race: when one of the promises resolves (image is loaded) we can fire our function again (we probably have less than 5 Images loading at the same time)
        $mediaStack(img).then(function(data) { //call the function again
          deferred.resolve(data); //as we return a promise form that function we have to resolve main deferred object
        });
      });
    }

    if (!(img in imgDict)) { //when the image is not loaded yet
      loadingNow++; //increase the number of images being loaded
      imgDict[img] = loadImage(img).then(function(imgDOM) { //and load the image
        imgDict[img] = imgDOM;
        deferred.resolve(imgDOM); //once it's loaded resolve the main deferred task
        loadingNow--;
      });
    } else {
      deferred.resolve(imgDict[img]);
    }

    return deferred.promise; //promise to the main deferred task
  }

  return $mediaStack;
}]);

The general idea behind promises and deferred tasks:
Deferred object is a deferred task, which has a Promise parameter - a entry point of a callback, which is going to be invoked once the deferred task is completed.

Check $q docs for more: angular $q

And how to write a service: https://docs.angularjs.org/guide/services

What is Promise? The general idea and native API

Hope it helps.


问:
Stream video from isolated storage in wp7
I'm trying to make some wp7 app which should play videos from server.
One of the app's features is downloading selected videos and playing them from isolated storage.

I'm using next code for downloading:

```<code>WebClient wc = new WebClient();
wc.OpenReadCompleted += (s, a) => { /* saving result stream to isolated storage */}
wc.OpenReadAsync(fileUri);
</code>```

So, when I click on play button, I check if file was downloaded or not, and if it was I open IsolatedStorageFileStream for this file and set it to player's source, otherwise I set to source file Uri.

Problem is that I get MediaFailed exception when I'm trying to set IsolatedStorageFileStream as MedialElement's source. Can anybody help me with it?

Code looks like in next way

```<code>private IsolatedStorageFile isf;
private IsolatedStorageFileStream stream;

private void playButton_Click(..)
{
isf = IsolatedStorageFile.GetUserStoreForApplication();
stream = isf.OpenFile(path, FileMode.Open);
MediaPlayer.SetSource(stream);
MediaPlayer.Play();
}
</code>```

Stream is not corrupted, its length is correct. I realy don't know what to do with it.
Thanks in advance

答:
I've found solution, it's very strange, but works

The problem was that I save files with names %clipId%.clip, but when I changed file names to %clipId%.mp4 (my clips are encoded in mp4) it becomes work!!!

Can't understand why it is so.

Body:
I'm trying to make some wp7 app which should play videos from server.
One of the app's features is downloading selected videos and playing them from isolated storage.

I'm using next code for downloading:

WebClient wc = new WebClient();
wc.OpenReadCompleted += (s, a) => { /* saving result stream to isolated storage */}
wc.OpenReadAsync(fileUri);

So, when I click on play button, I check if file was downloaded or not, and if it was I open IsolatedStorageFileStream for this file and set it to player's source, otherwise I set to source file Uri.

Problem is that I get MediaFailed exception when I'm trying to set IsolatedStorageFileStream as MedialElement's source. Can anybody help me with it?

Code looks like in next way

private IsolatedStorageFile isf;
private IsolatedStorageFileStream stream;

private void playButton_Click(..)
{
isf = IsolatedStorageFile.GetUserStoreForApplication();
stream = isf.OpenFile(path, FileMode.Open);
MediaPlayer.SetSource(stream);
MediaPlayer.Play();
}

Stream is not corrupted, its length is correct. I realy don't know what to do with it.
Thanks in advance


问:
All UITableViewControllers in app allow scrolling up beyond the beginning and past the end of the list.
After using my app for several minutes, all table views in the app start behaving strangely. The scrolling becomes jerky and you can scroll the list above the start and below the end. What could be causing this?

答: I had a recursive UiView Animation that was preventing a viewcontroller from being deallocated. After loading and not unloading that VC a few times, the main thread began to bog down.</p>


问:
Steps required to interract with IndexedDB via Dexie
Let's say I create a very simple datastore using the steps below:

var db = new Dexie('MyDatabase');

db.version(1).stores({ friends: 'name, age' });

db.friends.add({ name: 'Camilla', age: 25 });

Now, let’s say the user closes their browser and comes back a day later and we need to query the data that we already saved in a datastore that should already exist.  Do I need to include both line 1 and line 2 each time before I query the datastore or insert new rows?  I’m confused about when I’m required to execute line 2 – is it basically before I do anything to/with the datastore?

答:
You would normally provide the db.version(x).stores({...}) each time you open the database, no matter if it needs to be created, upgraded or just being opened. By providing this info, you will get immediate access to your tables directly on the db object (accessing for example db.friends.toArray() without waiting for db.open() to finish) as samplified below:

```<code>var db = new Dexie("friendsDB");
db.version(1).stores({friends: 'id, name'});
// Here you can just access db.friends without waiting for db.open()
db.friends.toArray()
   .then(friends => console.table(friends))
   .catch(err => console.error(err));
</code>```

However, it is also possible to open a database dynamically - that is, open an exising database without knowing its tables or indexes. To do that, you just omit the version().stores() part. Just be aware that you wont be able to access tables directly on the db instance and you don't get the magic auto-creation of the database. Tables meed to be accessed through the tables property and table() method, and only after db.open() has completed.

```<code>new Dexie("friendsDB").open().then(db => {
    console.log("Table names: " + db.tables.map(t => t.name));
    return db.table("friends").toArray();
}).then(friends => {
    console.table(friends);
}).catch(err => console.error(err));
</code>```

Body:
You would normally provide the db.version(x).stores({...}) each time you open the database, no matter if it needs to be created, upgraded or just being opened. By providing this info, you will get immediate access to your tables directly on the db object (accessing for example db.friends.toArray() without waiting for db.open() to finish) as samplified below:

var db = new Dexie("friendsDB");
db.version(1).stores({friends: 'id, name'});
// Here you can just access db.friends without waiting for db.open()
db.friends.toArray()
   .then(friends => console.table(friends))
   .catch(err => console.error(err));

However, it is also possible to open a database dynamically - that is, open an exising database without knowing its tables or indexes. To do that, you just omit the version().stores() part. Just be aware that you wont be able to access tables directly on the db instance and you don't get the magic auto-creation of the database. Tables meed to be accessed through the tables property and table() method, and only after db.open() has completed.

new Dexie("friendsDB").open().then(db => {
    console.log("Table names: " + db.tables.map(t => t.name));
    return db.table("friends").toArray();
}).then(friends => {
    console.table(friends);
}).catch(err => console.error(err));


问:
jQuery .focus() causes page to jump
I have a function that should scroll a user back to a search input at the top of the page, and then place focus on it (so the cursor is blinking). For some reason, it seems to apply the focus to the search input first. This creates a very quick jump/spazzy movement of the page to the search bar, jumps back to the bottom, and then scrolls up slowly.

The Javascript:

```<code>function goToSearch(){
    $('html,body').animate({scrollTop: $('#search').offset().top},'medium');
    $('#search').focus()
}
</code>```

The HTML:

```<code><input type="text" id="search" placeholder="search">
...
<a href="#" onclick="goToSearch()">Search</a>
</code>```

I've tried setting .delay() functions to no avail; it seems to always apply the .focus() first. Why is this happening?

答:
If you found this question like me, you were probably looking for a CSS related issue coupled with the js focus() and you might think you're out of luck. Well, think again - the good news is that there IS a way to have a callback when a CSS animation or transition ends and then fire your event.

You can make use of jQuery's one method and use either webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend for transitions or webkitAnimationEnd oanimationend msAnimationEnd animationend for animations.

An example:

JS:

```<code>var myButton = $('#button'),
   myBox = $('#box');
    myButton.click(function () {
    myBox.addClass('change-size');
    myBox.one('webkitAnimationEnd oanimationend msAnimationEnd animationend',
    function(e) {
    // code to execute after animation ends
    myBox.removeClass('change-size');
    });

});
</code>```

CSS:

```<code>.box {
   width: 100px;
   height: 100px;
   background: hotpink;
}

@keyframes growBox {
    to {
        width: 300px;
        height: 200px;
    }
}

.change-size {
    animation: growBox 3s linear 0s 1 normal;
}
</code>```

The solution is not mine, I just found it after a couple of wasted hours, and I'm posting it in case you find this question first.

Source: http://blog.teamtreehouse.com/using-jquery-to-detect-when-css3-animations-and-transitions-end

Title: jQuery .focus() causes page to jump

Body:
I have a function that should scroll a user back to a search input at the top of the page, and then place focus on it (so the cursor is blinking). For some reason, it seems to apply the focus to the search input first. This creates a very quick jump/spazzy movement of the page to the search bar, jumps back to the bottom, and then scrolls up slowly.

The Javascript:

function goToSearch(){
    $('html,body').animate({scrollTop: $('#search').offset().top},'medium');
    $('#search').focus()
}

The HTML:

<input type="text" id="search" placeholder="search">
...
Search

I've tried setting .delay() functions to no avail; it seems to always apply the .focus() first. Why is this happening?

Body:
If you found this question like me, you were probably looking for a CSS related issue coupled with the js focus() and you might think you're out of luck. Well, think again - the good news is that there IS a way to have a callback when a CSS animation or transition ends and then fire your event.

You can make use of jQuery's one method and use either webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend for transitions or webkitAnimationEnd oanimationend msAnimationEnd animationend for animations.

An example:

JS:

var myButton = $('#button'),
   myBox = $('#box');
    myButton.click(function () {
    myBox.addClass('change-size');
    myBox.one('webkitAnimationEnd oanimationend msAnimationEnd animationend',
    function(e) {
    // code to execute after animation ends
    myBox.removeClass('change-size');
    });

});

CSS:

.box {
   width: 100px;
   height: 100px;
   background: hotpink;
}

@keyframes growBox {
    to {
        width: 300px;
        height: 200px;
    }
}

.change-size {
    animation: growBox 3s linear 0s 1 normal;
}

The solution is not mine, I just found it after a couple of wasted hours, and I'm posting it in case you find this question first.

Source: http://blog.teamtreehouse.com/using-jquery-to-detect-when-css3-animations-and-transitions-end


问:
Embed UIViewController inside a UIView
I want to embed a UIViewController inside a UIView. I want to create this programmatically. I have created the UIViewController inside the storyboard.

My code to create a empty UIView:

```<code>let myNewView=UIView(frame: CGRect(x: (0 + screenHeight / 2), y: leftView.frame.origin.y, width: screenHeight / 2, height: leftView.frame.height))
myNewView.backgroundColor=UIColor.lightGray

self.view.addSubview(myNewView)
</code>```

And the code to append the UIViewController to the view:

```<code>let storyboard = UIStoryboard(name: "Main", bundle: nil)
var controller: UIViewController = storyboard.instantiateViewController(withIdentifier: "testView") as UIViewController
myNewView.addSubview(controller.view)
</code>```

This displays the view inside my UIView, but not at the correct way. The UIView is in this case 512 pixels wide. While the (embeded) UIViewcontroller thinks that is is 1024 pixels wide (the full screen width).

How can I fix it that the embeded view gets the width and height from its parent (the UIView)?

答:
As others said you can't embed a viewcontroller view inside a view.
What you can do is embed a ViewController inside another ViewController as a ChildViewController.

Try replacing your newView code with:

```<code>let storyboard = UIStoryboard(name: "Main", bundle: nil)
var controller: UIViewController = storyboard.instantiateViewController(withIdentifier: "testView") as UIViewController

//add as a childviewcontroller
 addChildViewController(controller)

 // Add the child's View as a subview
 self.view.addSubview(controller.view)
 controller.view.frame = view.bounds
 controller.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]

 // tell the childviewcontroller it's contained in it's parent
  controller.didMove(toParentViewController: self)
</code>```

EDIT:
To change how and where the childviewcontroller appears, simply update its frame.
for example to make it half the height and anchored to the bottom:

```<code>controller.view.frame = CGRect(x: 0, y: view.center.y, width: view.size.width, height: view.size.height * 0.5)
</code>```

Title: Embed UIViewController inside a UIView

Body:
I want to embed a UIViewController inside a UIView. I want to create this programmatically. I have created the UIViewController inside the storyboard.

My code to create a empty UIView:

let myNewView=UIView(frame: CGRect(x: (0 + screenHeight / 2), y: leftView.frame.origin.y, width: screenHeight / 2, height: leftView.frame.height))
myNewView.backgroundColor=UIColor.lightGray

self.view.addSubview(myNewView)

And the code to append the UIViewController to the view:

let storyboard = UIStoryboard(name: "Main", bundle: nil)
var controller: UIViewController = storyboard.instantiateViewController(withIdentifier: "testView") as UIViewController
myNewView.addSubview(controller.view)

This displays the view inside my UIView, but not at the correct way. The UIView is in this case 512 pixels wide. While the (embeded) UIViewcontroller thinks that is is 1024 pixels wide (the full screen width).

How can I fix it that the embeded view gets the width and height from its parent (the UIView)?

Body:
As others said you can't embed a viewcontroller view inside a view.
What you can do is embed a ViewController inside another ViewController as a ChildViewController.

Try replacing your newView code with:

let storyboard = UIStoryboard(name: "Main", bundle: nil)
var controller: UIViewController = storyboard.instantiateViewController(withIdentifier: "testView") as UIViewController

//add as a childviewcontroller
 addChildViewController(controller)

 // Add the child's View as a subview
 self.view.addSubview(controller.view)
 controller.view.frame = view.bounds
 controller.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]

 // tell the childviewcontroller it's contained in it's parent
  controller.didMove(toParentViewController: self)

EDIT:
To change how and where the childviewcontroller appears, simply update its frame.
for example to make it half the height and anchored to the bottom:

controller.view.frame = CGRect(x: 0, y: view.center.y, width: view.size.width, height: view.size.height * 0.5)


问:
JavaFX Auto Open new Window
I have A.fxml and B.fxml. A runing with Java Application override start method. I want to every 40 min in loop(5 times) { open new stage B.fxml and wait stage.close, if stage close continue loop open new stage B fxml. Loop this five times. I try timer timertask i could not. I try JavaFX Service i could not. I create Mythread extend Thread object. This time i could not control loop for next stage. When for statement start opening 5 stage. But i want to loop wait for currentstage is close then go next loop.  This is my fail code;

```<code>public class Driver extends Application {

public static Stage stage;

@Override
public void start(Stage primaryStage) throws Exception {
    FXMLLoader loader = new FXMLLoader(getClass().getResource(View.SETTINGS));
    Parent root = loader.load();
    Scene scene = new Scene(root);
    stage = primaryStage;
    stage.setScene(scene);
    stage.setTitle("Info Library");
    stage.setResizable(false);
    stage.show();
    RandomQuestionThread thread = new RandomQuestionThread();
    if (DBContext.settings.isAbbreviation() || DBContext.settings.isTranslation()) {
        thread.start();
    }
}

public static void main(String[] args) throws InterruptedException {
    DBContext.settings = DBContext.getInstance().settings().getSettings();

    launch(args);
    HibernateUtil.getSessionFactory().close();
}
</code>```

}

```<code>public class RandomQuestionThread extends Thread {
Thread randomThread = new Thread(this);
private String fxml;
private static String TITLE;

@Override
public void run() {
    while (true) {
        try {
            Thread.sleep(DBContext.settings.getAutoQuestionTime() * 6000);
        } catch (InterruptedException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        for (int i = 0; i<DBContext.settings.getAutoQuestionCount(); i++) {
            randomFxml();
            Platform.runLater(()->{
                Parent root = null;
                try {
                    root = new FXMLLoader(getClass().getResource(fxml)).load();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                Stage stage = new Stage();
                stage.setScene(new Scene(root));
                stage.setTitle(TITLE);
                stage.show();
                System.out.println(currentThread().getName());
            });
        }
    }
}

private void randomFxml() {
    int start = 0;
    if (DBContext.settings.isTranslation() && DBContext.settings.isAbbreviation()) {
        start = new Random().nextInt(2);
    } else if (DBContext.settings.isTranslation()) {
        start = 1;
    }

    switch (start) {
    case 0:
        fxml = View.ABBREVIATION;
        break;
    case 1:
        fxml = View.TRANSLATION;
        break;

    default:
        break;
    }
    if (start == 0) {
        TITLE = "KISALTMA SORUSU";
    } else TITLE = "ÇEVİRİ SORUSU";
}
</code>```

}

I need to work more Java multi threads. But after fix this problem. Please explain where I'm doing wrong. In loop write console currentThread name console result "Java Apllication Thread". But i set my thread name "MyThread". I'm so confused.My brain gave blue screen error.

答:
You've put your System.out.println(currentThread().getName()) statement into Platform.runLater(), which means that it will be executed on JavaFX Application Thread (see JavaDoc).

Regarding your question about scheduling some task to repeat fixed number of times with predefined rate, this post could help you.

Title: JavaFX Auto Open new Window

Body:
I have A.fxml and B.fxml. A runing with Java Application override start method. I want to every 40 min in loop(5 times) { open new stage B.fxml and wait stage.close, if stage close continue loop open new stage B fxml. Loop this five times. I try timer timertask i could not. I try JavaFX Service i could not. I create Mythread extend Thread object. This time i could not control loop for next stage. When for statement start opening 5 stage. But i want to loop wait for currentstage is close then go next loop.  This is my fail code;

public class Driver extends Application {

public static Stage stage;

@Override
public void start(Stage primaryStage) throws Exception {
    FXMLLoader loader = new FXMLLoader(getClass().getResource(View.SETTINGS));
    Parent root = loader.load();
    Scene scene = new Scene(root);
    stage = primaryStage;
    stage.setScene(scene);
    stage.setTitle("Info Library");
    stage.setResizable(false);
    stage.show();
    RandomQuestionThread thread = new RandomQuestionThread();
    if (DBContext.settings.isAbbreviation() || DBContext.settings.isTranslation()) {
        thread.start();
    }
}

public static void main(String[] args) throws InterruptedException {
    DBContext.settings = DBContext.getInstance().settings().getSettings();

    launch(args);
    HibernateUtil.getSessionFactory().close();
}

}

public class RandomQuestionThread extends Thread {
Thread randomThread = new Thread(this);
private String fxml;
private static String TITLE;

@Override
public void run() {
    while (true) {
        try {
            Thread.sleep(DBContext.settings.getAutoQuestionTime() * 6000);
        } catch (InterruptedException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        for (int i = 0; i<DBContext.settings.getAutoQuestionCount(); i++) {
            randomFxml();
            Platform.runLater(()->{
                Parent root = null;
                try {
                    root = new FXMLLoader(getClass().getResource(fxml)).load();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                Stage stage = new Stage();
                stage.setScene(new Scene(root));
                stage.setTitle(TITLE);
                stage.show();
                System.out.println(currentThread().getName());
            });
        }
    }
}

private void randomFxml() {
    int start = 0;
    if (DBContext.settings.isTranslation() && DBContext.settings.isAbbreviation()) {
        start = new Random().nextInt(2);
    } else if (DBContext.settings.isTranslation()) {
        start = 1;
    }

    switch (start) {
    case 0:
        fxml = View.ABBREVIATION;
        break;
    case 1:
        fxml = View.TRANSLATION;
        break;

    default:
        break;
    }
    if (start == 0) {
        TITLE = "KISALTMA SORUSU";
    } else TITLE = "ÇEVİRİ SORUSU";
}

}

I need to work more Java multi threads. But after fix this problem. Please explain where I'm doing wrong. In loop write console currentThread name console result "Java Apllication Thread". But i set my thread name "MyThread". I'm so confused.My brain gave blue screen error.


问:
vb.net/pinvoke: enum specific process windows
Hello guys

i'm making a little app in which i need to enumerate all the windows of a specific process.

i managed to do that but through enumerating all the windows in the system and then just test if it is the process i'm talking about or not by using

```<code>GetWindowThreadProcessId(hwnd, proc)
Dim _Process = Process.GetProcessById(proc)
Dim _name = _Process.ProcessName
If (_name = "ProcessName") then
</code>```

but this method seem to take a lot of unnecessary time.
is there a wind32 function that can allow me to enumerate the windows of a specific process giving its handle.
thank you.

答:
You are already using GetWindowThreadProcessId().  That function returns a thread ID, you can use it with EnumThreadWindows() to get all the toplevel windows owned by the thread.  If necessary, EnumChildWindows() gets you the child windows owned by each toplevel window.

This approach does not give you windows that might be owned by any other thread in the process.  That's however quite rare and you typically don't want to know about them.  If that's a hangup then use Process.Threads to enumerate all the threads in the process, ProcessThread.Id gets you the thread ID.

Body:
Hello guys

i'm making a little app in which i need to enumerate all the windows of a specific process.

i managed to do that but through enumerating all the windows in the system and then just test if it is the process i'm talking about or not by using

GetWindowThreadProcessId(hwnd, proc)
Dim _Process = Process.GetProcessById(proc)
Dim _name = _Process.ProcessName
If (_name = "ProcessName") then

but this method seem to take a lot of unnecessary time.
is there a wind32 function that can allow me to enumerate the windows of a specific process giving its handle.
thank you.


问:
aria-labelledby not working with NVDA/Firefox
I need some help to make NVDA screen reader read a custom description of a math expression I've written in my index.html. The math expression is inside of a sentence. So it looks pretty much like this:

```<code><div>
  some text here...
  ε<sub>x</sub> = -200(10<sup>-6</sup>),
  ε<sub>y</sub> = 550(10<sup>-6</sup>),
  γ<sub>xy</sub> = 150(10<sup>-6</sup>)
  some more text here...
<div>
</code>```

The problem is that screen readers do not read the superscripts nor the minus symbols.

To fix this problem I added a aria-labelledby to add a custom description:

```<code><label id="label">Formula description here</label>
<div>
  some text here...
  <span aria-labelledby="label">
    ε<sub>x</sub> = -200(10<sup>-6</sup>),
    ...
  </span>
<div>
</code>```

It partially fixed the problem (only Voice Over/MacOS). But Windows/NVDA/Firefox does not work. It just ignore it.

I've tried using aria-label and aria-describedby but seems it does not work.
Thanks in advance.

答:
A browser / screen reader combo should ignore aria-label and/or aria-labelledby on a . You can see a bit more about what elements with those attributes are supported in which combinations here: ARIA support by user agent

Instead, your best bet is likely to use an off-screen technique. First the CSS to visually hide a thing but still leave it in the page for screen readers:

```<code>  .visually-hidden {
    position: absolute !important;
    clip: rect(1px 1px 1px 1px); /* IE6, IE7 */
    clip: rect(1px, 1px, 1px, 1px);
    padding:0 !important;
    border:0 !important;
    height: 1px !important;
    width: 1px !important;
    overflow: hidden;
  }
</code>```

Then you can put your alternative into a  and nobody will see it. Then the piece you do not want the screen reader to speak gets an aria-hidden:

```<code>  <p>
    some text here...
    <span class="visually-hidden">Formula description</span>
    <span aria-hidden="true">
      ε<sub>x</sub> = -200(10<sup>-6</sup>),
      ...
    </span>
  <p>
</code>```

That should do it for you.

Body:
I need some help to make NVDA screen reader read a custom description of a math expression I've written in my index.html. The math expression is inside of a sentence. So it looks pretty much like this:

  some text here...
  εx = -200(10-6),
  εy = 550(10-6),
  γxy = 150(10-6)
  some more text here...

The problem is that screen readers do not read the superscripts nor the minus symbols.

To fix this problem I added a aria-labelledby to add a custom description:

Formula description here

  some text here...

    εx = -200(10-6),
    ...

It partially fixed the problem (only Voice Over/MacOS). But Windows/NVDA/Firefox does not work. It just ignore it.

I've tried using aria-label and aria-describedby but seems it does not work.
Thanks in advance.

Body:
A browser / screen reader combo should ignore aria-label and/or aria-labelledby on a <span>. You can see a bit more about what elements with those attributes are supported in which combinations here: ARIA support by user agent

Instead, your best bet is likely to use an off-screen technique. First the CSS to visually hide a thing but still leave it in the page for screen readers:

  .visually-hidden {
    position: absolute !important;
    clip: rect(1px 1px 1px 1px); /* IE6, IE7 */
    clip: rect(1px, 1px, 1px, 1px);
    padding:0 !important;
    border:0 !important;
    height: 1px !important;
    width: 1px !important;
    overflow: hidden;
  }

Then you can put your alternative into a <span class="visually-hidden"> and nobody will see it. Then the piece you do not want the screen reader to speak gets an aria-hidden:

  <p>
    some text here...
    <span class="visually-hidden">Formula description</span>
    <span aria-hidden="true">
      &epsilon;<sub>x</sub> = -200(10<sup>-6</sup>),
      ...
    </span>
  <p>

That should do it for you.


问:
FadeOut element to FadeIn another in the same place with CSS animations
So I got a little circle shape with an icon that when I click, it will make the icon disappear and show a few elements in another div. The circle shape transforms into a 260x260 px square with CSS animation.

Until that I was fine, but I can't make the fadeIn/fadeOut work. Is there a way to handle this by toggling a CSS class over the parent element?

I can't just use opacity 0 to opacity 1 because I need the icon to really disappear with display none. Same for the other when going back to circle+icon state. But I just can't even make the opacity animation work. I also tried with those keyframes of fadeIn and fadeOut but didn't work either.

I found this fiddle but it looks so ugly having to use a setTimeout.

Is there a way to solve this with only CSS?

$('.toggle-btn').click(function() {
  $('.parent').toggleClass('expanded');
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.parent {
  width: 40px;
  height: 40px;
  background-color: lightgray;
  -webkit-border-radius: 50%;
  -moz-border-radius: 50%;
  border-radius: 50%;
  position: fixed;
  left: 11px;
  bottom: 18px;
  text-align: center;
  transition: all 500ms;
  -webkit-transition: all 500ms;
  -moz-transition: all 500ms;
}

.parent.expanded {
  width: 200px;
  height: 200px;
  border-radius: 0 14px 0 0;
  left: 0;
  bottom: 0;
}

.children-1 {
  display: block;
  animation: opacity-up 500ms linear 700ms 1;
  animation-fill-mode: forwards;
}

.help {
  width: 21px;
  height: 21px;
  position: relative;
  top: 9px;
}

.children-2 {
  display: none;
  animation: opacity-down 500ms linear 700ms 1;
  animation-fill-mode: forwards;
}

.parent.expanded .children-1 {
  animation: opacity-down 500ms linear 700ms 1;
  animation-fill-mode: forwards;
  display: none;
}

.parent.expanded .children-2 {
  animation: opacity-up 500ms linear 700ms 1;
  animation-fill-mode: forwards;
  display: block;
}

@keyframes opacity-down {
  0% {
   visibility: visible;
    opacity: 1;
  }
  100% {
   opacity: 0;
   visibility: hidden;
  }
}

@keyframes opacity-up {
  0% {
    opacity: 0;
    visibility: hidden;
  }
  100% {
   opacity: 1;
   visibility: visible;
  }
}

/*
@-webkit-keyframes fadeIn {
  0% { opacity: 0;
    visibility: hidden;
    display: none;  }
  100% { opacity: 1;
    visibility: visible;
    display: block; }
}

@keyframes fadeIn {
  0% { opacity: 0;
    visibility: hidden;
    display: none;  }
  100% { opacity: 1;
    visibility: visible;
    display: block; }
}

@-webkit-keyframes fadeOut {
  0% { opacity: 1;
    visibility: visible;
    display: block; }
  100% { opacity: 0;
    visibility: hidden;
    display: none; }
}

@keyframes fadeOut {
  0% { opacity: 1;
    visibility: visible;
    display: block; }
  100% { opacity: 0;
    visibility: hidden;
    display: none;  }
}*/</code>```

      Here is some content+inputs+other stuff, Here is some content+inputs+other stuff

<button class="toggle-btn">TOGGLE!</button>```

答:
Until that I was fine, but I can't make the fadeIn/fadeOut work. Is
  there a way to handle this by toggling a CSS class over the parent
  element?

You can do this without animation with toggle classes

$('.toggle-btn').click(function() {
  $('.parent').toggleClass('expanded');
  $('.children-2').toggleClass('show1');
  $('.children-1').toggleClass('show2');
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.parent {
  width: 40px;
  height: 40px;
  background-color: lightgray;
  -webkit-border-radius: 50%;
  -moz-border-radius: 50%;
  border-radius: 50%;
  position: fixed;
  left: 11px;
  bottom: 18px;
  text-align: center;
  transition: all 500ms;
  -webkit-transition: all 500ms;
  -moz-transition: all 500ms;
}

.parent.expanded {
  width: 200px;
  height: 200px;
  border-radius: 0 14px 0 0;
  left: 0;
  bottom: 0;
}

.children-1 {
  display: block;
  animation: opacity-up 500ms lineal 0s 1;
  animation-fill-mode: forwards;
}

.help {
  width: 21px;
  height: 21px;
  position: relative;
  top: 9px;
}

.children-2 {
  opacity: 0;
  transition: opacity 1s;
}

.children-1 {
  opacity: 1;
  transition: opacity 1s;
}

.show1 {
  opacity: 1;
}

.show2 {
  opacity: 1;
}

.parent.expanded .children-1 {
  animation: opacity-down 500ms lineal 0s 1;
  animation-fill-mode: forwards;
  display: none;
}

.parent.expanded .children-2 {
  animation: opacity-up 500ms lineal 0s 1;
  animation-fill-mode: forwards;
  display: block;
}</code>```

      Here is some content+inputs+other stuff, Here is some content+inputs+other stuff

<button class="toggle-btn">TOGGLE!</button>```

Body:
So I got a little circle shape with an icon that when I click, it will make the icon disappear and show a few elements in another div. The circle shape transforms into a 260x260 px square with CSS animation.

Until that I was fine, but I can't make the fadeIn/fadeOut work. Is there a way to handle this by toggling a CSS class over the parent element?

I can't just use opacity 0 to opacity 1 because I need the icon to really disappear with display none. Same for the other when going back to circle+icon state. But I just can't even make the opacity animation work. I also tried with those keyframes of fadeIn and fadeOut but didn't work either.

I found this fiddle but it looks so ugly having to use a setTimeout.

Is there a way to solve this with only CSS?

$('.toggle-btn').click(function() {
  $('.parent').toggleClass('expanded');
});

.parent {
  width: 40px;
  height: 40px;
  background-color: lightgray;
  -webkit-border-radius: 50%;
  -moz-border-radius: 50%;
  border-radius: 50%;
  position: fixed;
  left: 11px;
  bottom: 18px;
  text-align: center;
  transition: all 500ms;
  -webkit-transition: all 500ms;
  -moz-transition: all 500ms;
}

.parent.expanded {
  width: 200px;
  height: 200px;
  border-radius: 0 14px 0 0;
  left: 0;
  bottom: 0;
}

.children-1 {
  display: block;
  animation: opacity-up 500ms linear 700ms 1;
  animation-fill-mode: forwards;
}

.help {
  width: 21px;
  height: 21px;
  position: relative;
  top: 9px;
}

.children-2 {
  display: none;
  animation: opacity-down 500ms linear 700ms 1;
  animation-fill-mode: forwards;
}

.parent.expanded .children-1 {
  animation: opacity-down 500ms linear 700ms 1;
  animation-fill-mode: forwards;
  display: none;
}

.parent.expanded .children-2 {
  animation: opacity-up 500ms linear 700ms 1;
  animation-fill-mode: forwards;
  display: block;
}

@keyframes opacity-down {
  0% {
   visibility: visible;
    opacity: 1;
  }
  100% {
   opacity: 0;
   visibility: hidden;
  }
}

@keyframes opacity-up {
  0% {
    opacity: 0;
    visibility: hidden;
  }
  100% {
   opacity: 1;
   visibility: visible;
  }
}

/*
@-webkit-keyframes fadeIn {
  0% { opacity: 0;
    visibility: hidden;
    display: none;  }
  100% { opacity: 1;
    visibility: visible;
    display: block; }
}

@keyframes fadeIn {
  0% { opacity: 0;
    visibility: hidden;
    display: none;  }
  100% { opacity: 1;
    visibility: visible;
    display: block; }
}

@-webkit-keyframes fadeOut {
  0% { opacity: 1;
    visibility: visible;
    display: block; }
  100% { opacity: 0;
    visibility: hidden;
    display: none; }
}

@keyframes fadeOut {
  0% { opacity: 1;
    visibility: visible;
    display: block; }
  100% { opacity: 0;
    visibility: hidden;
    display: none;  }
}*/

      Here is some content+inputs+other stuff, Here is some content+inputs+other stuff

<button class="toggle-btn">TOGGLE!</button>

Body:
Until that I was fine, but I can't make the fadeIn/fadeOut work. Is
  there a way to handle this by toggling a CSS class over the parent
  element?

You can do this without animation with toggle classes

$('.toggle-btn').click(function() {
  $('.parent').toggleClass('expanded');
  $('.children-2').toggleClass('show1');
  $('.children-1').toggleClass('show2');
});

.parent {
  width: 40px;
  height: 40px;
  background-color: lightgray;
  -webkit-border-radius: 50%;
  -moz-border-radius: 50%;
  border-radius: 50%;
  position: fixed;
  left: 11px;
  bottom: 18px;
  text-align: center;
  transition: all 500ms;
  -webkit-transition: all 500ms;
  -moz-transition: all 500ms;
}

.parent.expanded {
  width: 200px;
  height: 200px;
  border-radius: 0 14px 0 0;
  left: 0;
  bottom: 0;
}

.children-1 {
  display: block;
  animation: opacity-up 500ms lineal 0s 1;
  animation-fill-mode: forwards;
}

.help {
  width: 21px;
  height: 21px;
  position: relative;
  top: 9px;
}

.children-2 {
  opacity: 0;
  transition: opacity 1s;
}

.children-1 {
  opacity: 1;
  transition: opacity 1s;
}

.show1 {
  opacity: 1;
}

.show2 {
  opacity: 1;
}

.parent.expanded .children-1 {
  animation: opacity-down 500ms lineal 0s 1;
  animation-fill-mode: forwards;
  display: none;
}

.parent.expanded .children-2 {
  animation: opacity-up 500ms lineal 0s 1;
  animation-fill-mode: forwards;
  display: block;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent">
  <div class="children-1">
    <img class="help" src="http://media1.calvinklein.com/images/static/e-comm/icons/questionMark.png" />
  </div>
  <div class="children-2">
    <p class="paragraph">
      Here is some content+inputs+other stuff, Here is some content+inputs+other stuff
    </p>
  </div>
</div>

<button class="toggle-btn">TOGGLE!</button>


问:
Need to associate unique integer value with classes
Alright, so I have a base class which we'll call TFruit. From this there are various descendants like TApple, TOrange and so on. I need to save the properties of the descendant classes to a file.

In order to be able to create the right class when loading the data, each class needs to have an ID that I write to the file before writing the actual data. Currently, I've come up with the following way of doing it:

```<code>type
  TFruit = class
    const ID = 0;
  end;

  TApple = class(TFruit)
    const ID = 1;
  end;

  TOrange = class(TFruit)
    const ID = 2;
  end;
</code>```

Testing this, I found out that I need to be super careful which class I declare. If I use this:

```<code>  var Fruit: TFruit;

  Fruit := TOrange.Create;
</code>```

...then Fruit.ID will return zero. However, declaring Fruit as a TOrange will yield the expected result Fruit.ID = 2 (anyone know why?)

So basically, am I doing this right or is there a better way to do it? Having to create a class function and return a value from there seems very ugly by comparison (extra function declaration, implementation and code).

答:
anyone know why?

Because you're declaring a class field? TOrange inherits from TFruit, so it has the ID=0 field too. Then you override it with another ID=2 field. Now you have two of these. If you cast TOrange to TFruit then you're getting inherited field, this is precisely the way to access them.

If you're on Delphi 2010+, use attributes:

```<code>[ClassId(4)] TOrange = class(TFruit)
</code>```

But why do you need these IDs in the first place? You'll have to manually mark your every class type, this is prone to errors. Just use class name.

```<code>var t: TOrange;
begin
  writeFile(t.Classname, t.Data);
</code>```

If you're so concerned with space, keep a classname-id table at the beginning of the file and assign IDs dynamically as you go:

```<code>procedure WriteObject(c: TObject);
var id: integer;
begin
  if not GetAlreadyRegisteredClassnameId(c.Classname, id) then
    id := AddClassnameToTable(c.Classname);

  writeToCache(id, c.Data)
end;

procedure WriteFile()
var i: integer;
begin
  for i := 0 to ObjectCount-1 do
    WriteObject(objects[i]);
  OutputClassnameTableToFile;
  OutputObjectCacheToFile;
end;
</code>```

(Of course ignoring memory constraints here for demonstrative purposes, but it's easy to do this without memory cache too)

Body:
Alright, so I have a base class which we'll call TFruit. From this there are various descendants like TApple, TOrange and so on. I need to save the properties of the descendant classes to a file.

In order to be able to create the right class when loading the data, each class needs to have an ID that I write to the file before writing the actual data. Currently, I've come up with the following way of doing it:

type
  TFruit = class
    const ID = 0;
  end;

  TApple = class(TFruit)
    const ID = 1;
  end;

  TOrange = class(TFruit)
    const ID = 2;
  end;

Testing this, I found out that I need to be super careful which class I declare. If I use this:

  var Fruit: TFruit;

  Fruit := TOrange.Create;

...then Fruit.ID will return zero. However, declaring Fruit as a TOrange will yield the expected result Fruit.ID = 2 (anyone know why?)

So basically, am I doing this right or is there a better way to do it? Having to create a class function and return a value from there seems very ugly by comparison (extra function declaration, implementation and code).

Body:
anyone know why?

Because you're declaring a class field? TOrange inherits from TFruit, so it has the ID=0 field too. Then you override it with another ID=2 field. Now you have two of these. If you cast TOrange to TFruit then you're getting inherited field, this is precisely the way to access them.

If you're on Delphi 2010+, use attributes:

[ClassId(4)] TOrange = class(TFruit)

But why do you need these IDs in the first place? You'll have to manually mark your every class type, this is prone to errors. Just use class name.

var t: TOrange;
begin
  writeFile(t.Classname, t.Data);

If you're so concerned with space, keep a classname-id table at the beginning of the file and assign IDs dynamically as you go:

procedure WriteObject(c: TObject);
var id: integer;
begin
  if not GetAlreadyRegisteredClassnameId(c.Classname, id) then
    id := AddClassnameToTable(c.Classname);

  writeToCache(id, c.Data)
end;

procedure WriteFile()
var i: integer;
begin
  for i := 0 to ObjectCount-1 do
    WriteObject(objects[i]);
  OutputClassnameTableToFile;
  OutputObjectCacheToFile;
end;

(Of course ignoring memory constraints here for demonstrative purposes, but it's easy to do this without memory cache too)