问:
Best way to exclude results from a big db query in Laravel 5.2
I'm using Laravel 5.2 to build a big product inventory and I'm having trouble with the query that will show the products. Here's the example:

I have many products - above 20k to be exact in my DB. Most of them I want to show every day, but about 500-1000 I need to display only on certain days of the week.

Currenly I've reviewed the following methods, each with its drawbacks:

Create a table product_availability, where each row will contain product_id, weekday and available (true/false) colums. However with that structure I'd have 7 rows giving info for 1 product and the whole table would containg ~ 140 000 rows which I don't think its a good idea - because most of the products would be available every day anyway and only 500-1000 wouldn't.

My second guess was to simply add an 'availability' column to the products table, that will contain JSON string in the format:

{"mo": "true", "tu": "false", "we": "false", "th": "true", "fr": "false", "sa": "false", "su": "true"}

Then I'd make my query like so:

```<code>$weekday = date('N');
        switch ($weekday) {
            case '1':
                $builder->where('$availability->mo', 'true');
                break;
            case '2':
                $builder->where('$availability->tu', 'true');
                break;
            case '3':
                $builder->where('$availability->we', 'true');
                break;
            case '4':
                $builder->where('$availability->th', 'true');
                break;
            case '5':
                $builder->where('$availability->fr', 'true');
                break;
            case '6':
                $builder->where('$availability->sa', 'true');
                break;
            case '7':
                $builder->where('$availability->su', 'true');
                break;
        }
</code>```

But the problem IMO for this solution is that it is going to be slow and heavy method also.

My third guess is to work backwards, not to check if the product is available today, but to check on which day it isn't. This way I'd get all the products where 'availability' column would be null and for these that it isn to run an if statement and then add them somehow, but I don't know how to structure that either.

So my question is:

What would be the fastest query to get all the products that are available today, keeping in mind that only a very small fraction of them wouldn't be available (how to exclude them, maybe) ?

答:
I think your first option is the best solution to go with (albeit with some changes).

I would suggest a table structure for product_availability to be something like:

```<code>| id | product_id | mon | tue | wed | thu | fri | sat | sun |
| 1  |      13403 |   1 |   0 |   1 |   0 |   1 |   0 |   0 |
</code>```

Then you can query something like:

```<code>SELECT
  products.*
FROM
  products
LEFT JOIN
  product_availability
ON
  product_availability.product_id = products.id
WHERE
  # show if no entry here (i.e. always to be shown)
  product_availability.id IS NULL
  OR
  # only want to show specific days
  product_availability.id IS NOT NULL AND CASE
    WHEN DAYOFWEEK(CURDATE()) = 1 THEN `sun` = 1
    WHEN DAYOFWEEK(CURDATE()) = 2 THEN `mon` = 1
    WHEN DAYOFWEEK(CURDATE()) = 3 THEN `tue` = 1
    WHEN DAYOFWEEK(CURDATE()) = 4 THEN `wed` = 1
    WHEN DAYOFWEEK(CURDATE()) = 5 THEN `thu` = 1
    WHEN DAYOFWEEK(CURDATE()) = 6 THEN `fri` = 1
    WHEN DAYOFWEEK(CURDATE()) = 7 THEN `sat` = 1
  END
</code>```

This will show all products. If there is an entry for the product ID in product_availability then it will get the current day of week (you can replace this with another method if you would like) and see if the corresponding day has 1 to show it.

only a very small fraction of them wouldn't be available

In this case the you would only need to add an entry in product_availability.

Here is a fiddle: http://sqlfiddle.com/#!9/c2bbf1/3

Hope this helps :)

Edit: Some method you could use to convert to eloquent query:

```<code>  ->leftJoin('product_availability', 'products.id', '=', 'product_availability.product_id')
  ->whereNull('product_availability.id')
  ->orWhere(function ($query) {
    $query
      ->whereRaw('(product_availability.id IS NOT NULL AND CASE
        WHEN DAYOFWEEK(CURDATE()) = 1 THEN `sun` = 1
        WHEN DAYOFWEEK(CURDATE()) = 2 THEN `mon` = 1
        WHEN DAYOFWEEK(CURDATE()) = 3 THEN `tue` = 1
        WHEN DAYOFWEEK(CURDATE()) = 4 THEN `wed` = 1
        WHEN DAYOFWEEK(CURDATE()) = 5 THEN `thu` = 1
        WHEN DAYOFWEEK(CURDATE()) = 6 THEN `fri` = 1
        WHEN DAYOFWEEK(CURDATE()) = 7 THEN `sat` = 1
      END)');
  });
</code>```

Or you could just do DB::raw queries

Body:
I'm using Laravel 5.2 to build a big product inventory and I'm having trouble with the query that will show the products. Here's the example:

I have many products - above 20k to be exact in my DB. Most of them I want to show every day, but about 500-1000 I need to display only on certain days of the week.

Currenly I've reviewed the following methods, each with its drawbacks:

Create a table product_availability, where each row will contain product_id, weekday and available (true/false) colums. However with that structure I'd have 7 rows giving info for 1 product and the whole table would containg ~ 140 000 rows which I don't think its a good idea - because most of the products would be available every day anyway and only 500-1000 wouldn't.

My second guess was to simply add an 'availability' column to the products table, that will contain JSON string in the format:

{"mo": "true", "tu": "false", "we": "false", "th": "true", "fr": "false", "sa": "false", "su": "true"}

Then I'd make my query like so:

$weekday = date('N');
        switch ($weekday) {
            case '1':
                $builder->where('$availability->mo', 'true');
                break;
            case '2':
                $builder->where('$availability->tu', 'true');
                break;
            case '3':
                $builder->where('$availability->we', 'true');
                break;
            case '4':
                $builder->where('$availability->th', 'true');
                break;
            case '5':
                $builder->where('$availability->fr', 'true');
                break;
            case '6':
                $builder->where('$availability->sa', 'true');
                break;
            case '7':
                $builder->where('$availability->su', 'true');
                break;
        }

But the problem IMO for this solution is that it is going to be slow and heavy method also.

My third guess is to work backwards, not to check if the product is available today, but to check on which day it isn't. This way I'd get all the products where 'availability' column would be null and for these that it isn to run an if statement and then add them somehow, but I don't know how to structure that either.

So my question is:

What would be the fastest query to get all the products that are available today, keeping in mind that only a very small fraction of them wouldn't be available (how to exclude them, maybe) ?

Body:
I think your first option is the best solution to go with (albeit with some changes).

I would suggest a table structure for product_availability to be something like:

| id | product_id | mon | tue | wed | thu | fri | sat | sun |
| 1  |      13403 |   1 |   0 |   1 |   0 |   1 |   0 |   0 |

Then you can query something like:

SELECT
  products.*
FROM
  products
LEFT JOIN
  product_availability
ON
  product_availability.product_id = products.id
WHERE
  # show if no entry here (i.e. always to be shown)
  product_availability.id IS NULL
  OR
  # only want to show specific days
  product_availability.id IS NOT NULL AND CASE
    WHEN DAYOFWEEK(CURDATE()) = 1 THEN `sun` = 1
    WHEN DAYOFWEEK(CURDATE()) = 2 THEN `mon` = 1
    WHEN DAYOFWEEK(CURDATE()) = 3 THEN `tue` = 1
    WHEN DAYOFWEEK(CURDATE()) = 4 THEN `wed` = 1
    WHEN DAYOFWEEK(CURDATE()) = 5 THEN `thu` = 1
    WHEN DAYOFWEEK(CURDATE()) = 6 THEN `fri` = 1
    WHEN DAYOFWEEK(CURDATE()) = 7 THEN `sat` = 1
  END

This will show all products. If there is an entry for the product ID in product_availability then it will get the current day of week (you can replace this with another method if you would like) and see if the corresponding day has 1 to show it.

only a very small fraction of them wouldn't be available

In this case the you would only need to add an entry in product_availability.

Here is a fiddle: http://sqlfiddle.com/#!9/c2bbf1/3

Hope this helps :)

Edit: Some method you could use to convert to eloquent query:

  ->leftJoin('product_availability', 'products.id', '=', 'product_availability.product_id')
  ->whereNull('product_availability.id')
  ->orWhere(function ($query) {
    $query
      ->whereRaw('(product_availability.id IS NOT NULL AND CASE
        WHEN DAYOFWEEK(CURDATE()) = 1 THEN `sun` = 1
        WHEN DAYOFWEEK(CURDATE()) = 2 THEN `mon` = 1
        WHEN DAYOFWEEK(CURDATE()) = 3 THEN `tue` = 1
        WHEN DAYOFWEEK(CURDATE()) = 4 THEN `wed` = 1
        WHEN DAYOFWEEK(CURDATE()) = 5 THEN `thu` = 1
        WHEN DAYOFWEEK(CURDATE()) = 6 THEN `fri` = 1
        WHEN DAYOFWEEK(CURDATE()) = 7 THEN `sat` = 1
      END)');
  });

Or you could just do DB::raw queries


来源: stackexchange

问:
StoreKit In App Purchase invalid product identifiers
I am getting an empty array of product identifiers from SKProductsRequest.

I did the following steps:

Created a In App Purchase Test User account under 'Manage Users' in iTunes Connect

Created some in app purchase products under 'Manage Your In App Purchases'.

Loaded the app onto the iPhone, went to Settings → Store and logged out of the regular store

Set a breakpoint in the (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response callback

All the submitted Product ID's are in the response's invalidProductIdentifiers property. When submitting the request I tried both the Product IDs created during step 2 as well as those IDs prefixed with the Bundle ID.

Thanks in advance,

Raghu

答: I discovered today another thing that can cause this sort of problem. Some times, for strange reasons, the app gets corrupted and all tries to buy something end in error. I solved my problem deleting the app from the device, cleaning the build on Xcode and building it again to the device.</p>

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 2.5


问:
LINQ query nested loop with multiple select statements
I'm trying to generate XML, to create the nested XElements I am using LINQ.

However, I'm struggling to then create more nested elements based on the previous LINQ loop.

This is what I am trying:

```<code>List<MessageValues> desValues;

XElement xml = new XElement(ns + "Message_Name",
          new XAttribute(XNamespace.Xmlns + "i", nsi.NamespaceName),
              from sr in subNames
              select new XElement(sr),
              from v in desValues
              where v.SubRoot = sr //need a way of doing this
              select new XElement(v.Key, v.Value));
</code>```

Basically I need to know whether there's a way of nesting 2 LINQ loops but still selecting after each iteration.

Hope this makes enough sense..

答:
Try this:</p>

```<code>XElement xml =
    new XElement(
        ns + "Message_Name",
        new XAttribute(
            XNamespace.Xmlns + "i",
            nsi.NamespaceName),
        from sr in subNames
        select new XElement(sr),
        from sr in subNames
        from v in desValues
        where v.SubRoot = sr
        select new XElement(v.Key, v.Value));
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to generate XML, to create the nested XElements I am using LINQ.

However, I'm struggling to then create more nested elements based on the previous LINQ loop.

This is what I am trying:

List<MessageValues> desValues;

XElement xml = new XElement(ns + "Message_Name",
          new XAttribute(XNamespace.Xmlns + "i", nsi.NamespaceName),
              from sr in subNames
              select new XElement(sr),
              from v in desValues
              where v.SubRoot = sr //need a way of doing this
              select new XElement(v.Key, v.Value));

Basically I need to know whether there's a way of nesting 2 LINQ loops but still selecting after each iteration.

Hope this makes enough sense..

Body:
Try this:

XElement xml =
    new XElement(
        ns + "Message_Name",
        new XAttribute(
            XNamespace.Xmlns + "i",
            nsi.NamespaceName),
        from sr in subNames
        select new XElement(sr),
        from sr in subNames
        from v in desValues
        where v.SubRoot = sr
        select new XElement(v.Key, v.Value));


问:
Prolog - Creating a list
Need a hand here creating a list.  I need to return all possible combinations of prerequisites of courses, including the prerequisites of prerequisites.

Here are some rules and facts that I need to use, (Some provided, some I've created).

```<code>prereqFor(engg233, []).
prereqFor(encm339, [engg233]).
prereqFor(cpsc217, []).
prereqFor(cpsc219, [cpsc217]).
prereqFor(cpsc231, []).
prereqFor(cpsc233, [cpsc231]).
prereqFor(math271, [X]) :-
   member(X, [math211, math213]).
prereqFor(math273, []).
prereqFor(cpsc319, [C]) :-
   member(C, [cpsc219, cpsc233, cpsc235, encm339]).
prereqFor(cpsc331, [M, C]) :-
   member(M, [math271, math273]),
   member(C, [cpsc219, cpsc233, cpsc235, encm339]).
prereqFor(cpsc335, [C]) :-
   member(C, [cpsc319, cpsc331]).
</code>```

Now what I'm trying to do to accomplish this is two functions, one of which is a helper... And I can't seem to populate a list by using [H|T] or append... My current attempt:

```<code>allPrereqFor(Course, Prerequisites) :-
   prereqFor(Course, Prerequisites),
   creatingList(Course, Prerequisites, []).

creatingList(Course, Prerequisites, OnGoingList) :-
   append(Course, Prerequisites, myList).
</code>```

I also tried something like:

```<code>allPrereqFor(Course, Prerequisites) :-
   prereqFor(Course, Prerequisites),
   creatingList(Prerequisites, []).

creatingList(Addition, OnGoingList) :-
   [Addition | OnGoingList].
</code>```

I can't even get the most simple output before I even attempt a recursive case.

I have not listed every prereqFor function, but an example output would be:

```<code>| ?- allPrereqFor(cpsc331, X).
X = [cpsc217,cpsc219,math211,math271] ? ;
X = [cpsc231,cpsc233,math211,math271] ? ;
X = [consent235,cpsc235,math211,math271] ? ;
X = [encm339,engg233,math211,math271] ? ;
</code>```

Another attempt at a solution...

```<code>allPrereqFor(Course,[],Result) :-   append([Course],[],Result).
allPrereqFor(Course, X,Result) :-   prereqFor(Course, Y),
                                    Y=[H|T],
                                    allPrereqFor(H,X,Result).
</code>```

The trace:

```<code>| ?- allPrereqFor(cpsc331,X).
  1    1  Call: allPrereqFor(cpsc331,_23) ?
  1    1  Exit: allPrereqFor(cpsc331,[]) ?

X = [] ? ;
  1    1  Redo: allPrereqFor(cpsc331,[]) ?
  2    2  Call: prereqFor(cpsc331,_92) ?
  3    3  Call: member(_78,[math271,math273]) ?
  3    3  Exit: member(math271,[math271,math273]) ?
  4    3  Call: member(_80,[cpsc219,cpsc233,cpsc235,encm339]) ?
  4    3  Exit: member(cpsc219,[cpsc219,cpsc233,cpsc235,encm339]) ?
  2    2  Exit: prereqFor(cpsc331,[math271,cpsc219]) ?
  5    2  Call: allPrereqFor(math271,_23) ?
  5    2  Exit: allPrereqFor(math271,[]) ?
  1    1  Exit: allPrereqFor(cpsc331,[]) ?

X = [] ? ;
  1    1  Redo: allPrereqFor(cpsc331,[]) ?
  5    2  Redo: allPrereqFor(math271,[]) ?
</code>```

When I trace I can see that it's recursively hitting all the right courses, but it just keeps outputting:

```<code>X = [] ?;
</code>```

答:
If I understand your question correctly then:

You are looking to build a list of combinations based on and and or predicates.

For example

to take cpsc219 you would need to take

    cpsc217 and cpsc219

to take math271 you would need to take

    math211 and math271 or

    math213 and math271

In the link the example used a build of materials for a bike and build of materials for practical questions is similar to your prerequisites.

This answer will be using DCG because you are constructing list and with Prolog when working mostly with list DCG is preferred.

For the bike example the DCG rules only showed and DCG rules and after seeing your answer to my question in the comment you also need or DCG rules but those were not given in the bike example.

So just to review:
  In Prolog and is done with , (,/2) and or which can be done with ; (;/2) but is more commonly done with multiple DCG rules. Note that , and ; as mentioned here are not list operators but operators working on goals.

An example of the bike and DCG rule for drivechain.

```<code>drivechain --> crank, pedal, pedal, chain.
</code>```

Now the missing example of the or DCG rule implemented using multiple DCG rules

```<code>tire --> [dunlop].
tire --> [goodyear].
tire --> [yomoto].
</code>```

or implemented using ;

```<code>tire -->
    [dunlop]; [goodyear]; [yomoto].
</code>```

A working example of the and DCG rule:

```<code>?- drivechain(X,[]).
X = [crank, pedal, pedal, chain] ;
false.
</code>```

A working example of the or DCG rule:

```<code>?- tire(X,[]).
X = [dunlop] ;
X = [goodyear] ;
X = [yomoto] ;
false.
</code>```

So for your problem with math271 needing math211 or math213 the DCG rules would be:

```<code>math211 --> [math211].
math213 --> [math213].

math271 --> math211.
math271 --> math213.

?- math271(X,[]).
X = [math211] ;
X = [math213].
</code>```

Since you noted that this is an assignment in the original post I will take that to mean homework so I won't give a specific answer to your question but show you something similar using the bike example.

```<code>bike --> frame, drivechain, wheel, wheel.
wheel --> spokes, rim, hub, tire.

tire --> [dunlop].
tire --> [goodyear].
tire --> [yomoto].

drivechain --> crank, pedal, pedal, chain.

spokes --> [spokes].
crank --> [crank].
pedal --> [pedal].
chain --> [chain].
rim --> [rim].
hub --> [hub].
frame --> [frame].

?- bike(X,[]).
X = [frame, crank, pedal, pedal, chain, spokes, rim, hub, dunlop, spokes, rim, hub, dunlop] ;
X = [frame, crank, pedal, pedal, chain, spokes, rim, hub, dunlop, spokes, rim, hub, goodyear] ;
X = [frame, crank, pedal, pedal, chain, spokes, rim, hub, dunlop, spokes, rim, hub, yomoto] ;
X = [frame, crank, pedal, pedal, chain, spokes, rim, hub, goodyear, spokes, rim, hub, dunlop] ;
X = [frame, crank, pedal, pedal, chain, spokes, rim, hub, goodyear, spokes, rim, hub, goodyear] ;
X = [frame, crank, pedal, pedal, chain, spokes, rim, hub, goodyear, spokes, rim, hub, yomoto] ;
X = [frame, crank, pedal, pedal, chain, spokes, rim, hub, yomoto, spokes, rim, hub, dunlop] ;
X = [frame, crank, pedal, pedal, chain, spokes, rim, hub, yomoto, spokes, rim, hub, goodyear] ;
X = [frame, crank, pedal, pedal, chain, spokes, rim, hub, yomoto, spokes, rim, hub, yomoto].
</code>```

Notice that even though a tire is composed of three brands, there are 9 answers because there are two wheels each with a tire and each tire can be one of three brands thus 3 * 3 is 9.

SWI-Prolog specific:

Since some of these answers will be long and truncated with ... see this answer for help to see the entire answer without the .... In other words append ;false to the query and press w after the first answer, then press the space bar for more answers.

Since DCG is like syntactic sugar, to see the de-sugared DCG rules ( --> ) as predicates ( :- ) use listing/1, e.g.

```<code>?- listing(wheel).
wheel(A, E) :-
        spokes(A, B),
        rim(B, C),
        hub(C, D),
        tire(D, E).
true.
</code>```

As I noted in the comments, I see that @false is probably going to answer this. I learn from him so I fully expect his answer to be better than mine, but I am posting my answer because if anyone sees a problem with my answer and points it out then I will learn also.

===================================

A more elaborate bike example that can make a bicycle or a tricycle.

```<code>bike --> type.
type --> bicycle.
type --> tricycle.
bicycle --> bicycle_frame, bicycle_drivechain, wheel, wheel.
tricycle --> tricycle_frame, tricycle_drive, wheel, wheel, wheel.
wheel --> spokes, rim, hub, tire.
bicycle_drivechain --> crank, pedal, pedal, chain.
tricycle_drive --> crank, pedal, pedal.
bicycle_frame --> [bicycle_frame].
tricycle_frame --> [tricycle_frame].
tire --> [dunlop].
tire --> [goodyear].
tire --> [yomoto].
spokes --> [spokes].
crank --> [crank].
pedal --> [pedal].
chain --> [chain].
rim --> [rim].
hub --> [hub].

?- bike(X,[]);false.
X = [bicycle_frame, crank, pedal, pedal, chain, spokes, rim, hub, dunlop, spokes, rim, hub, dunlop] ;
X = [bicycle_frame, crank, pedal, pedal, chain, spokes, rim, hub, dunlop, spokes, rim, hub, goodyear] ;
X = [bicycle_frame, crank, pedal, pedal, chain, spokes, rim, hub, dunlop, spokes, rim, hub, yomoto] ;
X = [bicycle_frame, crank, pedal, pedal, chain, spokes, rim, hub, goodyear, spokes, rim, hub, dunlop] ;
X = [bicycle_frame, crank, pedal, pedal, chain, spokes, rim, hub, goodyear, spokes, rim, hub, goodyear] ;
X = [bicycle_frame, crank, pedal, pedal, chain, spokes, rim, hub, goodyear, spokes, rim, hub, yomoto] ;
X = [bicycle_frame, crank, pedal, pedal, chain, spokes, rim, hub, yomoto, spokes, rim, hub, dunlop] ;
X = [bicycle_frame, crank, pedal, pedal, chain, spokes, rim, hub, yomoto, spokes, rim, hub, goodyear] ;
X = [bicycle_frame, crank, pedal, pedal, chain, spokes, rim, hub, yomoto, spokes, rim, hub, yomoto] ;
X = [tricycle_frame, crank, pedal, pedal, spokes, rim, hub, dunlop, spokes, rim, hub, dunlop, spokes, rim, hub, dunlop] ;
X = [tricycle_frame, crank, pedal, pedal, spokes, rim, hub, dunlop, spokes, rim, hub, dunlop, spokes, rim, hub, goodyear] ;
X = [tricycle_frame, crank, pedal, pedal, spokes, rim, hub, dunlop, spokes, rim, hub, dunlop, spokes, rim, hub, yomoto] ;
X = [tricycle_frame, crank, pedal, pedal, spokes, rim, hub, dunlop, spokes, rim, hub, goodyear, spokes, rim, hub, dunlop] ;
X = [tricycle_frame, crank, pedal, pedal, spokes, rim, hub, dunlop, spokes, rim, hub, goodyear, spokes, rim, hub, goodyear] ;
X = [tricycle_frame, crank, pedal, pedal, spokes, rim, hub, dunlop, spokes, rim, hub, goodyear, spokes, rim, hub, yomoto] ;
X = [tricycle_frame, crank, pedal, pedal, spokes, rim, hub, dunlop, spokes, rim, hub, yomoto, spokes, rim, hub, dunlop] ;
X = [tricycle_frame, crank, pedal, pedal, spokes, rim, hub, dunlop, spokes, rim, hub, yomoto, spokes, rim, hub, goodyear] ;
X = [tricycle_frame, crank, pedal, pedal, spokes, rim, hub, dunlop, spokes, rim, hub, yomoto, spokes, rim, hub, yomoto] ;
X = [tricycle_frame, crank, pedal, pedal, spokes, rim, hub, goodyear, spokes, rim, hub, dunlop, spokes, rim, hub, dunlop] ;
X = [tricycle_frame, crank, pedal, pedal, spokes, rim, hub, goodyear, spokes, rim, hub, dunlop, spokes, rim, hub, goodyear] ;
X = [tricycle_frame, crank, pedal, pedal, spokes, rim, hub, goodyear, spokes, rim, hub, dunlop, spokes, rim, hub, yomoto] ;
X = [tricycle_frame, crank, pedal, pedal, spokes, rim, hub, goodyear, spokes, rim, hub, goodyear, spokes, rim, hub, dunlop] ;
X = [tricycle_frame, crank, pedal, pedal, spokes, rim, hub, goodyear, spokes, rim, hub, goodyear, spokes, rim, hub, goodyear] ;
X = [tricycle_frame, crank, pedal, pedal, spokes, rim, hub, goodyear, spokes, rim, hub, goodyear, spokes, rim, hub, yomoto] ;
X = [tricycle_frame, crank, pedal, pedal, spokes, rim, hub, goodyear, spokes, rim, hub, yomoto, spokes, rim, hub, dunlop] ;
X = [tricycle_frame, crank, pedal, pedal, spokes, rim, hub, goodyear, spokes, rim, hub, yomoto, spokes, rim, hub, goodyear] ;
X = [tricycle_frame, crank, pedal, pedal, spokes, rim, hub, goodyear, spokes, rim, hub, yomoto, spokes, rim, hub, yomoto] ;
X = [tricycle_frame, crank, pedal, pedal, spokes, rim, hub, yomoto, spokes, rim, hub, dunlop, spokes, rim, hub, dunlop] ;
X = [tricycle_frame, crank, pedal, pedal, spokes, rim, hub, yomoto, spokes, rim, hub, dunlop, spokes, rim, hub, goodyear] ;
X = [tricycle_frame, crank, pedal, pedal, spokes, rim, hub, yomoto, spokes, rim, hub, dunlop, spokes, rim, hub, yomoto] ;
X = [tricycle_frame, crank, pedal, pedal, spokes, rim, hub, yomoto, spokes, rim, hub, goodyear, spokes, rim, hub, dunlop] ;
X = [tricycle_frame, crank, pedal, pedal, spokes, rim, hub, yomoto, spokes, rim, hub, goodyear, spokes, rim, hub, goodyear] ;
X = [tricycle_frame, crank, pedal, pedal, spokes, rim, hub, yomoto, spokes, rim, hub, goodyear, spokes, rim, hub, yomoto] ;
X = [tricycle_frame, crank, pedal, pedal, spokes, rim, hub, yomoto, spokes, rim, hub, yomoto, spokes, rim, hub, dunlop] ;
X = [tricycle_frame, crank, pedal, pedal, spokes, rim, hub, yomoto, spokes, rim, hub, yomoto, spokes, rim, hub, goodyear] ;
X = [tricycle_frame, crank, pedal, pedal, spokes, rim, hub, yomoto, spokes, rim, hub, yomoto, spokes, rim, hub, yomoto] ;
false.
</code>```

Title: Prolog - Creating a list

Body:
Need a hand here creating a list.  I need to return all possible combinations of prerequisites of courses, including the prerequisites of prerequisites.

Here are some rules and facts that I need to use, (Some provided, some I've created).

prereqFor(engg233, []).
prereqFor(encm339, [engg233]).
prereqFor(cpsc217, []).
prereqFor(cpsc219, [cpsc217]).
prereqFor(cpsc231, []).
prereqFor(cpsc233, [cpsc231]).
prereqFor(math271, [X]) :-
   member(X, [math211, math213]).
prereqFor(math273, []).
prereqFor(cpsc319, [C]) :-
   member(C, [cpsc219, cpsc233, cpsc235, encm339]).
prereqFor(cpsc331, [M, C]) :-
   member(M, [math271, math273]),
   member(C, [cpsc219, cpsc233, cpsc235, encm339]).
prereqFor(cpsc335, [C]) :-
   member(C, [cpsc319, cpsc331]).

Now what I'm trying to do to accomplish this is two functions, one of which is a helper... And I can't seem to populate a list by using [H|T] or append... My current attempt:

allPrereqFor(Course, Prerequisites) :-
   prereqFor(Course, Prerequisites),
   creatingList(Course, Prerequisites, []).

creatingList(Course, Prerequisites, OnGoingList) :-
   append(Course, Prerequisites, myList).

I also tried something like:

allPrereqFor(Course, Prerequisites) :-
   prereqFor(Course, Prerequisites),
   creatingList(Prerequisites, []).

creatingList(Addition, OnGoingList) :-
   [Addition | OnGoingList].

I can't even get the most simple output before I even attempt a recursive case.

I have not listed every prereqFor function, but an example output would be:

| ?- allPrereqFor(cpsc331, X).
X = [cpsc217,cpsc219,math211,math271] ? ;
X = [cpsc231,cpsc233,math211,math271] ? ;
X = [consent235,cpsc235,math211,math271] ? ;
X = [encm339,engg233,math211,math271] ? ;

Another attempt at a solution...

allPrereqFor(Course,[],Result) :-   append([Course],[],Result).
allPrereqFor(Course, X,Result) :-   prereqFor(Course, Y),
                                    Y=[H|T],
                                    allPrereqFor(H,X,Result).

The trace:

| ?- allPrereqFor(cpsc331,X).
  1    1  Call: allPrereqFor(cpsc331,_23) ?
  1    1  Exit: allPrereqFor(cpsc331,[]) ?

X = [] ? ;
  1    1  Redo: allPrereqFor(cpsc331,[]) ?
  2    2  Call: prereqFor(cpsc331,_92) ?
  3    3  Call: member(_78,[math271,math273]) ?
  3    3  Exit: member(math271,[math271,math273]) ?
  4    3  Call: member(_80,[cpsc219,cpsc233,cpsc235,encm339]) ?
  4    3  Exit: member(cpsc219,[cpsc219,cpsc233,cpsc235,encm339]) ?
  2    2  Exit: prereqFor(cpsc331,[math271,cpsc219]) ?
  5    2  Call: allPrereqFor(math271,_23) ?
  5    2  Exit: allPrereqFor(math271,[]) ?
  1    1  Exit: allPrereqFor(cpsc331,[]) ?

X = [] ? ;
  1    1  Redo: allPrereqFor(cpsc331,[]) ?
  5    2  Redo: allPrereqFor(math271,[]) ?

When I trace I can see that it's recursively hitting all the right courses, but it just keeps outputting:

X = [] ?;

Body:
If I understand your question correctly then:

You are looking to build a list of combinations based on and and or predicates.

For example

to take cpsc219 you would need to take

    cpsc217 and cpsc219

to take math271 you would need to take

    math211 and math271 or

    math213 and math271

In the link the example used a build of materials for a bike and build of materials for practical questions is similar to your prerequisites.

This answer will be using DCG because you are constructing list and with Prolog when working mostly with list DCG is preferred.

For the bike example the DCG rules only showed and DCG rules and after seeing your answer to my question in the comment you also need or DCG rules but those were not given in the bike example.

So just to review:
  In Prolog and is done with , (,/2) and or which can be done with ; (;/2) but is more commonly done with multiple DCG rules. Note that , and ; as mentioned here are not list operators but operators working on goals.

An example of the bike and DCG rule for drivechain.

drivechain --> crank, pedal, pedal, chain.

Now the missing example of the or DCG rule implemented using multiple DCG rules

tire --> [dunlop].
tire --> [goodyear].
tire --> [yomoto].

or implemented using ;

tire -->
    [dunlop]; [goodyear]; [yomoto].

A working example of the and DCG rule:

?- drivechain(X,[]).
X = [crank, pedal, pedal, chain] ;
false.

A working example of the or DCG rule:

?- tire(X,[]).
X = [dunlop] ;
X = [goodyear] ;
X = [yomoto] ;
false.

So for your problem with math271 needing math211 or math213 the DCG rules would be:

math211 --> [math211].
math213 --> [math213].

math271 --> math211.
math271 --> math213.

?- math271(X,[]).
X = [math211] ;
X = [math213].

Since you noted that this is an assignment in the original post I will take that to mean homework so I won't give a specific answer to your question but show you something similar using the bike example.

bike --> frame, drivechain, wheel, wheel.
wheel --> spokes, rim, hub, tire.

tire --> [dunlop].
tire --> [goodyear].
tire --> [yomoto].

drivechain --> crank, pedal, pedal, chain.

spokes --> [spokes].
crank --> [crank].
pedal --> [pedal].
chain --> [chain].
rim --> [rim].
hub --> [hub].
frame --> [frame].

?- bike(X,[]).
X = [frame, crank, pedal, pedal, chain, spokes, rim, hub, dunlop, spokes, rim, hub, dunlop] ;
X = [frame, crank, pedal, pedal, chain, spokes, rim, hub, dunlop, spokes, rim, hub, goodyear] ;
X = [frame, crank, pedal, pedal, chain, spokes, rim, hub, dunlop, spokes, rim, hub, yomoto] ;
X = [frame, crank, pedal, pedal, chain, spokes, rim, hub, goodyear, spokes, rim, hub, dunlop] ;
X = [frame, crank, pedal, pedal, chain, spokes, rim, hub, goodyear, spokes, rim, hub, goodyear] ;
X = [frame, crank, pedal, pedal, chain, spokes, rim, hub, goodyear, spokes, rim, hub, yomoto] ;
X = [frame, crank, pedal, pedal, chain, spokes, rim, hub, yomoto, spokes, rim, hub, dunlop] ;
X = [frame, crank, pedal, pedal, chain, spokes, rim, hub, yomoto, spokes, rim, hub, goodyear] ;
X = [frame, crank, pedal, pedal, chain, spokes, rim, hub, yomoto, spokes, rim, hub, yomoto].

Notice that even though a tire is composed of three brands, there are 9 answers because there are two wheels each with a tire and each tire can be one of three brands thus 3 * 3 is 9.

SWI-Prolog specific:

Since some of these answers will be long and truncated with ... see this answer for help to see the entire answer without the .... In other words append ;false to the query and press w after the first answer, then press the space bar for more answers.

Since DCG is like syntactic sugar, to see the de-sugared DCG rules ( --> ) as predicates ( :- ) use listing/1, e.g.

?- listing(wheel).
wheel(A, E) :-
        spokes(A, B),
        rim(B, C),
        hub(C, D),
        tire(D, E).
true.

As I noted in the comments, I see that @false is probably going to answer this. I learn from him so I fully expect his answer to be better than mine, but I am posting my answer because if anyone sees a problem with my answer and points it out then I will learn also.

===================================

A more elaborate bike example that can make a bicycle or a tricycle.

bike --> type.
type --> bicycle.
type --> tricycle.
bicycle --> bicycle_frame, bicycle_drivechain, wheel, wheel.
tricycle --> tricycle_frame, tricycle_drive, wheel, wheel, wheel.
wheel --> spokes, rim, hub, tire.
bicycle_drivechain --> crank, pedal, pedal, chain.
tricycle_drive --> crank, pedal, pedal.
bicycle_frame --> [bicycle_frame].
tricycle_frame --> [tricycle_frame].
tire --> [dunlop].
tire --> [goodyear].
tire --> [yomoto].
spokes --> [spokes].
crank --> [crank].
pedal --> [pedal].
chain --> [chain].
rim --> [rim].
hub --> [hub].

?- bike(X,[]);false.
X = [bicycle_frame, crank, pedal, pedal, chain, spokes, rim, hub, dunlop, spokes, rim, hub, dunlop] ;
X = [bicycle_frame, crank, pedal, pedal, chain, spokes, rim, hub, dunlop, spokes, rim, hub, goodyear] ;
X = [bicycle_frame, crank, pedal, pedal, chain, spokes, rim, hub, dunlop, spokes, rim, hub, yomoto] ;
X = [bicycle_frame, crank, pedal, pedal, chain, spokes, rim, hub, goodyear, spokes, rim, hub, dunlop] ;
X = [bicycle_frame, crank, pedal, pedal, chain, spokes, rim, hub, goodyear, spokes, rim, hub, goodyear] ;
X = [bicycle_frame, crank, pedal, pedal, chain, spokes, rim, hub, goodyear, spokes, rim, hub, yomoto] ;
X = [bicycle_frame, crank, pedal, pedal, chain, spokes, rim, hub, yomoto, spokes, rim, hub, dunlop] ;
X = [bicycle_frame, crank, pedal, pedal, chain, spokes, rim, hub, yomoto, spokes, rim, hub, goodyear] ;
X = [bicycle_frame, crank, pedal, pedal, chain, spokes, rim, hub, yomoto, spokes, rim, hub, yomoto] ;
X = [tricycle_frame, crank, pedal, pedal, spokes, rim, hub, dunlop, spokes, rim, hub, dunlop, spokes, rim, hub, dunlop] ;
X = [tricycle_frame, crank, pedal, pedal, spokes, rim, hub, dunlop, spokes, rim, hub, dunlop, spokes, rim, hub, goodyear] ;
X = [tricycle_frame, crank, pedal, pedal, spokes, rim, hub, dunlop, spokes, rim, hub, dunlop, spokes, rim, hub, yomoto] ;
X = [tricycle_frame, crank, pedal, pedal, spokes, rim, hub, dunlop, spokes, rim, hub, goodyear, spokes, rim, hub, dunlop] ;
X = [tricycle_frame, crank, pedal, pedal, spokes, rim, hub, dunlop, spokes, rim, hub, goodyear, spokes, rim, hub, goodyear] ;
X = [tricycle_frame, crank, pedal, pedal, spokes, rim, hub, dunlop, spokes, rim, hub, goodyear, spokes, rim, hub, yomoto] ;
X = [tricycle_frame, crank, pedal, pedal, spokes, rim, hub, dunlop, spokes, rim, hub, yomoto, spokes, rim, hub, dunlop] ;
X = [tricycle_frame, crank, pedal, pedal, spokes, rim, hub, dunlop, spokes, rim, hub, yomoto, spokes, rim, hub, goodyear] ;
X = [tricycle_frame, crank, pedal, pedal, spokes, rim, hub, dunlop, spokes, rim, hub, yomoto, spokes, rim, hub, yomoto] ;
X = [tricycle_frame, crank, pedal, pedal, spokes, rim, hub, goodyear, spokes, rim, hub, dunlop, spokes, rim, hub, dunlop] ;
X = [tricycle_frame, crank, pedal, pedal, spokes, rim, hub, goodyear, spokes, rim, hub, dunlop, spokes, rim, hub, goodyear] ;
X = [tricycle_frame, crank, pedal, pedal, spokes, rim, hub, goodyear, spokes, rim, hub, dunlop, spokes, rim, hub, yomoto] ;
X = [tricycle_frame, crank, pedal, pedal, spokes, rim, hub, goodyear, spokes, rim, hub, goodyear, spokes, rim, hub, dunlop] ;
X = [tricycle_frame, crank, pedal, pedal, spokes, rim, hub, goodyear, spokes, rim, hub, goodyear, spokes, rim, hub, goodyear] ;
X = [tricycle_frame, crank, pedal, pedal, spokes, rim, hub, goodyear, spokes, rim, hub, goodyear, spokes, rim, hub, yomoto] ;
X = [tricycle_frame, crank, pedal, pedal, spokes, rim, hub, goodyear, spokes, rim, hub, yomoto, spokes, rim, hub, dunlop] ;
X = [tricycle_frame, crank, pedal, pedal, spokes, rim, hub, goodyear, spokes, rim, hub, yomoto, spokes, rim, hub, goodyear] ;
X = [tricycle_frame, crank, pedal, pedal, spokes, rim, hub, goodyear, spokes, rim, hub, yomoto, spokes, rim, hub, yomoto] ;
X = [tricycle_frame, crank, pedal, pedal, spokes, rim, hub, yomoto, spokes, rim, hub, dunlop, spokes, rim, hub, dunlop] ;
X = [tricycle_frame, crank, pedal, pedal, spokes, rim, hub, yomoto, spokes, rim, hub, dunlop, spokes, rim, hub, goodyear] ;
X = [tricycle_frame, crank, pedal, pedal, spokes, rim, hub, yomoto, spokes, rim, hub, dunlop, spokes, rim, hub, yomoto] ;
X = [tricycle_frame, crank, pedal, pedal, spokes, rim, hub, yomoto, spokes, rim, hub, goodyear, spokes, rim, hub, dunlop] ;
X = [tricycle_frame, crank, pedal, pedal, spokes, rim, hub, yomoto, spokes, rim, hub, goodyear, spokes, rim, hub, goodyear] ;
X = [tricycle_frame, crank, pedal, pedal, spokes, rim, hub, yomoto, spokes, rim, hub, goodyear, spokes, rim, hub, yomoto] ;
X = [tricycle_frame, crank, pedal, pedal, spokes, rim, hub, yomoto, spokes, rim, hub, yomoto, spokes, rim, hub, dunlop] ;
X = [tricycle_frame, crank, pedal, pedal, spokes, rim, hub, yomoto, spokes, rim, hub, yomoto, spokes, rim, hub, goodyear] ;
X = [tricycle_frame, crank, pedal, pedal, spokes, rim, hub, yomoto, spokes, rim, hub, yomoto, spokes, rim, hub, yomoto] ;
false.


问:
How to set the timeout of 'driver.get' for python selenium 3.8.0?
In selenium tests, you open a webpage using

```<code>from selenium import webdriver
driver = webdriver.Firefox()
driver.get("whateverpage.org.com")
</code>```

How can I set the timeout of this command for selenium version 3.8.0 and python 2.7.12?

答:
To set the time out for Page Loading you can induce the set_page_load_timeout(seconds).

set_page_load_timeout

Method Details

```<code>def set_page_load_timeout(self, time_to_wait):
    """
    Set the amount of time to wait for a page load to complete
    before throwing an error.
</code>```

Args

```<code>time_to_wait: The amount of time to wait
</code>```

Usage

```<code>driver.set_page_load_timeout(3)
</code>```

Example

```<code>from selenium import webdriver
from selenium.common.exceptions import TimeoutException

driver = webdriver.Chrome(executable_path=r'C:\Utility\BrowserDrivers\chromedriver.exe')
driver.set_page_load_timeout(2)
try :
    driver.get("https://www.booking.com/hotel/in/the-taj-mahal-palace-tower.html?label=gen173nr-1FCAEoggJCAlhYSDNiBW5vcmVmaGyIAQGYATG4AQbIAQzYAQHoAQH4AQKSAgF5qAID;sid=338ad58d8e83c71e6aa78c67a2996616;dest_id=-2092174;dest_type=city;dist=0;group_adults=2;hip_dst=1;hpos=1;room1=A%2CA;sb_price_type=total;srfid=ccd41231d2f37b82d695970f081412152a59586aX1;srpvid=c71751e539ea01ce;type=total;ucfs=1&#hotelTmpl")
    print("URL successfully Accessed")
    driver.quit()
except TimeoutException as e:
    print("Page load Timeout Occurred. Quitting !!!")
    driver.quit()
</code>```

Console Output

```<code>Page load Timeout Occurred. Quitting !!!
</code>```

Documentation

You can find a detailed discussion on pageLoadTimeout here pageLoadTimeout in Selenium not working

Deep Dive

As per Python 3.x if we don't handle the exception the following log messages are observed :

```<code>    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.TimeoutException: Message: timeout
  (Session info: chrome=62.0.3202.94)
  (Driver info: chromedriver=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f),platform=Windows NT 6.2.9200 x86_64)
</code>```

Body:
In selenium tests, you open a webpage using

from selenium import webdriver
driver = webdriver.Firefox()
driver.get("whateverpage.org.com")

How can I set the timeout of this command for selenium version 3.8.0 and python 2.7.12?

Body:
To set the time out for Page Loading you can induce the set_page_load_timeout(seconds).

set_page_load_timeout

Method Details

def set_page_load_timeout(self, time_to_wait):
    """
    Set the amount of time to wait for a page load to complete
    before throwing an error.

Args

time_to_wait: The amount of time to wait

Usage

driver.set_page_load_timeout(3)

Example

from selenium import webdriver
from selenium.common.exceptions import TimeoutException

driver = webdriver.Chrome(executable_path=r'C:\Utility\BrowserDrivers\chromedriver.exe')
driver.set_page_load_timeout(2)
try :
    driver.get("https://www.booking.com/hotel/in/the-taj-mahal-palace-tower.html?label=gen173nr-1FCAEoggJCAlhYSDNiBW5vcmVmaGyIAQGYATG4AQbIAQzYAQHoAQH4AQKSAgF5qAID;sid=338ad58d8e83c71e6aa78c67a2996616;dest_id=-2092174;dest_type=city;dist=0;group_adults=2;hip_dst=1;hpos=1;room1=A%2CA;sb_price_type=total;srfid=ccd41231d2f37b82d695970f081412152a59586aX1;srpvid=c71751e539ea01ce;type=total;ucfs=1&#hotelTmpl")
    print("URL successfully Accessed")
    driver.quit()
except TimeoutException as e:
    print("Page load Timeout Occurred. Quitting !!!")
    driver.quit()

Console Output

Page load Timeout Occurred. Quitting !!!

Documentation

You can find a detailed discussion on pageLoadTimeout here pageLoadTimeout in Selenium not working

Deep Dive

As per Python 3.x if we don't handle the exception the following log messages are observed :

    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.TimeoutException: Message: timeout
  (Session info: chrome=62.0.3202.94)
  (Driver info: chromedriver=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f),platform=Windows NT 6.2.9200 x86_64)


问:
Toolbar not showing at the top of the page in Tab Bar Based Application in iPhone
In my iPhone app, I am using a tab-bar based application as my basic application type.

I created one toolbar at the top of the page in FirstViewController of tab-bar based app.

Also I changed File's Owner Class to "FirstViewController" aqnd have connected the outlets to toolbar buttons.

Now the problem is that when I run the project I don't see any toolbar at the top my page.

What could be wrong?

答:
Got the answer.

All credit goes to Madhup.

Check Madhup's Comment below this Question. He is right because of tab bar the toolbar went out of the page and was hidden under status bar in iphone.

Tried moving it a little below and now I am able to see the toolbar. :)

Thanks Madhup!!

Hope this helps someone


问:
React: router link with param not working

My problem is passing ${file.id} to link, but when I navigate to that link, I only receive like this:

the ${file.id} is not get correct value.
But when I inspect the key of row, it can render correct.

What are my mising?

Thanks

答:
You are using the wrong quotes. String interpolation is not possible with single quotes or doublequotes. You have to use the backtick `

So

<Link to={'api/admin/blobManager/${file.id}'} />

should instead be

<Link to={`api/admin/blobManager/${file.id}`} />


问:
How to get to know cell position in dynamic Table Layout in android
Here I am using dynamic table layout but i am not able to get cell position. My question is "How to get to row and column position" in dynamic table Layout in android. Please help me.

Thanks.

```<code>for (int i = 1; i <= rows; i++) {

        TableRow row = new TableRow(this);
        row.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.WRAP_CONTENT));

        // inner for loop
        for (int j = 1; j <= cols; j++) {

             TextView tv = new TextView(this);
            tv.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
                     LayoutParams.WRAP_CONTENT));
            tv.setBackgroundResource(R.drawable.cell_shape);
            tv.setPadding(5, 5, 5, 5);
            tv.setId(j);
            tv.setText("R " + i + ", C" + j);

            //mOrangeToolTipView = mToolTipFrameLayout.showToolTipForView(toolTip, tv);
            tv.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(final View v) {

                    Log.d("Row and Column position ", v.getTouchables()+"");

                }
            });

            row.addView(tv);

        }

        table_layout.addView(row);

    }
</code>```

答:
Got stuck in same problem ...found a solution which worked for me but .....it is not applicable in all cases.

Changed this line :tv.setId(j);
To : tv.setId((i*100)+j);

Logic of how it works:

To get row index :  row_index = id/100;
To get column index : column_index = id%100;
Note : it works give i and j are 2 digit number.(Guess as it is indices to locate a textview in a tablelayout,it would be within 99 ,at max)

Body:
Here I am using dynamic table layout but i am not able to get cell position. My question is "How to get to row and column position" in dynamic table Layout in android. Please help me.

Thanks.

for (int i = 1; i <= rows; i++) {

        TableRow row = new TableRow(this);
        row.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.WRAP_CONTENT));

        // inner for loop
        for (int j = 1; j <= cols; j++) {

             TextView tv = new TextView(this);
            tv.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
                     LayoutParams.WRAP_CONTENT));
            tv.setBackgroundResource(R.drawable.cell_shape);
            tv.setPadding(5, 5, 5, 5);
            tv.setId(j);
            tv.setText("R " + i + ", C" + j);

            //mOrangeToolTipView = mToolTipFrameLayout.showToolTipForView(toolTip, tv);
            tv.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(final View v) {

                    Log.d("Row and Column position ", v.getTouchables()+"");

                }
            });

            row.addView(tv);

        }

        table_layout.addView(row);

    }


问:
How to clean a class correcly
I have a class with functions to read data files. When read the class stores this datas in public properties.

After that I write the content of the puplic properties into a database.

Then it repeates. This means I read again datas with this class.

Before it repeates I want to clean the class.

What is the best way to do it?

Is it better to clear the content of the public properties manually or is it better to dispose the class. Maybe this is the more elegant way to do it?

答:
What about Memento pattern? Might be useful for you:

https://www.codeproject.com/Articles/186184/Memento-Design-Pattern

Or, as already pointed out, you have 3 other good possibilities:
 - Create a method Clear() that sets properties to default value,
 - If you have some unmanaged resources, you can use IDisposable interface,
 - Create static readonly property holding Empty instance of the class and reassign it. But I would go with Memento/Clear way.

Title: How to clean a class correcly


问:
uwp: how to change background color of listview item based on its value?
Edit: UWP App is not 100% the same like the WPF App.

I have a uwp App with a ListView. In the ListView i use a DataTemplate with the class of Tests. It displays the name of the Test and Points.

What i want to accomplish is that a Trigger !? checks if the Points are greater than i.e.: 50 and then change the background color of the ListViewItem to red.

```<code>            <ListView.ItemTemplate>
                <DataTemplate x:DataType="data:Tests">
                    <Grid>
                        <TextBlock Text="{x:Bind Name}"  />
                        <TextBlock Text="{x:Bind Points}"  />
                    </Grid>
                </DataTemplate>
            </ListView.ItemTemplate>
</code>```

答: have a look at that full code snippet answer about alternate colors. </p>

Body:
Edit: UWP App is not 100% the same like the WPF App.

I have a uwp App with a ListView. In the ListView i use a DataTemplate with the class of Tests. It displays the name of the Test and Points.

What i want to accomplish is that a Trigger !? checks if the Points are greater than i.e.: 50 and then change the background color of the ListViewItem to red.

            <ListView.ItemTemplate>
                <DataTemplate x:DataType="data:Tests">
                    <Grid>
                        <TextBlock Text="{x:Bind Name}"  />
                        <TextBlock Text="{x:Bind Points}"  />
                    </Grid>
                </DataTemplate>
            </ListView.ItemTemplate>


问:
Ionic 3 : Close modal with phone's back button
I try to override the phone's back button in my Ionic App.

This code permit me to open a modal to close the App if I'm not in a page, else close the page.

But this doesn't allow me to close an opened modal. How can I detect if I'm in a modal to close it ?

```<code>platform.registerBackButtonAction(() => {

      let nav = app.getActiveNav();
      let activeView: ViewController = nav.getActive();
      console.log(activeView);

      if(activeView != null){
        if(nav.canGoBack()) {
          activeView.dismiss();
        } else{
          let alert = this.alertCtrl.create({
            title: this.pdataManager.translate.get("close-app"),
            message: this.pdataManager.translate.get("sure-want-leave"),
            buttons: [
              {
                text: this.pdataManager.translate.get("no"),
                handler: () => {
                  this.presentedAlert = false;
                },
                role: 'cancel',
              },
              {
                text: this.pdataManager.translate.get("yes"),
                handler: () => {
                  this.presentedAlert = false;
                  this.platform.exitApp();
                }
              }
            ]
          });
          if(!this.presentedAlert) {
            alert.present();
            this.presentedAlert = true;
          }
        }
      }
    });
  }
</code>```

答:
1.Import IonicApp:

```<code>import {IonicApp } from 'ionic-angular';
</code>```

2.Add to your constructor:

```<code>  private ionicApp: IonicApp
</code>```

3.Inside your platform.registerBackButtonAction add:

```<code>let activeModal=this.ionicApp._modalPortal.getActive();
if(activeModal){
     activePortal.dismiss();
      return;
   }
</code>```

I found the answer here :
https://github.com/ionic-team/ionic/issues/6982

Body:
I try to override the phone's back button in my Ionic App.

This code permit me to open a modal to close the App if I'm not in a page, else close the page.

But this doesn't allow me to close an opened modal. How can I detect if I'm in a modal to close it ?

platform.registerBackButtonAction(() => {

      let nav = app.getActiveNav();
      let activeView: ViewController = nav.getActive();
      console.log(activeView);

      if(activeView != null){
        if(nav.canGoBack()) {
          activeView.dismiss();
        } else{
          let alert = this.alertCtrl.create({
            title: this.pdataManager.translate.get("close-app"),
            message: this.pdataManager.translate.get("sure-want-leave"),
            buttons: [
              {
                text: this.pdataManager.translate.get("no"),
                handler: () => {
                  this.presentedAlert = false;
                },
                role: 'cancel',
              },
              {
                text: this.pdataManager.translate.get("yes"),
                handler: () => {
                  this.presentedAlert = false;
                  this.platform.exitApp();
                }
              }
            ]
          });
          if(!this.presentedAlert) {
            alert.present();
            this.presentedAlert = true;
          }
        }
      }
    });
  }

Body:
1.Import IonicApp:

import {IonicApp } from 'ionic-angular';

2.Add to your constructor:

  private ionicApp: IonicApp

3.Inside your platform.registerBackButtonAction add:

let activeModal=this.ionicApp._modalPortal.getActive();
if(activeModal){
     activePortal.dismiss();
      return;
   }

I found the answer here :
https://github.com/ionic-team/ionic/issues/6982


问:
How to split an SQL Table into half and send the other half of the rows to new columns with SQL Query?
```<code>Country    Percentage

India      12%
USA        20%
Australia  15%
Qatar      10%
</code>```

Output :

```<code>Country1    Percentage1     Country2     Percentage2
India       12%             Australia    15%
USA         20%             Qatar        10%
</code>```

For example there is a table Country which has percentages, I need to divide the table in Half and show the remaining half (i.e. the remaining rows) in the new columns. I've also provided the table structure in text.

答:
I just wanted to try something. I have used the function OFFSET. It does the requirement i think for your sample data, but dont know if its bulletproof all the way:

SQL Code

```<code>declare @myt table (country nvarchar(50),percentage int)
insert into @myt
values
('India'      ,12),
('USA'        ,20),
('Australia'  ,15),
('Qatar'      ,10),
('Denmark',10)

DECLARE @TotalRows int
SET @TotalRows = (select CEILING(count(*) / 2.) from @myt);

WITH dataset1 AS (
SELECT *,ROW_NUMBER() over(order by country ) as rn from (
SELECT Country,percentage from @myt a
ORDER BY country OFFSET 0 rows FETCH FIRST @TotalRows ROWS ONLY
) z
)

,dataset2 AS (
SELECT *,ROW_NUMBER() over(order by country ) as rn from (
SELECT Country,percentage from @myt a
ORDER BY country OFFSET @TotalRows rows FETCH NEXT @TotalRows ROWS ONLY
) z
)

SELECT * FROM dataset1 a LEFT JOIN dataset2 b ON a.rn = b.rn
</code>```

Result

Body:
Country    Percentage

India      12%
USA        20%
Australia  15%
Qatar      10%

Output :

Country1    Percentage1     Country2     Percentage2
India       12%             Australia    15%
USA         20%             Qatar        10%

For example there is a table Country which has percentages, I need to divide the table in Half and show the remaining half (i.e. the remaining rows) in the new columns. I've also provided the table structure in text.

Body:
I just wanted to try something. I have used the function OFFSET. It does the requirement i think for your sample data, but dont know if its bulletproof all the way:

SQL Code

declare @myt table (country nvarchar(50),percentage int)
insert into @myt
values
('India'      ,12),
('USA'        ,20),
('Australia'  ,15),
('Qatar'      ,10),
('Denmark',10)

DECLARE @TotalRows int
SET @TotalRows = (select CEILING(count(*) / 2.) from @myt);

WITH dataset1 AS (
SELECT *,ROW_NUMBER() over(order by country ) as rn from (
SELECT Country,percentage from @myt a
ORDER BY country OFFSET 0 rows FETCH FIRST @TotalRows ROWS ONLY
) z
)

,dataset2 AS (
SELECT *,ROW_NUMBER() over(order by country ) as rn from (
SELECT Country,percentage from @myt a
ORDER BY country OFFSET @TotalRows rows FETCH NEXT @TotalRows ROWS ONLY
) z
)

SELECT * FROM dataset1 a LEFT JOIN dataset2 b ON a.rn = b.rn

Result


问:
Finding type hierarchy assemblies using Mono.Cecil
I am trying to implement a method that receives a type and returns all the assemblies that contain its base types.

For example:

Class A is a base type (class A belongs to assembly c:\A.dll)

Class B inherits from A (class B belongs to assembly c:\B.dll)

Class C inherits from B (class C belongs to assembly c:\c.dll)

```<code>public IEnumerable<string> GetAssembliesFromInheritance(string assembly,
                                                        string type)
{
    // If the method recieves type C from assembly c:\C.dll
    // it should return { "c:\A.dll", "c:\B.dll", "c:\C.dll" }
}
</code>```

My main problem is that AssemblyDefinition from Mono.Cecil does not contain any property like Location.

How can an assembly location be found given an AssemblyDefinition?

答:
An assembly can be composed of multiple modules, so it doesn't really have a location per se. The assembly's main module does have a location though:

```<code>AssemblyDefinition assembly = ...;
ModuleDefinition module = assembly.MainModule;
string fileName = module.FullyQualifiedName;
</code>```

So you could write something along the line of:

```<code>public IEnumerable<string> GetAssembliesFromInheritance (TypeDefinition type)
{
    while (type != null) {
        yield return type.Module.FullyQualifiedName;

        if (type.BaseType == null)
            yield break;

        type = type.BaseType.Resolve ();
    }
}
</code>```

Or any other variant which pleases you more.

Body:
I am trying to implement a method that receives a type and returns all the assemblies that contain its base types.

For example:

Class A is a base type (class A belongs to assembly c:\A.dll)

Class B inherits from A (class B belongs to assembly c:\B.dll)

Class C inherits from B (class C belongs to assembly c:\c.dll)

public IEnumerable<string> GetAssembliesFromInheritance(string assembly,
                                                        string type)
{
    // If the method recieves type C from assembly c:\C.dll
    // it should return { "c:\A.dll", "c:\B.dll", "c:\C.dll" }
}

My main problem is that AssemblyDefinition from Mono.Cecil does not contain any property like Location.

How can an assembly location be found given an AssemblyDefinition?

Body:
An assembly can be composed of multiple modules, so it doesn't really have a location per se. The assembly's main module does have a location though:

AssemblyDefinition assembly = ...;
ModuleDefinition module = assembly.MainModule;
string fileName = module.FullyQualifiedName;

So you could write something along the line of:

public IEnumerable<string> GetAssembliesFromInheritance (TypeDefinition type)
{
    while (type != null) {
        yield return type.Module.FullyQualifiedName;

        if (type.BaseType == null)
            yield break;

        type = type.BaseType.Resolve ();
    }
}

Or any other variant which pleases you more.


问:
How to make 2 dimensional array containing lists
I've got a type Package, and I want to make something like a rubic's cube. I want to make the floor with a 2-dimensional array and each entry will hold a list (3D).

Making my 2D array

```<code>Package[][] floor = new Package[x][y];
</code>```

And I've got my List of package, and want to make something like this

```<code>floor[i][j]= (new ArrayList <Package>()); in a loop
</code>```

Can someone explain why I've got the error message:

"Cannot convert Package to ArrayList Package"

On my lessons teacher said, I can do something like this.

答:
Your array is declared to store Package type objects.
I assume that you want to store Lists of Package objects in that array.

I found answer on Stack which tells that you cannot create arrays of parameterized objects. It means that you are unable to create array of lists.

Guy who answered thst question shows example of how to create ArrayList of ArrayLists. Using that example you should be able to create what you want.
You have to create 2D ArrayList of Lists.

Link to answer on stack

Body:
I've got a type Package, and I want to make something like a rubic's cube. I want to make the floor with a 2-dimensional array and each entry will hold a list (3D).

Making my 2D array

Package[][] floor = new Package[x][y];

And I've got my List of package, and want to make something like this

floor[i][j]= (new ArrayList <Package>()); in a loop

Can someone explain why I've got the error message:

"Cannot convert Package to ArrayList Package"

On my lessons teacher said, I can do something like this.


问:
Python/Socket: How to send multi messages without waiting the respond?
I want to send multi messages using socket module without waiting the respond from the client or server. However the codes that are below can not do this. What are your suggestions in order to do that? Thanks in advance.

Here are the codes:

server.py

```<code>#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("", 12345))
s.listen(1)
print(s)

c, addr = s.accept()
print('{} connected.'.format(addr))

while True:
    respond = input("Server: ").encode("utf-8")
    if respond == b"q":
        exit()
    else:
        c.sendall(bytes(respond))
        data = str(c.recv(1024))[1:]
        if data:
            print("Client: {}".format(data))
</code>```

client.py

```<code>#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("", 12345))

while True:
    respond = input("Client: ").encode("utf-8")
    if respond == b"q":
        exit()
    else:
        s.sendall(bytes(respond))
        data = str(s.recv(1024))[1:]
        if data:
            print("Server: {}".format(data))
</code>```

答:
Ok, so for what you want to achieve, you need to change the approach completely and use asyncio equivalents of socket methods as well as replacement for bare standard input handling.

The following code works on Python >= 3.5 and requires aioconsole Python package which can be installed with pip install aioconsole.

server.py

```<code>import asyncio
import aioconsole

class StreamWrapper(object):
    """This class is used to make socket stream created by server available for send_messgaes() function"""

    def __init__(self):
        self.reader = None
        self.writer = None

async def send_messages(stream_wrapper, stdin):
    # Wait asynchronously until server part initializes socket stream
    while stream_wrapper.writer is None:
        await asyncio.sleep(0.1)
    writer = stream_wrapper.writer
    # Asynchronusly read from standard input
    async for message in stdin:
        if message.decode().strip() == "q":
            writer.close()
            exit()
        else:
            # Send message through the socket
            writer.write(message)

def receive_messages_wrapper(stream_wrapper, stdout):
    """Wrapper function which adds stream_wrapper and stdout to the scope of receive_messages()"""
    async def receive_messages(reader, writer):
        # Copy socket stream reference to stream wrapper
        stream_wrapper.reader = reader
        stream_wrapper.writer = writer
        # Asynchronusly read messages from the socket
        async for message in reader:
            stdout.write('\nClient: {}'.format(message.decode()))
            stdout.write("Server: ")
    # Wrapper returns receive_messages function with enhanced scope - receive_messages() can "see" stream_wrapper and stdout
    return receive_messages

async def run_server(loop):
    """Initialize stdin and stdout asynchronous streams and start the server"""
    stdin, stdout = await aioconsole.get_standard_streams()
    stream_wrapper = StreamWrapper()
    # Asynchronously execute send_messages and start_server()
    await asyncio.gather(
        send_messages(stream_wrapper, stdin),
        asyncio.start_server(receive_messages_wrapper(stream_wrapper, stdout), '127.0.0.1', 8888, loop=loop)
    )

# Run the server on the event loop
loop = asyncio.get_event_loop()
loop.run_until_complete(run_server(loop))
loop.close()
</code>```

client.py

```<code>import asyncio
import aioconsole

async def send_messages(writer, stdin):
    # Asynchronusly read from standard input
    async for message in stdin:
        if message.decode().strip() == "q":
            writer.close()
            exit()
        else:
            # Send message through the socket
            writer.write(message)

async def receive_messages(reader, stdout):
    # Asynchronusly read messages from the socket
    async for message in reader:
        stdout.write('\nServer: {}'.format(message.decode()))
        stdout.write("Client: ")

async def run_client(loop):
    """Initialize stdin and stdout asynchronous streams and open the client connection, then start exchanging messages"""
    stdin, stdout = await aioconsole.get_standard_streams()
    reader, writer = await asyncio.open_connection('127.0.0.1', 8888)
    stdout.write("Client: ")
    # Asynchronously execute send_messages and receive_messages()
    await asyncio.gather(
        send_messages(writer, stdin),
        receive_messages(reader, stdout)
    )

# Run the client on the event loop
loop = asyncio.get_event_loop()
loop.run_until_complete(run_client(loop))
loop.close()
</code>```

This might seem complicated if you never used asyncio before but it does exactly what you want. You can spam multiple messages from any end (client or server) and the other end will receive it and print, while waiting for user input. I've provided comments but if you want to fully understand it, you should get familiar with asyncio documentation.
The other possible approaches involve using threads or multiprocessing. I wouldn't say they are easier than asyncio.

Body:
I want to send multi messages using socket module without waiting the respond from the client or server. However the codes that are below can not do this. What are your suggestions in order to do that? Thanks in advance.

Here are the codes:

server.py

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("", 12345))
s.listen(1)
print(s)

c, addr = s.accept()
print('{} connected.'.format(addr))

while True:
    respond = input("Server: ").encode("utf-8")
    if respond == b"q":
        exit()
    else:
        c.sendall(bytes(respond))
        data = str(c.recv(1024))[1:]
        if data:
            print("Client: {}".format(data))

client.py

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("", 12345))

while True:
    respond = input("Client: ").encode("utf-8")
    if respond == b"q":
        exit()
    else:
        s.sendall(bytes(respond))
        data = str(s.recv(1024))[1:]
        if data:
            print("Server: {}".format(data))

Body:
Ok, so for what you want to achieve, you need to change the approach completely and use asyncio equivalents of socket methods as well as replacement for bare standard input handling.

The following code works on Python >= 3.5 and requires aioconsole Python package which can be installed with pip install aioconsole.

server.py

import asyncio
import aioconsole

class StreamWrapper(object):
    """This class is used to make socket stream created by server available for send_messgaes() function"""

    def __init__(self):
        self.reader = None
        self.writer = None

async def send_messages(stream_wrapper, stdin):
    # Wait asynchronously until server part initializes socket stream
    while stream_wrapper.writer is None:
        await asyncio.sleep(0.1)
    writer = stream_wrapper.writer
    # Asynchronusly read from standard input
    async for message in stdin:
        if message.decode().strip() == "q":
            writer.close()
            exit()
        else:
            # Send message through the socket
            writer.write(message)

def receive_messages_wrapper(stream_wrapper, stdout):
    """Wrapper function which adds stream_wrapper and stdout to the scope of receive_messages()"""
    async def receive_messages(reader, writer):
        # Copy socket stream reference to stream wrapper
        stream_wrapper.reader = reader
        stream_wrapper.writer = writer
        # Asynchronusly read messages from the socket
        async for message in reader:
            stdout.write('\nClient: {}'.format(message.decode()))
            stdout.write("Server: ")
    # Wrapper returns receive_messages function with enhanced scope - receive_messages() can "see" stream_wrapper and stdout
    return receive_messages

async def run_server(loop):
    """Initialize stdin and stdout asynchronous streams and start the server"""
    stdin, stdout = await aioconsole.get_standard_streams()
    stream_wrapper = StreamWrapper()
    # Asynchronously execute send_messages and start_server()
    await asyncio.gather(
        send_messages(stream_wrapper, stdin),
        asyncio.start_server(receive_messages_wrapper(stream_wrapper, stdout), '127.0.0.1', 8888, loop=loop)
    )

# Run the server on the event loop
loop = asyncio.get_event_loop()
loop.run_until_complete(run_server(loop))
loop.close()

client.py

import asyncio
import aioconsole

async def send_messages(writer, stdin):
    # Asynchronusly read from standard input
    async for message in stdin:
        if message.decode().strip() == "q":
            writer.close()
            exit()
        else:
            # Send message through the socket
            writer.write(message)

async def receive_messages(reader, stdout):
    # Asynchronusly read messages from the socket
    async for message in reader:
        stdout.write('\nServer: {}'.format(message.decode()))
        stdout.write("Client: ")

async def run_client(loop):
    """Initialize stdin and stdout asynchronous streams and open the client connection, then start exchanging messages"""
    stdin, stdout = await aioconsole.get_standard_streams()
    reader, writer = await asyncio.open_connection('127.0.0.1', 8888)
    stdout.write("Client: ")
    # Asynchronously execute send_messages and receive_messages()
    await asyncio.gather(
        send_messages(writer, stdin),
        receive_messages(reader, stdout)
    )

# Run the client on the event loop
loop = asyncio.get_event_loop()
loop.run_until_complete(run_client(loop))
loop.close()

This might seem complicated if you never used asyncio before but it does exactly what you want. You can spam multiple messages from any end (client or server) and the other end will receive it and print, while waiting for user input. I've provided comments but if you want to fully understand it, you should get familiar with asyncio documentation.
The other possible approaches involve using threads or multiprocessing. I wouldn't say they are easier than asyncio.


问:
Getting back to my application after sending sms using intent
I have been searching for this, found many threads specifying on this. But things are not working for me. Tried setting "exit_on_sent" and also tried using startAcitivityForResult. Here is the code snippet I was trying with</p>

```<code>Intent sendIntent = new Intent(Intent.ACTION_VIEW);
sendIntent.setData(Uri.parse("smsto:" + phoneNumbers)); // phoneNumbers is a list of phone numbers to which i need to send messages at the same time
sendIntent.putExtra("sms_body", context.getResources().getString(R.string.message_body));
sendIntent.putExtra("exit_on_sent", true);
context.startActivity(sendIntent);
</code>```

答:
You can send SMS silently using SMSManager. as following : </p>

```<code>       try {

            String ph="1234568790";
            String msg="Hello";

            SmsManager smsManager = SmsManager.getDefault();
            smsManager.sendTextMessage(ph, null,msg, null, null);
            Toast.makeText(MainActivity.this, "Message Sent",
                    Toast.LENGTH_LONG).show();
        }
        catch (Exception e)
        {
            Toast.makeText(MainActivity.this, "Message not Sent",
                    Toast.LENGTH_LONG).show();
        }
</code>```

Body:
I have been searching for this, found many threads specifying on this. But things are not working for me. Tried setting "exit_on_sent" and also tried using startAcitivityForResult. Here is the code snippet I was trying with

Intent sendIntent = new Intent(Intent.ACTION_VIEW);
sendIntent.setData(Uri.parse("smsto:" + phoneNumbers)); // phoneNumbers is a list of phone numbers to which i need to send messages at the same time
sendIntent.putExtra("sms_body", context.getResources().getString(R.string.message_body));
sendIntent.putExtra("exit_on_sent", true);
context.startActivity(sendIntent);

Body:
You can send SMS silently using SMSManager. as following :

       try {

            String ph="1234568790";
            String msg="Hello";

            SmsManager smsManager = SmsManager.getDefault();
            smsManager.sendTextMessage(ph, null,msg, null, null);
            Toast.makeText(MainActivity.this, "Message Sent",
                    Toast.LENGTH_LONG).show();
        }
        catch (Exception e)
        {
            Toast.makeText(MainActivity.this, "Message not Sent",
                    Toast.LENGTH_LONG).show();
        }


问:
How to recursively walk tree with SimpleXMLIterator?
I have this sample code, why my code can find only test3 tag? Where are test and test2?

```<code>$iter = new RecursiveIteratorIterator(
    new SimpleXMLIterator(file_get_contents('./test.xml'))
);

foreach ($iter as $node) {
    echo "Tag found: ".$node->getName()."\n";
}
</code>```

test.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<test>
  <test2>
    <test3>dsfds</test3>
  </test2>
</test>
</code>```

答:
When using RecursiveIteratorIterator, the default mode is JUST to list the leaves(http://php.net/manual/en/recursiveiteratoriterator.construct.php).  If you change the construction to

```<code>$iter = new RecursiveIteratorIterator(
        new SimpleXMLIterator($xml)
        , RecursiveIteratorIterator::SELF_FIRST);
</code>```

This indicates to also list the various other parts of the structure and will output...

```<code>Tag found: test2
Tag found: test3
</code>```

Body:
I have this sample code, why my code can find only test3 tag? Where are test and test2?

$iter = new RecursiveIteratorIterator(
    new SimpleXMLIterator(file_get_contents('./test.xml'))
);

foreach ($iter as $node) {
    echo "Tag found: ".$node->getName()."\n";
}

test.xml

<?xml version="1.0" encoding="UTF-8"?>
<test>
  <test2>
    <test3>dsfds</test3>
  </test2>
</test>

Body:
When using RecursiveIteratorIterator, the default mode is JUST to list the leaves(http://php.net/manual/en/recursiveiteratoriterator.construct.php).  If you change the construction to

$iter = new RecursiveIteratorIterator(
        new SimpleXMLIterator($xml)
        , RecursiveIteratorIterator::SELF_FIRST);

This indicates to also list the various other parts of the structure and will output...

Tag found: test2
Tag found: test3


问:
html child element to extend over parent boundaries
Basically, as the title states, I want a child element to extend over the parent boundaries. This element is only visible when hovering its parent element.

I'm not allowed to share the whole css, so I tried to create a basic jsfiddle to demonstrate my problem here

Our layout looks something like:

```<code>   Fixed top bar
_____________________
S  |  Scrollable body
i  |
d  |
e  |
b  |
a  |
r  |
</code>```

where sidebar is also fixed. Sidebar contains multiple scrollable items.

.sidebar {
    width: 25%;
    position: fixed;
    display: flex;
    flex-direction: column;
}

.sidebar-item {
    display: flex;
    flex-direction: column;
    min-height: 0;
}

.body {
  overflow: auto;
}

.help {
    display: inline-block;
    position: relative;
    cursor: default;
    padding-right: 10px;
    z-index: 2;
}

span:hover + .help-text {
    transition: all 0.2s 0.4s;
    display: block;
    opacity: 1;
}

.help-text {
    display: none;
    opacity: 0;
    position: absolute;
    top: -5px;
    left: 10px;
    width: 300px;
    padding: 5px;
    font-size: 12px;
    background-color: black;
    color: white;
    white-space: pre-wrap;
    border-radius: 5px;
    z-index: 1500;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="sidebar">
  <div class="sidebar-item">
    <div class="body">
      <div class="help">
        <span>hover over me</span>
        <pre class="help-text">
          some test data
          some test data
          some test data
          some test data
          some test data
          some test data
          some test data
          some test data
          some test data
          some test data
          some test data
          some test data
          some test data
          some test data
        ```

      gvregrfvrtyewrfgvrtbh
      vgrewtghwrt
      frgerghrthbed
      hewrtgrhbrwwh

```

I want to avoid having the vertical and horizontal scrollbars and when the help text is shown it should go over the parent div's limits. z-index isn't working. Is this possible?

EDIT

Was able to get rid of the scrollbars when help-text is not shown by changing visibility to display, but still the text is shown inside parent container when hovered over

答:
try this:

I removed the width of the text-help and and hover in it to continue visible on reading.

.sidebar {
    width: 25%;
    position: fixed;
    display: flex;
    flex-direction: column;
}

.sidebar-item {
    display: flex;
    flex-direction: column;
    min-height: 0;
}

.body {
  overflow: auto;
}

.help {
    display: inline-block;
    position: relative;
    cursor: default;
    padding-right: 10px;
    z-index: 2;
}

span:hover + .help-text {
    transition: all 0.2s 0.4s;
    visibility: visible;
    opacity: 1;
}
.help-text:hover {
    transition: all 0.2s 0.4s;
    visibility: visible;
    opacity: 1;
}

.help-text {
    visibility: hidden;
    opacity: 0;
    position: absolute;
    top: -5px;
    left: 10px;
    padding: 5px;
    font-size: 12px;
    background-color: black;
    color: white;
    white-space: pre-wrap;
    border-radius: 5px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="sidebar">
  <div class="sidebar-item">
    <div class="body">
      <div class="help">
        <span>hover over me</span>
        <pre class="help-text">
          some test data
          some test data
          some test data
          some test data
          some test data
          some test data
          some test data
          some test data
          some test data
          some test data
          some test data
          some test data
          some test data
          some test data
        ```

      gvregrfvrtyewrfgvrtbh
      vgrewtghwrt
      frgerghrthbed
      hewrtgrhbrwwh

```

Body:
Basically, as the title states, I want a child element to extend over the parent boundaries. This element is only visible when hovering its parent element.

I'm not allowed to share the whole css, so I tried to create a basic jsfiddle to demonstrate my problem here

Our layout looks something like:

   Fixed top bar
_____________________
S  |  Scrollable body
i  |
d  |
e  |
b  |
a  |
r  |

where sidebar is also fixed. Sidebar contains multiple scrollable items.

.sidebar {
    width: 25%;
    position: fixed;
    display: flex;
    flex-direction: column;
}

.sidebar-item {
    display: flex;
    flex-direction: column;
    min-height: 0;
}

.body {
  overflow: auto;
}

.help {
    display: inline-block;
    position: relative;
    cursor: default;
    padding-right: 10px;
    z-index: 2;
}

span:hover + .help-text {
    transition: all 0.2s 0.4s;
    display: block;
    opacity: 1;
}

.help-text {
    display: none;
    opacity: 0;
    position: absolute;
    top: -5px;
    left: 10px;
    width: 300px;
    padding: 5px;
    font-size: 12px;
    background-color: black;
    color: white;
    white-space: pre-wrap;
    border-radius: 5px;
    z-index: 1500;
}

        hover over me

          some test data
          some test data
          some test data
          some test data
          some test data
          some test data
          some test data
          some test data
          some test data
          some test data
          some test data
          some test data
          some test data
          some test data

      gvregrfvrtyewrfgvrtbh
      vgrewtghwrt
      frgerghrthbed
      hewrtgrhbrwwh

I want to avoid having the vertical and horizontal scrollbars and when the help text is shown it should go over the parent div's limits. z-index isn't working. Is this possible?

EDIT

Was able to get rid of the scrollbars when help-text is not shown by changing visibility to display, but still the text is shown inside parent container when hovered over

Body:
try this:

I removed the width of the text-help and and hover in it to continue visible on reading.

.sidebar {
    width: 25%;
    position: fixed;
    display: flex;
    flex-direction: column;
}

.sidebar-item {
    display: flex;
    flex-direction: column;
    min-height: 0;
}

.body {
  overflow: auto;
}

.help {
    display: inline-block;
    position: relative;
    cursor: default;
    padding-right: 10px;
    z-index: 2;
}

span:hover + .help-text {
    transition: all 0.2s 0.4s;
    visibility: visible;
    opacity: 1;
}
.help-text:hover {
    transition: all 0.2s 0.4s;
    visibility: visible;
    opacity: 1;
}

.help-text {
    visibility: hidden;
    opacity: 0;
    position: absolute;
    top: -5px;
    left: 10px;
    padding: 5px;
    font-size: 12px;
    background-color: black;
    color: white;
    white-space: pre-wrap;
    border-radius: 5px;
}

<div class="sidebar">
  <div class="sidebar-item">
    <div class="body">
      <div class="help">
        <span>hover over me</span>
        <pre class="help-text">
          some test data
          some test data
          some test data
          some test data
          some test data
          some test data
          some test data
          some test data
          some test data
          some test data
          some test data
          some test data
          some test data
          some test data
        </pre>
      </div>
      gvregrfvrtyewrfgvrtbh
      vgrewtghwrt
      frgerghrthbed
      hewrtgrhbrwwh
    </div>
  </div>
</div>


问:
Rails - Images API for quick Resizing? Something like Google App Engine's Images Python API
Google's app engine has this speedy image resizing api which appears to perform significantly faster than the rails paperclip resizing alternative.

Anyone know of any rails/heroku friend image resizing api's that could work with paperclip to be a faster resizing solution?

Thanks

答: Paperclip itself doesn't include image-resizing code; it simply plugs into tools like ImageMagick and MiniMagick. Have you tried some of these other engines?</p>


问:
How to Sort List in Ascending Order by Firebase Childs (Numeric)?
```<code>ref.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {

                list = new ArrayList<>();
                for(DataSnapshot dataSnapshot1 :dataSnapshot.getChildren()){

                    Model userdetails = dataSnapshot1.getValue(Model.class);
                    Model listdata = new Model();

                    String name = userdetails.getName();
                    String points = userdetails.getPoints();

                    listdata.setName(name);
                    listdata.setPoints(points);
                    list.add(listdata);

                }

           try {
                Collections.sort(list, new Comparator<Model>() {
                    @Override
                    public int compare(Model lhs, Model rhs) {
                        int left = Integer.parseInt(rhs.getPoints());
                        int right = Integer.parseInt(lhs.getPoints());
                        return left - right;
                    }
                });
            } catch (Exception ignored){}

                Adapter recyclerview = new Adapter(list, getActivity());
                RecyclerView.LayoutManager layoutmanager = new LinearLayoutManager(getActivity());
                recycler.setLayoutManager(layoutmanager);
                recycler.setItemAnimator( new DefaultItemAnimator());
                recycler.setAdapter(recyclerview);

            }
</code>```

This is the code I'm using for retrieving data from firebase.

and below is the data.

I want to sort the data in ascending order but by the points. Maximum
  the point will be on first.

I've already posted a question about it and it did the trick, the list is sorted but after some items it becomes unsorted.

AND THE POST IMPORTANT THING IS THE LIST IS VERY VERY BIG.

I'll show you an example:

AFTER SORTED, AND SOME ITEMS LATER IT BECOMES UNSORTED.

Can Anyone help me? Thanks.

答:
try this one

```<code>Collections.sort(list, new Comparator<Model>() {
                @Override
                public int compare(Model lhs, Model rhs) {
                    int left = Integer.parseInt(rhs.getPoints());
                    int right = Integer.parseInt(lhs.getPoints());
                    return left - right;
                }
            });
</code>```

Replace to this

```<code>Collections.sort(list, new Comparator<Model>() {
                @Override
      public int compare(Model o1, Model o2) {
               return Integer.compare(o2.getPoints(), o1.getPoints());
   }
});
</code>```

Update:

```<code>Collections.sort(list, new Comparator<Model>() {
                    @Override
          public int compare(Model o1, Model o2) {
                   return Integer.compare(Integer.parseInt(o2.getPoints()), Integer.parseInt(o1.getPoints()));
       }
    });
</code>```

Please set exception see the below code : set break point and check any exception are fire or not

```<code>try {
      Collections.sort(list, new Comparator<Model>() {
          @Override
              public int compare(Model o1, Model o2) {
                       return Integer.compare(Integer.parseInt(o2.getPoints()), Integer.parseInt(o1.getPoints()));
           }
        });
   } catch (Exception ignored){
        ignored.getStackTrace();
   }
</code>```

Body:
ref.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {

                list = new ArrayList<>();
                for(DataSnapshot dataSnapshot1 :dataSnapshot.getChildren()){

                    Model userdetails = dataSnapshot1.getValue(Model.class);
                    Model listdata = new Model();

                    String name = userdetails.getName();
                    String points = userdetails.getPoints();

                    listdata.setName(name);
                    listdata.setPoints(points);
                    list.add(listdata);

                }

           try {
                Collections.sort(list, new Comparator<Model>() {
                    @Override
                    public int compare(Model lhs, Model rhs) {
                        int left = Integer.parseInt(rhs.getPoints());
                        int right = Integer.parseInt(lhs.getPoints());
                        return left - right;
                    }
                });
            } catch (Exception ignored){}

                Adapter recyclerview = new Adapter(list, getActivity());
                RecyclerView.LayoutManager layoutmanager = new LinearLayoutManager(getActivity());
                recycler.setLayoutManager(layoutmanager);
                recycler.setItemAnimator( new DefaultItemAnimator());
                recycler.setAdapter(recyclerview);

            }

This is the code I'm using for retrieving data from firebase.

and below is the data.

I want to sort the data in ascending order but by the points. Maximum
  the point will be on first.

I've already posted a question about it and it did the trick, the list is sorted but after some items it becomes unsorted.

AND THE POST IMPORTANT THING IS THE LIST IS VERY VERY BIG.

I'll show you an example:

AFTER SORTED, AND SOME ITEMS LATER IT BECOMES UNSORTED.

Can Anyone help me? Thanks.

Body:
try this one

Collections.sort(list, new Comparator<Model>() {
                @Override
                public int compare(Model lhs, Model rhs) {
                    int left = Integer.parseInt(rhs.getPoints());
                    int right = Integer.parseInt(lhs.getPoints());
                    return left - right;
                }
            });

Replace to this

Collections.sort(list, new Comparator<Model>() {
                @Override
      public int compare(Model o1, Model o2) {
               return Integer.compare(o2.getPoints(), o1.getPoints());
   }
});

Update:

Collections.sort(list, new Comparator<Model>() {
                    @Override
          public int compare(Model o1, Model o2) {
                   return Integer.compare(Integer.parseInt(o2.getPoints()), Integer.parseInt(o1.getPoints()));
       }
    });

Please set exception see the below code : set break point and check any exception are fire or not

try {
      Collections.sort(list, new Comparator<Model>() {
          @Override
              public int compare(Model o1, Model o2) {
                       return Integer.compare(Integer.parseInt(o2.getPoints()), Integer.parseInt(o1.getPoints()));
           }
        });
   } catch (Exception ignored){
        ignored.getStackTrace();
   }