问:
WordPress: get_post_type_object() return NULL for CPT
The function get_post_type_object() is returning NULL for my CPTs. For default post types, the informations is returned.

Here is one of my CPTs configuration:

```<code>function cptui_register_my_cpts_discurso() {

    /**
     * Post Type: Discursos.
     */

    $labels = array(
        "name" => __( "Discursos", "foo" ),
        "singular_name" => __( "Discurso", "foo" ),
    );

    $args = array(
        "label" => __( "Discursos", "foo" ),
        "labels" => $labels,
        "description" => "",
        "public" => true,
        "publicly_queryable" => true,
        "show_ui" => true,
        "show_in_rest" => true,
        "rest_base" => "",
        "has_archive" => true,
        "show_in_menu" => true,
        "exclude_from_search" => false,
        "capability_type" => "post",
        "map_meta_cap" => true,
        "hierarchical" => false,
        "rewrite" => array( "slug" => "discurso", "with_front" => true ),
        "query_var" => true,
        "menu_icon" => "dashicons-format-chat",
        "supports" => array( "title", "editor", "revisions", "author" ),
    );

    register_post_type( "discurso", $args );
}

add_action( 'init', 'cptui_register_my_cpts_discurso' );
</code>```

Getting post type object

```<code>$obj = get_post_type_object( 'discurso' );
</code>```

答:
Try to use it inside an action, it may be init or wp as follows,

```<code>function cptui_register_my_cpts_discurso(){
    ....
    ....
    register_post_type( "discurso", $args );

    // Get your object
    $obj = get_post_type_object( 'discurso' );
}
add_action( 'init', 'cptui_register_my_cpts_discurso' );
</code>```

Or try wp action

```<code>function just_another_function(){

    // Get your object
    $obj = get_post_type_object( 'discurso' );
}
add_action( 'wp', 'just_another_function' );
</code>```

Hope this once helps.

Body:
The function get_post_type_object() is returning NULL for my CPTs. For default post types, the informations is returned.

Here is one of my CPTs configuration:

function cptui_register_my_cpts_discurso() {

    /**
     * Post Type: Discursos.
     */

    $labels = array(
        "name" => __( "Discursos", "foo" ),
        "singular_name" => __( "Discurso", "foo" ),
    );

    $args = array(
        "label" => __( "Discursos", "foo" ),
        "labels" => $labels,
        "description" => "",
        "public" => true,
        "publicly_queryable" => true,
        "show_ui" => true,
        "show_in_rest" => true,
        "rest_base" => "",
        "has_archive" => true,
        "show_in_menu" => true,
        "exclude_from_search" => false,
        "capability_type" => "post",
        "map_meta_cap" => true,
        "hierarchical" => false,
        "rewrite" => array( "slug" => "discurso", "with_front" => true ),
        "query_var" => true,
        "menu_icon" => "dashicons-format-chat",
        "supports" => array( "title", "editor", "revisions", "author" ),
    );

    register_post_type( "discurso", $args );
}

add_action( 'init', 'cptui_register_my_cpts_discurso' );

Getting post type object

$obj = get_post_type_object( 'discurso' );

Body:
Try to use it inside an action, it may be init or wp as follows,

function cptui_register_my_cpts_discurso(){
    ....
    ....
    register_post_type( "discurso", $args );

    // Get your object
    $obj = get_post_type_object( 'discurso' );
}
add_action( 'init', 'cptui_register_my_cpts_discurso' );

Or try wp action

function just_another_function(){

    // Get your object
    $obj = get_post_type_object( 'discurso' );
}
add_action( 'wp', 'just_another_function' );

Hope this once helps.


来源: stackexchange

问:
Printing dictionary in a While Loop
I have been looking around to see if anyone has actually done it but couldn't find it so hoping I can get some help here.

```<code>newDict = {'Jan':31, 'Feb':29, 'Mar':31, 'Apr':30, 'May':31, 'Jun':30, 'Jul':31, 'Aug':30}
</code>```

I created this dict and I want to use a while loop to output it this way:

```<code>Jan 31
Feb 29
Mar 31
Apr 30
May 31
Jun 30
Jul 31
Aug 30
</code>```

I am able to do it with a for loop, just curious how it can be done with a while loop.

答:
Here's another option, using the .pop method.

```<code>newDict = {
    'Jan':31, 'Feb':29, 'Mar':31, 'Apr':30,
    'May':31, 'Jun':30, 'Jul':31, 'Aug':30
}
t = newDict.items()
while t:
    print '%s %d' % t.pop()
</code>```

typical output

```<code>Jul 31
Jun 30
Apr 30
Aug 30
Feb 29
Mar 31
May 31
Jan 31
</code>```

This code doesn't modify the contents of newDict, since in Python 2 dict.items() creates a list of the (key, value) pairs of the dictionary. In Python 3 it returns a dynamic View object, which doesn't have a .pop method, so this code won't work there.

Bear in mind that a dict is an unordered collection, so the output order may not be what you expect.

ContentLicense: CC BY-SA 3.0

Title: Printing dictionary in a While Loop

Body:
I have been looking around to see if anyone has actually done it but couldn't find it so hoping I can get some help here.

newDict = {'Jan':31, 'Feb':29, 'Mar':31, 'Apr':30, 'May':31, 'Jun':30, 'Jul':31, 'Aug':30}

I created this dict and I want to use a while loop to output it this way:

Jan 31
Feb 29
Mar 31
Apr 30
May 31
Jun 30
Jul 31
Aug 30

I am able to do it with a for loop, just curious how it can be done with a while loop.

Body:
Here's another option, using the .pop method.

newDict = {
    'Jan':31, 'Feb':29, 'Mar':31, 'Apr':30,
    'May':31, 'Jun':30, 'Jul':31, 'Aug':30
}
t = newDict.items()
while t:
    print '%s %d' % t.pop()

typical output

Jul 31
Jun 30
Apr 30
Aug 30
Feb 29
Mar 31
May 31
Jan 31

This code doesn't modify the contents of newDict, since in Python 2 dict.items() creates a list of the (key, value) pairs of the dictionary. In Python 3 it returns a dynamic View object, which doesn't have a .pop method, so this code won't work there.

Bear in mind that a dict is an unordered collection, so the output order may not be what you expect.


问:
How can I return the list of 2 first students in the list “s”?
I'm learning java. I have trouble when I return a list of 2 first students on the list s after I sort name by alphabet. Someone help me please, thank so much. Here is my code comparator and interface. </p>

```<code>@Override
public List<Student> f1(List<Student> s) {
   Collections.sort(s, new Comparator<Student>() {
       @Override
       public int compare(Student o1, Student o2) {
           return o1.getName().compareToIgnoreCase(o2.getName());
       }
   });
    return s;
}
 List<Student> f1(List<Student> s);
</code>```

答:
I have trouble when I return a list of 2 first students on the list s
  after I sort name by alphabet.

You need to return

```<code>return s.subList(0,2);
</code>```

where subList will give you the desired portion of list as List

Body:
I'm learning java. I have trouble when I return a list of 2 first students on the list s after I sort name by alphabet. Someone help me please, thank so much. Here is my code comparator and interface.

@Override
public List<Student> f1(List<Student> s) {
   Collections.sort(s, new Comparator<Student>() {
       @Override
       public int compare(Student o1, Student o2) {
           return o1.getName().compareToIgnoreCase(o2.getName());
       }
   });
    return s;
}
 List<Student> f1(List<Student> s);

Body:
I have trouble when I return a list of 2 first students on the list s
  after I sort name by alphabet.

You need to return

return s.subList(0,2);

where subList will give you the desired portion of list as List


问:
What does "-" do in Powershell
I'm new to powershell and I'm still trying to understand the syntax.
In a command like this

```<code>Get-ChildItem *.txt | Rename-Item -NewName { $_.name -Replace '\.txt$','.log' }
</code>```

What does - actually do?
Sometimes it is there, sometimes not, and I just don't understand what purpose it has xD

答:
In Powershell, All the parameters of a specific cmdlet has been defined to start with "-". It indicates the parameters are for the corresponding cmdlet.

All the cmdlets are functions that are written in Csharp or Powershell functions where they have defined the way to pass the argument of the parameters like:

```<code>Get-ChildItem *.txt | Rename-Item -NewName { $_.name -Replace '\.txt$','.log' }
</code>```

Get-Childitem is the cmdlet which has a -include paramater and whose value is **.txt*. So even though you have not given the parameter name , powershell has the capability to identify certain parameters value by native.
So that is the reason it is having no issue.

Similarly when you are piping the output of the first cmdlet to the second one (which is Rename-item) , it has a parameter -NewName whose value has been passed as an output of the entire {$_.name -Replace '.txt$','.log' }

Hope it helps you.

Title: What does "-" do in Powershell

Body:
I'm new to powershell and I'm still trying to understand the syntax.
In a command like this

Get-ChildItem *.txt | Rename-Item -NewName { $_.name -Replace '\.txt$','.log' }

What does - actually do?
Sometimes it is there, sometimes not, and I just don't understand what purpose it has xD

Body:
In Powershell, All the parameters of a specific cmdlet has been defined to start with "-". It indicates the parameters are for the corresponding cmdlet.

All the cmdlets are functions that are written in Csharp or Powershell functions where they have defined the way to pass the argument of the parameters like:

Get-ChildItem *.txt | Rename-Item -NewName { $_.name -Replace '\.txt$','.log' }

Get-Childitem is the cmdlet which has a -include paramater and whose value is **.txt*. So even though you have not given the parameter name , powershell has the capability to identify certain parameters value by native.
So that is the reason it is having no issue.

Similarly when you are piping the output of the first cmdlet to the second one (which is Rename-item) , it has a parameter -NewName whose value has been passed as an output of the entire {$_.name -Replace '.txt$','.log' }

Hope it helps you.


问:
Combination of for-loop and index slicing is not returning expected results
Apologies in advance, I loathe to ask such a newb question (this is the first language I'm learning) but there's clearly a gap in my understanding, and I can't find a link to any content which solves the issue I'm experiencing.

The below code defines 3 dictionaries, and an empty list. I then run a for loop to populate the list with 30 "Slow Aliens".

I then run another loop on the first 10 entries in the list in order to update that particular instance to a "Fast Alien" dictionary. However, I seem to be replacing every dictionary in the list.

Any help pointing me to some articles which discuss/solve/educate me further would be appreciatively received.

```<code>slow_alien = {
    "Name": "Slow Alien",
    "Colour": "Green",
    "Points": 10,
    "X Position": 15,
    "Y Position": 20,
    "Current Speed": "Slow",
    "Height": 1.8,
}
medium_alien = {
    "Name": "Medium Alien",
    "Colour": "Yellow",
    "Points": 15,
    "X Position": 30,
    "Y Position": 20,
    "Current Speed": "Medium",
    "Height": 2.2,
}
fast_alien = {
    "Name": "Fast Alien",
    "Colour": "Red",
    "Points": 20,
    "X Position": 45,
    "Y Position": 20,
    "Current Speed": "Fast",
    "Height": 2.6,
}
aliens = []

for alien in range(30):
    aliens.append(slow_alien)

for alien in aliens[:10]:
    if alien == slow_alien:
        alien.update(fast_alien)

for alien in aliens:
    for key, value in alien.items():
        print(str(key) + ": " + str(value))
    print("")
print("The aliens list contains " + str(len(aliens)) + " dictionaries")
</code>```

Thanks,

Carl.

答:
You said:

```<code>I then run a for loop to populate the list with 30 "Slow Aliens".
</code>```

But that's wrong, you actually populate the list with 1 slow alien thirty times.

If you actually wanted 30 of them you would have to make a copy when adding them to the list.

```<code>for alien in range(30):
    aliens.append(slow_alien.copy())
</code>```

Body:
Apologies in advance, I loathe to ask such a newb question (this is the first language I'm learning) but there's clearly a gap in my understanding, and I can't find a link to any content which solves the issue I'm experiencing.

The below code defines 3 dictionaries, and an empty list. I then run a for loop to populate the list with 30 "Slow Aliens".

I then run another loop on the first 10 entries in the list in order to update that particular instance to a "Fast Alien" dictionary. However, I seem to be replacing every dictionary in the list.

Any help pointing me to some articles which discuss/solve/educate me further would be appreciatively received.

slow_alien = {
    "Name": "Slow Alien",
    "Colour": "Green",
    "Points": 10,
    "X Position": 15,
    "Y Position": 20,
    "Current Speed": "Slow",
    "Height": 1.8,
}
medium_alien = {
    "Name": "Medium Alien",
    "Colour": "Yellow",
    "Points": 15,
    "X Position": 30,
    "Y Position": 20,
    "Current Speed": "Medium",
    "Height": 2.2,
}
fast_alien = {
    "Name": "Fast Alien",
    "Colour": "Red",
    "Points": 20,
    "X Position": 45,
    "Y Position": 20,
    "Current Speed": "Fast",
    "Height": 2.6,
}
aliens = []

for alien in range(30):
    aliens.append(slow_alien)

for alien in aliens[:10]:
    if alien == slow_alien:
        alien.update(fast_alien)

for alien in aliens:
    for key, value in alien.items():
        print(str(key) + ": " + str(value))
    print("")
print("The aliens list contains " + str(len(aliens)) + " dictionaries")

Thanks,

Carl.

Body:
You said:

I then run a for loop to populate the list with 30 "Slow Aliens".

But that's wrong, you actually populate the list with 1 slow alien thirty times.

If you actually wanted 30 of them you would have to make a copy when adding them to the list.

for alien in range(30):
    aliens.append(slow_alien.copy())


问:
Rearranging a sublist within a list
I am having a hard time rearanging a list of tuples of names, first and last. I want to sort the list by last name and if there are identical last names then the sublist of those names should be arranged by first name. The first part was pretty easy with sorted and key=get_key1 but I am having diffuculties to complete the second part of the problem.

A list like this:

```<code>[('Tom','Haim'),('Eli','Levi'),('Eli','Cohen'),('Moshe','Levi'),('Haim','Cohen'),('Dina','Ram'),('Tova','Ben'),('Ben','Levi'),('Gil','Cohen'),('Eli','Ram')]
</code>```

should come out like:

```<code>[('Tova', 'Ben'), ('Eli', 'Cohen'), ('Gil', 'Cohen'), ('Haim', 'Cohen'), ('Tom', 'Haim'), ('Ben', 'Levi'), ('Eli', 'Levi'), ('Moshe', 'Levi'), ('Dina', 'Ram'), ('Eli', 'Ram')]
</code>```

Best I got is:

```<code>[('Tova', 'Ben'), ('Eli', 'Cohen'), ('Haim', 'Cohen'), ('Gil', 'Cohen'), ('Tom', 'Haim'), ('Eli', 'Levi'), ('Moshe', 'Levi'), ('Ben', 'Levi'), ('Dina', 'Ram'), ('Eli', 'Ram')]
</code>```

Thank you

答:
You can sort the list of the fly using the sort() method of list:

```<code>inlist = [('Tom','Haim'),('Eli','Levi'),('Eli','Cohen'),('Moshe','Levi'),('Haim','Cohen'),('Dina','Ram'),('Tova','Ben'),('Ben','Levi'),('Gil','Cohen'),('Eli','Ram')]
inlist.sort(key = lambda i: (i[1],i[0]))
print(inlist)
</code>```

Output:

```<code>[('Tova', 'Ben'), ('Eli', 'Cohen'), ('Gil', 'Cohen'), ('Haim', 'Cohen'), ('Tom', 'Haim'), ('Ben', 'Levi'), ('Eli', 'Levi'), ('Moshe', 'Levi'), ('Dina', 'Ram'), ('Eli', 'Ram')]
</code>```

An alternative to lambda, suggested by @cezar would be itemgetter from the operator module:

```<code>from operator import itemgetter

inlist = [('Tom','Haim'),('Eli','Levi'),('Eli','Cohen'),('Moshe','Levi'),('Haim','Cohen'),('Dina','Ram'),('Tova','Ben'),('Ben','Levi'),('Gil','Cohen'),('Eli','Ram')]

inlist.sort(key = itemgetter(1,0))
print(inlist)
</code>```

Output:

```<code>[('Tova', 'Ben'), ('Eli', 'Cohen'), ('Gil', 'Cohen'), ('Haim', 'Cohen'), ('Tom', 'Haim'), ('Ben', 'Levi'), ('Eli', 'Levi'), ('Moshe', 'Levi'), ('Dina', 'Ram'), ('Eli', 'Ram')]
</code>```

Title: Rearranging a sublist within a list

Body:
I am having a hard time rearanging a list of tuples of names, first and last. I want to sort the list by last name and if there are identical last names then the sublist of those names should be arranged by first name. The first part was pretty easy with sorted and key=get_key1 but I am having diffuculties to complete the second part of the problem.

A list like this:

[('Tom','Haim'),('Eli','Levi'),('Eli','Cohen'),('Moshe','Levi'),('Haim','Cohen'),('Dina','Ram'),('Tova','Ben'),('Ben','Levi'),('Gil','Cohen'),('Eli','Ram')]

should come out like:

[('Tova', 'Ben'), ('Eli', 'Cohen'), ('Gil', 'Cohen'), ('Haim', 'Cohen'), ('Tom', 'Haim'), ('Ben', 'Levi'), ('Eli', 'Levi'), ('Moshe', 'Levi'), ('Dina', 'Ram'), ('Eli', 'Ram')]

Best I got is:

[('Tova', 'Ben'), ('Eli', 'Cohen'), ('Haim', 'Cohen'), ('Gil', 'Cohen'), ('Tom', 'Haim'), ('Eli', 'Levi'), ('Moshe', 'Levi'), ('Ben', 'Levi'), ('Dina', 'Ram'), ('Eli', 'Ram')]

Thank you

Body:
You can sort the list of the fly using the sort() method of list:

inlist = [('Tom','Haim'),('Eli','Levi'),('Eli','Cohen'),('Moshe','Levi'),('Haim','Cohen'),('Dina','Ram'),('Tova','Ben'),('Ben','Levi'),('Gil','Cohen'),('Eli','Ram')]
inlist.sort(key = lambda i: (i[1],i[0]))
print(inlist)

Output:

[('Tova', 'Ben'), ('Eli', 'Cohen'), ('Gil', 'Cohen'), ('Haim', 'Cohen'), ('Tom', 'Haim'), ('Ben', 'Levi'), ('Eli', 'Levi'), ('Moshe', 'Levi'), ('Dina', 'Ram'), ('Eli', 'Ram')]

An alternative to lambda, suggested by @cezar would be itemgetter from the operator module:

from operator import itemgetter

inlist = [('Tom','Haim'),('Eli','Levi'),('Eli','Cohen'),('Moshe','Levi'),('Haim','Cohen'),('Dina','Ram'),('Tova','Ben'),('Ben','Levi'),('Gil','Cohen'),('Eli','Ram')]

inlist.sort(key = itemgetter(1,0))
print(inlist)

Output:

[('Tova', 'Ben'), ('Eli', 'Cohen'), ('Gil', 'Cohen'), ('Haim', 'Cohen'), ('Tom', 'Haim'), ('Ben', 'Levi'), ('Eli', 'Levi'), ('Moshe', 'Levi'), ('Dina', 'Ram'), ('Eli', 'Ram')]


问:
Xcode - Target specific localization
My project includes several targets, each target is used for a different customer. Some customers need specific localization, and I don't want all the customers to get this specific localization. Since localization is handled on the project level, I couldn't find a way to add localization only for a specific target.

Any suggestions how to do it?

Looking for stable option without the need to delete unused localization before each build.

答:
I manage to solve it with @Yitzchak answer + additional changes:

In project level add the desired language.

Remove original localizable file from the target.

Create new Localizable.strings / InfoPlist.strings and add it to the target.

Select only the relevant languages in "localization" option (see the image below)

ContentLicense: CC BY-SA 4.0

Title: Xcode - Target specific localization


问:
Hibernate large collections performance problems despite using 2nd Level Cache
We have a parent object with a collection of 500.000 child objects. We are using Hibernate for mapping with ehcache as the cache provider. Using the 2nd level cache for entities and collection works fine as we can avoid requests to the database.

But loading 500.000 objects by 2nd level cache still produces a lot of cpu and memory garbage and results in a reponse time of a few seconds. As the child objects are not immutable we can't enable the hibernate.cache.use_reference_entries property.

With using an application layer cache of dao objects in top of the hibernate 2nd level cache, there's no cpu and no garbage memory overhead. The response time is a few milliseconds instead of seconds.

But the big disadvantage of this solution is, that we have to manage this cache by ourself. Including invalidation und synchronization in a clustered multithreading system.

My question is, if there's a better solution with the advantages of low cpu and garbage? Does anyone have experience in handling large collections?

答:
Do you really need that 500k at once?

You could remove the collection from the Parent and query the objects from Child by parent: SELECT c FROM Child c WHERE c.parent = :parent and add pagination or filtering when you dont need the 500k at once.

You could also load the data Child entieties as DTO which would improve memory performance because hibernate would not consider these DTO's for dirty checking. I guess this would remove memory footprint by half, although i never benchmarked it. Also a DTO would allow you to omit attributes which you dont need in this certain use case saving memory and CPU.

You could also take a look at enableDirtyTracking in Hibernate 5.


问:
How to retrieve data from Yahoo Finance to my website?
I am making an ASP.NET website where I want to retrieve data from Yahoo Finance, e.g.:

http://finance.yahoo.com/d/quotes.csv?s=RHT+MSFT&f=sb2b3jk

I am referring to above link to fetch data from Yahoo Finance.

The above link gives data in CSV format.

So how can I fetch data from the above link into my website? Any code or reference to some tutorial would be of great help.

答:
Got the answer.

Used System.Net.WebRequest to download the CSV and then parsed it using answer in below link.

How to parse a CSV file in an ASP.NET website?

Hope this helps someone.

ContentLicense: CC BY-SA 2.5


问:
Google Fonts seem to be showing Comic Sans only on certain computers
I had a client calling and telling me that all their navigation fonts have turned to comic sans. This site has been out for about 3 years with really no updates since to it.  They sent me a screenshot of what they were seeing.

I have contacted multiple people to have them look at this site: https://www.westcapital.com/

No one else seems to be able to see the issue.  I don't know how to explain this to my  client as they are insistent that the site is broken even though it seems to be only computers in their office.  Any help would be appreciated on what i could say, or if other people are seeing it.  I've tried Safari, IE11, Edge, Firefox, and Chrome.  The screenshot is from Chrome on her computer.

答: So it turns out the client was telling me it was on multiple computers, but it was theirs only. They were unsure what it was, but could have been ad blocker or the previous week they asked me for the font itself and they may of on accident overwrite the Unica One font with comic-sans.</p>


答:
The list has 30 references to the same slow_alien dictionary.

To fix this, try something like this:

```<code>aliens = []

for _ in range(30):
    aliens.append(slow_alien.copy())

for alien in aliens[:10]:
    alien.update(fast_alien)
</code>```

which follows your current approach, though you could also skip the update and just create the fast ones immediately:

```<code>aliens = []

for _ in range(10):
    aliens.append(fast_alien.copy())
for _ in range(20):
    aliens.append(slow_alien.copy())
</code>```

Title: Combination of for-loop and index slicing is not returning expected results

Body:
The list has 30 references to the same slow_alien dictionary.

To fix this, try something like this:

aliens = []

for _ in range(30):
    aliens.append(slow_alien.copy())

for alien in aliens[:10]:
    alien.update(fast_alien)

which follows your current approach, though you could also skip the update and just create the fast ones immediately:

aliens = []

for _ in range(10):
    aliens.append(fast_alien.copy())
for _ in range(20):
    aliens.append(slow_alien.copy())


问:
Laravel 5.5 global variable in template from service provider
How can I get info about logged user in service provider? When I use this in my template {{ $test }} always return 0 but i'm 100% sure that im logged in. Or mybe you have better solution?</p>

```<code>use Illuminate\Support\ServiceProvider;
use Auth;
use View;

class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        $user = Auth::user();
        if ($user !== null) {
            $walletsCount = $user->wallets()->count();
        } else {
            $walletsCount = 0;
        }
        View::share('test', $walletsCount);
    }
}
</code>```

答:
You do not have access to sessions this early in the request lifecycle, by default. The web group of middleware has a StartSession middleware which is responsible for actually starting and loading the session. The Auth system by default, web guard, uses sessions to store the user. So you don't have access to the session yet, so the user will return as null. The request hasn't even made it to that stack of middleware yet.

You could add a middleware to do this. Add the middleware to the end of your web stack. When this middleware gets ran the previous middleware in the stack have already loaded the session so you will have access to your authenticated user there.

If this is like a layout you need this variable for you could use a view composer instead. There are some options depending on exactly your need.

Body:
How can I get info about logged user in service provider? When I use this in my template {{ $test }} always return 0 but i'm 100% sure that im logged in. Or mybe you have better solution?

use Illuminate\Support\ServiceProvider;
use Auth;
use View;

class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        $user = Auth::user();
        if ($user !== null) {
            $walletsCount = $user->wallets()->count();
        } else {
            $walletsCount = 0;
        }
        View::share('test', $walletsCount);
    }
}


问:
FullCalender - Reset Event color when second event is clicked
I am wonderin how do you reset the event color when you click a second event? Right now I am changing the color when you click an event. When a second event is clicked the first events new color is the same. How do I reset it to the default color?

My Code:

```<code>eventClick: function (calEvent, jsEvent, view) {

   jQuery(this).css('background-color', '#b3ffb3');

}
</code>```

答:
Please update/edit your question with calendar element.

This will give you idea about how you can achieve that:

HTML (calendar element[supposedly]):

```<code><table id="calendar">
    <tr>
        <td>1</td>
        <td class="event">2 (event)</td>
        <td>3</td>
    </tr>
    <tr>
        <td>4</td>
        <td>5</td>
        <td>6</td>
    </tr>
    <tr>
        <td class="event">7 (event)</td>
        <td>8</td>
        <td>9</td>
    </tr>
</table>
</code>```

JS/Jquery:

```<code>jQuery('#calendar').on('click', '.event', function(){
    if(!$(this).hasClass('special')){
        $(this).parents('#calendar').find('.event.special').removeClass('special');
        $(this).addClass('special');
    }
});
</code>```

CSS:

```<code>.special {color: red;}
</code>```

P.S: in this way you will add a class .special to events which will clicked and also check to remove that class from other events. So at a time just one event has style and by clicking on another event it will lost its style and style will add to new one.

Sec P.S: You can add any jquery function after addClass and removeClass for exp:

```<code>jQuery('#calendar').on('click', '.event', function(){
    if(!$(this).hasClass('special')){
        $(this).parents('#calendar').find('.event.special').removeClass('special').css('background-color', '');
        $(this).addClass('special').css('background-color', '#b3ffb3');
    }
});
</code>```

Body:
I am wonderin how do you reset the event color when you click a second event? Right now I am changing the color when you click an event. When a second event is clicked the first events new color is the same. How do I reset it to the default color?

My Code:

eventClick: function (calEvent, jsEvent, view) {

   jQuery(this).css('background-color', '#b3ffb3');

}

Body:
Please update/edit your question with calendar element.

This will give you idea about how you can achieve that:

HTML (calendar element[supposedly]):

<table id="calendar">
    <tr>
        <td>1</td>
        <td class="event">2 (event)</td>
        <td>3</td>
    </tr>
    <tr>
        <td>4</td>
        <td>5</td>
        <td>6</td>
    </tr>
    <tr>
        <td class="event">7 (event)</td>
        <td>8</td>
        <td>9</td>
    </tr>
</table>

JS/Jquery:

jQuery('#calendar').on('click', '.event', function(){
    if(!$(this).hasClass('special')){
        $(this).parents('#calendar').find('.event.special').removeClass('special');
        $(this).addClass('special');
    }
});

CSS:

.special {color: red;}

P.S: in this way you will add a class .special to events which will clicked and also check to remove that class from other events. So at a time just one event has style and by clicking on another event it will lost its style and style will add to new one.

Sec P.S: You can add any jquery function after addClass and removeClass for exp:

jQuery('#calendar').on('click', '.event', function(){
    if(!$(this).hasClass('special')){
        $(this).parents('#calendar').find('.event.special').removeClass('special').css('background-color', '');
        $(this).addClass('special').css('background-color', '#b3ffb3');
    }
});


问:
Dynamic Coroutine name
How can I make the name of the Coroutine dynamic?
I use this to make targets die automatically after a few seconds:

```<code>void InitiateKill(int i)
{
   //i is the number of the target
   StartCoroutine(TargetDie(i, timeAlive/1000));
   //some other stuff
}
</code>```

When the target is killed before this timer ends, I obviously get an error because it can't kill the target again.

That's why I want to stop the coroutine of that specific target, but I don't know how.

I tried:

```<code>Coroutine b[i] = StartCoroutine(TargetDie(i, timeAlive/1000));
</code>```

But that gives a syntax error. b[i] can't be used for Coroutines.

How to do this the proper way?

Update:

This is (the relevant part of) my TargetDie function:

```<code>IEnumerator TargetDie(int i, float delayTime)
{
    yield return new WaitForSeconds(delayTime);
    Destroy(targets[i]);
}
</code>```

When the player kills the target, I do:

```<code>void Damage(int i)
{
   // at this time, the first Coroutine, started in InitiateKill, should stop, because otherwise it tries to destroy the target twice
   StartCoroutine(TargetDie(i, 0));
}
</code>```

答:
You can simply check for null before destroying it so that you won't get any error:

```<code>if (targets != null)
    Destroy(targets[i]);
</code>```

But below is the recommended way if you want to stop the old coroutine.

You can use Dictionary to handle it. Use the int i as the key and Coroutine as the value.

When you call InitiateKill, add the int i to the dictionary and when you start the coroutine, add the Coroutine as the value in the dictionary too.

When Damage is called, check if that int value exist in the Dictionary. If it does, use it to retrieve the Coroutine value and stop the old coroutine. If it doesn't exit, start a new coroutine and then add it to that dictionary.

The dictionary should look like this:

```<code>Dictionary<int, Coroutine> dyingTarget = new Dictionary<int, Coroutine>();
</code>```

Your new InitiateKill function which adds to the Dictionary:

```<code>void InitiateKill(int i)
{
    //i is the number of the target
    Coroutine crt = StartCoroutine(TargetDie(i, timeAlive / 1000));

    //Add to Dictionary
    dyingTarget.Add(i, crt);
}
</code>```

Your new Damage function now checks if the item is already in the dictionary then retries it, stops the coroutine and removes it from the Dictionary.

```<code>void Damage(int i)
{
    // at this time, the first Coroutine, started in InitiateKill, should stop, because otherwise it tries to destroy the target twice
    StopIfAlreadyRunning(i);

    Coroutine crt = StartCoroutine(TargetDie(i, 0));
    //Add to Dictionary
    dyingTarget.Add(i, crt);
}

void StopIfAlreadyRunning(int i)
{
    Coroutine crtOut;
    //Retrieve and stop old coroutine if it exist then removes it
    if (dyingTarget.TryGetValue(i, out crtOut))
    {
        StopCoroutine(crtOut);
        dyingTarget.Remove(i);
    }
}
</code>```

The new TargetDie function which removes it from the Dictionary after killing it. It also checks for null before destroying it:

```<code>IEnumerator TargetDie(int i, float delayTime)
{
    yield return new WaitForSeconds(delayTime);
    if (targets != null)
        Destroy(targets[i]);
    //Remove from Dictionary
    dyingTarget.Remove(i);
}
</code>```

Title: Dynamic Coroutine name

Body:
How can I make the name of the Coroutine dynamic?
I use this to make targets die automatically after a few seconds:

void InitiateKill(int i)
{
   //i is the number of the target
   StartCoroutine(TargetDie(i, timeAlive/1000));
   //some other stuff
}

When the target is killed before this timer ends, I obviously get an error because it can't kill the target again.

That's why I want to stop the coroutine of that specific target, but I don't know how.

I tried:

Coroutine b[i] = StartCoroutine(TargetDie(i, timeAlive/1000));

But that gives a syntax error. b[i] can't be used for Coroutines.

How to do this the proper way?

Update:

This is (the relevant part of) my TargetDie function:

IEnumerator TargetDie(int i, float delayTime)
{
    yield return new WaitForSeconds(delayTime);
    Destroy(targets[i]);
}

When the player kills the target, I do:

void Damage(int i)
{
   // at this time, the first Coroutine, started in InitiateKill, should stop, because otherwise it tries to destroy the target twice
   StartCoroutine(TargetDie(i, 0));
}

Body:
You can simply check for null before destroying it so that you won't get any error:

if (targets != null)
    Destroy(targets[i]);

But below is the recommended way if you want to stop the old coroutine.

You can use Dictionary to handle it. Use the int i as the key and Coroutine as the value.

When you call InitiateKill, add the int i to the dictionary and when you start the coroutine, add the Coroutine as the value in the dictionary too.

When Damage is called, check if that int value exist in the Dictionary. If it does, use it to retrieve the Coroutine value and stop the old coroutine. If it doesn't exit, start a new coroutine and then add it to that dictionary.

The dictionary should look like this:

Dictionary<int, Coroutine> dyingTarget = new Dictionary<int, Coroutine>();

Your new InitiateKill function which adds to the Dictionary:

void InitiateKill(int i)
{
    //i is the number of the target
    Coroutine crt = StartCoroutine(TargetDie(i, timeAlive / 1000));

    //Add to Dictionary
    dyingTarget.Add(i, crt);
}

Your new Damage function now checks if the item is already in the dictionary then retries it, stops the coroutine and removes it from the Dictionary.

void Damage(int i)
{
    // at this time, the first Coroutine, started in InitiateKill, should stop, because otherwise it tries to destroy the target twice
    StopIfAlreadyRunning(i);

    Coroutine crt = StartCoroutine(TargetDie(i, 0));
    //Add to Dictionary
    dyingTarget.Add(i, crt);
}

void StopIfAlreadyRunning(int i)
{
    Coroutine crtOut;
    //Retrieve and stop old coroutine if it exist then removes it
    if (dyingTarget.TryGetValue(i, out crtOut))
    {
        StopCoroutine(crtOut);
        dyingTarget.Remove(i);
    }
}

The new TargetDie function which removes it from the Dictionary after killing it. It also checks for null before destroying it:

IEnumerator TargetDie(int i, float delayTime)
{
    yield return new WaitForSeconds(delayTime);
    if (targets != null)
        Destroy(targets[i]);
    //Remove from Dictionary
    dyingTarget.Remove(i);
}


问:
How to handle async mutations in GraphQL Apollo client

Structure

This is a question how to best use Apollo Client 2 in our current infrastructure. We have one Graphql server (Apollo server 2) which connects to multiple other endpoints. Mutations are send via RabbitMQ and our Graphql also listens to RabbitMQ which then are pushed to the client via subscriptions.

Implementation

We have a Apollo server which we send mutations, these always give a null because they are async. Results will be send back via a subscription.
I have currently implemented it like this.

Send mutation.

Create a optimisticResponse.

Update the state optimistically via writeQuery in the update function.

When the real response comes (which is null) use the optimisticResponse again in the update method.

Wait for the subscription to come back with the response.

Then refresh the the state/component with the actual data.

As you can see.. not the most ideal way, and a lot of complexity in the client.

Would love to keep the client as dumb as possible and reduce complexity.
Seems Apollo is mostly designed for sync mutations (which is logical).

What are your thoughts on a better way to implement this?

答:
Mutations can be asynchronous

Mutations are generally not synchronous in Apollo Client. The client can wait for a mutation result as long as it needs to. You might not want your GraphQL service to keep the HTTP connection open for that duration and this seems to be the problem you are dealing with here. Your approach responding to mutations goes against how GraphQL is designed to work and that starts to create complexity that - in my opinion - you don't want to have.

Solve the problem on the implementation level - not API level

My idea to make this work better is the following: Follow the GraphQL spec and dogmatic approach. Let mutations return mutation results. This will create an API that any developer is familiar working with. Instead treat the delivery of these results as the actual problem you want to solve. GraphQL does not specify the transport protocol of the client server communication. If you have websockets running between server and client already throw away HTTP and completely operate on the socket level.

Leverage Apollo Client's flexible link system

This is where Apollo Client 2 comes in. Apollo Client 2 lets you write your own network links that handle client server communication. If you solve the communication on the link level, developers can use the client as they are used to without any knowledge of the network communication details.

I hope this helps and you still have the chance to go in this direction. I know that this might require changes on the server side but could be totally worth it when your application is frontend heavy (as most applications are these days)


问:
How do we get maximum value from table without using Max,Min or Order by Clause in SQL Server 2005?
I have one table has Salary has 3 columns and I want to get maximum value from this table without using Max, Min or order by clause.

Data

Salary has three fields - ID,Name,Amount
value of Amount - 100,70,80,400,300

I need to get value of 400 from this data.

I know Select max(Amount) from Salary, But i need without max,min or Order by clause.

Thanks in advance.

答:
```
SELECT *
FROM salary s1
WHERE s1.amount > ALL (SELECT s2.amount
                       FROM salary s2
                       WHERE s2.id <> s1.id);
```

But I doubt that it will be faster than using max()

Body:
SELECT *
FROM salary s1
WHERE s1.amount > ALL (SELECT s2.amount
                       FROM salary s2
                       WHERE s2.id <> s1.id);

But I doubt that it will be faster than using max()


问:
Gradle project refresh failed: Already finished
Background: I've been fighting with Studio/Gradle for a day or so at this point; there were initially multiple PEBKAC errors (namely permissions and resource limits) that have since been resolved. Unfortunately the google-fu has failed me for this current error.

The error specifically occurred attempting to complete ./gradlew clean which did not complete successfully; it failed about 30s in.

I temporarily 'fixed' the problem by blowing away the offending git repo and cloning it anew. I discovered the error seems to occur only on a specific branch (ie, switch to x_branch, run 'clean project,' receive error), but have not yet figured out why. Attempting to switch to another branch or back to master after receiving the error does not revert gradle back to a working state; the error remains.

Error:
Gradle project refresh failed: Error: Already finished

System env: Android Studio 3.1 // Gradle version 171.4250

My question(s): Has anyone seen this error before? What does this error mean and how do I prevent it from re-occurring?

答:
Restarting Android studio :

File > Invalidate Caches/Restart worked for me


答:
Many possibilities... for example

```<code>// your code
return Arrays.asList(s.get(0), s.get(1));
</code>```

or

```<code>s.stream()
    .sorted((s1, s2) -> s1.compareToIgnoreCase(s2)) // sort
    .limit(2)    // first two
    .collect(Collectors.toList()); // create list
</code>```

Title: How can I return the list of 2 first students in the list “s”?

Body:
Many possibilities... for example

// your code
return Arrays.asList(s.get(0), s.get(1));

or

s.stream()
    .sorted((s1, s2) -> s1.compareToIgnoreCase(s2)) // sort
    .limit(2)    // first two
    .collect(Collectors.toList()); // create list


问:
How to get only head and tail text of some DOMNode?
How can I get only head and tail text of nodes in DOMDocument?

Example, in this sample code I don't want to see contents of  tag:

```<code>$dom = new DOMDocument();
$dom->loadXML('<?xml version="1.0" encoding="UTF-8"?>
<root>
  <test>head text <b>some bold text</b> tail text</test>
</root>
');

foreach ($dom->getElementsByTagName('test') as $node) {
    echo 'nodeValue: '.$node->nodeValue."\n";
    echo 'textContent:'.$node->textContent."\n";
}
</code>```

答:
You will have to go through each node and look for just the child nodes which are text (DOMText), any other node can be ignored...

```<code>$dom = new DOMDocument();
$dom->loadXML('<?xml version="1.0" encoding="UTF-8"?>
<root>
  <test>head text <b>some bold text</b> tail text</test>
</root>
');

foreach ($dom->getElementsByTagName('test') as $node) {
    foreach ( $node->childNodes as $sub )   {
        if ( $sub instanceof DOMText )  {
            echo 'nodeValue: '.$sub->nodeValue."\n";
            echo 'textContent:'.$sub->textContent."\n";
        }
    }
}
</code>```

Gives you...

```<code>nodeValue: head text
textContent:head text
nodeValue:  tail text
textContent: tail text
</code>```

Body:
How can I get only head and tail text of nodes in DOMDocument?

Example, in this sample code I don't want to see contents of  tag:

$dom = new DOMDocument();
$dom->loadXML('<?xml version="1.0" encoding="UTF-8"?>
<root>
  <test>head text some bold text tail text</test>
</root>
');

foreach ($dom->getElementsByTagName('test') as $node) {
    echo 'nodeValue: '.$node->nodeValue."\n";
    echo 'textContent:'.$node->textContent."\n";
}

Body:
You will have to go through each node and look for just the child nodes which are text (DOMText), any other node can be ignored...

$dom = new DOMDocument();
$dom->loadXML('<?xml version="1.0" encoding="UTF-8"?>
<root>
  <test>head text <b>some bold text</b> tail text</test>
</root>
');

foreach ($dom->getElementsByTagName('test') as $node) {
    foreach ( $node->childNodes as $sub )   {
        if ( $sub instanceof DOMText )  {
            echo 'nodeValue: '.$sub->nodeValue."\n";
            echo 'textContent:'.$sub->textContent."\n";
        }
    }
}

Gives you...

nodeValue: head text
textContent:head text
nodeValue:  tail text
textContent: tail text


问:
Css overlay working on localhost but not server
I did an overlay on an image using a text which is actually working on my localhost very well, but after I deploy my web app to a live server the overlay on image refuse to work. help please.
Below is my code

```<code>   <div class="col-md-4 text-center ">
    <div class="rounded border m-1 p-1" id="box">
     <a href="<?php echo URL?>onlineMarket" style="text-decoration:none;">
        <div class="sitecolor2" >
            <img src="<?php echo URL?>images/online-market'.jpeg" class="img-fluid">
        </div>

        <div class="pt-5" id="overlay">Online Market</div>
    </a>
    </div>
    </div>

    #box {
        border: 1px solid black;
        position: relative;
        font-size: 35px;
        font-weight: bold;
        color: white;
        text-shadow: 0 0 7px black;
    }

    #box>a{
         color: white;
    }

    #overlay {
        position: absolute;
        top: 0px;
        left: 0px;
        bottom: 0px;
        right: 0px;
    /*    background-color: rgba(187, 213, 120, 0.24);*/
    }
</code>```

This is what i have in my local server http://prntscr.com/hkaqwv
while this is what its showing me after deploying to live server http://prntscr.com/hkas1j

答: it finally worked. i cleared my browser cache. cos it was using the old css and not the updated one. thanks </p>

Body:
I did an overlay on an image using a text which is actually working on my localhost very well, but after I deploy my web app to a live server the overlay on image refuse to work. help please.
Below is my code

     <a href="<?php echo URL?>onlineMarket" style="text-decoration:none;">

            <img src="<?php echo URL?>images/online-market'.jpeg" class="img-fluid">

Online Market

    #box {
        border: 1px solid black;
        position: relative;
        font-size: 35px;
        font-weight: bold;
        color: white;
        text-shadow: 0 0 7px black;
    }

    #box>a{
         color: white;
    }

    #overlay {
        position: absolute;
        top: 0px;
        left: 0px;
        bottom: 0px;
        right: 0px;
    /*    background-color: rgba(187, 213, 120, 0.24);*/
    }

This is what i have in my local server http://prntscr.com/hkaqwv
while this is what its showing me after deploying to live server http://prntscr.com/hkas1j


问:
adjust AppCompatEditText style
I have a CustomEditText extends EmojiEditText which extends AppCompatEditText and deriving https://github.com/vanniktech/Emoji library.

I used to ComposeEditText style for CustomEditText. But if I add this style, app is crashing. Please help me.

My edittext style:

```<code>        <style name="ComposeEditText" parent="@style/Widget.AppCompat.EditText">
        <item name="android:padding">2dp</item>
        <item name="android:background">@null</item>
        <item name="android:maxLines">4</item>
        <item name="android:maxLength">2000</item>
        <item name="android:capitalize">sentences</item>
        <item name="android:autoText">true</item>
        <item name="android:gravity">center_vertical</item>
        <item name="android:imeOptions">flagNoEnterAction</item>
        <item name="android:inputType">textAutoCorrect|textCapSentences|textMultiLine</item>
        </style>
</code>```

My edittext in xml:

```<code>         <com.android.android.util.view.CustomEditText
            android:id="@+id/editText"
            style="@style/ComposeEditText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            app:emojiSize="@dimen/emojiSize" />
</code>```

in code:

```<code>public class CustomEditText extends EmojiEditText {

    public CustomEditText(Context context) {
        super(context);
    }

    public CustomEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @SuppressLint("DrawAllocation")
    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
    }
}
</code>```

Error log:

```<code>    java.lang.RuntimeException: Unable to start activity
        ComponentInfo{com.android.android/com.android.android.conversation.a.PRofile}:
    android.view.InflateException: Binary XML file line #0:
       Binary XML file line #0: Error inflating class com.android.android.util.view.CustomEditText
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2927)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2988)
                                                                                at android.app.ActivityThread.-wrap14(ActivityThread.java)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1631)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:154)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6682)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)
                                                                              Caused by: android.view.InflateException: Binary XML file line #0: Binary XML file line #0: Error inflating class com.android.android.util.view.CustomEditText
                                                                              Caused by: android.view.InflateException: Binary XML file line #0: Error inflating class com.android.android.util.view.CustomEditText
                                                                              Caused by: java.lang.reflect.InvocationTargetException
</code>```

答:
I just remove "@style/" and it is solved. Thank you for your help

instead of

```<code><style name="ComposeEditText" parent="@style/Widget.AppCompat.EditText">
</code>```

use

```<code> <style name="ComposeEditText" parent="Widget.AppCompat.EditText">
</code>```

Title: adjust AppCompatEditText style

Body:
I have a CustomEditText extends EmojiEditText which extends AppCompatEditText and deriving https://github.com/vanniktech/Emoji library.

I used to ComposeEditText style for CustomEditText. But if I add this style, app is crashing. Please help me.

My edittext style:

My edittext in xml:

         <com.android.android.util.view.CustomEditText
            android:id="@+id/editText"
            style="@style/ComposeEditText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            app:emojiSize="@dimen/emojiSize" />

in code:

public class CustomEditText extends EmojiEditText {

    public CustomEditText(Context context) {
        super(context);
    }

    public CustomEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @SuppressLint("DrawAllocation")
    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
    }
}

Error log:

    java.lang.RuntimeException: Unable to start activity
        ComponentInfo{com.android.android/com.android.android.conversation.a.PRofile}:
    android.view.InflateException: Binary XML file line #0:
       Binary XML file line #0: Error inflating class com.android.android.util.view.CustomEditText
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2927)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2988)
                                                                                at android.app.ActivityThread.-wrap14(ActivityThread.java)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1631)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:154)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6682)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)
                                                                              Caused by: android.view.InflateException: Binary XML file line #0: Binary XML file line #0: Error inflating class com.android.android.util.view.CustomEditText
                                                                              Caused by: android.view.InflateException: Binary XML file line #0: Error inflating class com.android.android.util.view.CustomEditText
                                                                              Caused by: java.lang.reflect.InvocationTargetException

Body:
I just remove "@style/" and it is solved. Thank you for your help

instead of

<style name="ComposeEditText" parent="@style/Widget.AppCompat.EditText">

use

 <style name="ComposeEditText" parent="Widget.AppCompat.EditText">


问:
Learning Ruby from Python; Differences and Similarities
Inspired by Learning Python from Ruby; Differences and Similarities.

I'm in the exact opposite boat - I'm pretty well-versed in Python, but I need to start learning Ruby soon (and Rails later, but that's another topic). The question I'm linking to addresses this a bit, but are there any other resources out there that teach Ruby for someone who already has Python experience? (In other words, someone with a background in programming, but who doesn't yet know the difference between code that IRB will execute properly and proper Ruby code.)

EDIT: I'm not just looking for a list of the differences between the two languages - I'm wondering if there are any guides/walkthroughs that are directed towards teaching Python programmers to write idiomatic Ruby. I know similar guides exist for migrating to Python from other languages, but I don't know about Ruby.

答: The Ruby website has a page exactly on this topic. It's a summary list, so other answers with more best-practice style comments are surely a good idea.</p>


问:
css input corner triangle label with border radius
I would like to create an triangle label inside input (text) element exactly like this:

What I managed to do so far is this:

How can I put this triangle "under" the input border to, let's just say, keep border radius from input cutting the edge of this triangle?

This is my code:

```<code><div class="input">
   <label>email adress</label>
   <div class="note">
      <p>*</p>
      <input type="text" placeholder="Enter your email adress">
   </div>
</div>

.input {
   display: flex;
   flex-direction: column;
   width: 100%;
}
.note > input {
   width: 515px;
   height: 48px;
   border-radius: 5px;
   border: 1px solid #7d7d7d;
   box-shadow:inset 0 0 5px 1px lightgray;
   padding-left: 20px;
   color: #acacac;
   -webkit-color: #acacac;
   -moz-color: #acacac;
   -ms-color: #acacac;
   -o-color: #acacac;
   font-size: 16px;
   background-color: rgba(211, 211, 211, 0.50);
}

.note > input:focus {
   outline: none;
   background-color: #f9f9f9;
}

.note {
   position: relative;
   display: inline-block;
}
.note:after {
   content: "";
   position: absolute;
   top: 0;
   right: 0;
   width: 0;
   height: 0;
   display: block;
   border-left: 35px solid transparent;
   border-bottom: 35px solid transparent;
   border-top: 35px solid #0094bb;
}
</code>```

I imagine there is no way to give border-radius to this triangle itself without losing its shape, am I right?

答:
Consider declaring the pseudo-element to a nested element of .note instead.

This will allow you to specify the required border-radius property on the containing element rather than the pseudo-element. With an overflow: hidden rule declared on this new containing element in addition, the top-right corner of the pseudo-element will be "cut-off" from view, conveying the impression that this is an element nested within the input field.

Code Snippet Demonstration:

.note > input {
   width: 515px;
   height: 48px;
   border-radius: 5px;
   border: 1px solid #7d7d7d;
   box-shadow:inset 0 0 5px 1px lightgray;
   padding-left: 20px;
   color: #acacac;
   -webkit-color: #acacac;
   -moz-color: #acacac;
   -ms-color: #acacac;
   -o-color: #acacac;
   font-size: 16px;
   background-color: rgba(211, 211, 211, 0.50);
}

.note > input:focus {
   outline: none;
   background-color: #f9f9f9;
}

.note {
   position: relative;
   display: inline-block;
}

/* additional */
.note .required {
    position: absolute;
    top: 0;
    right: 0;
    z-index: 1;
    color: white;
    padding: 5px;
    box-sizing: border-box;
    border-top-right-radius: 5px;
    overflow: hidden;
    width: 35px;
    height: 35px;
    text-align: right;
}

.note .required:after {
    content: "";
    position: absolute;
    top: 0;
    right: 0;
    width: 0;
    height: 0;
    display: block;
    border-left: 35px solid transparent;
    border-bottom: 35px solid transparent;
    border-top: 35px solid #0094bb;
    z-index: -1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="input">
   <label>email adress</label>
   <div class="note">
      <span class="required">*</span>
      <input type="text" placeholder="Enter your email adress">
   </div>
</div></code>```

Body:
I would like to create an triangle label inside input (text) element exactly like this:

What I managed to do so far is this:

How can I put this triangle "under" the input border to, let's just say, keep border radius from input cutting the edge of this triangle?

This is my code:

   email adress

*

      <input type="text" placeholder="Enter your email adress">

.input {
   display: flex;
   flex-direction: column;
   width: 100%;
}
.note > input {
   width: 515px;
   height: 48px;
   border-radius: 5px;
   border: 1px solid #7d7d7d;
   box-shadow:inset 0 0 5px 1px lightgray;
   padding-left: 20px;
   color: #acacac;
   -webkit-color: #acacac;
   -moz-color: #acacac;
   -ms-color: #acacac;
   -o-color: #acacac;
   font-size: 16px;
   background-color: rgba(211, 211, 211, 0.50);
}

.note > input:focus {
   outline: none;
   background-color: #f9f9f9;
}

.note {
   position: relative;
   display: inline-block;
}
.note:after {
   content: "";
   position: absolute;
   top: 0;
   right: 0;
   width: 0;
   height: 0;
   display: block;
   border-left: 35px solid transparent;
   border-bottom: 35px solid transparent;
   border-top: 35px solid #0094bb;
}

I imagine there is no way to give border-radius to this triangle itself without losing its shape, am I right?

Body:
Consider declaring the pseudo-element to a nested element of .note instead.

This will allow you to specify the required border-radius property on the containing element rather than the pseudo-element. With an overflow: hidden rule declared on this new containing element in addition, the top-right corner of the pseudo-element will be "cut-off" from view, conveying the impression that this is an element nested within the input field.

Code Snippet Demonstration:

.note > input {
   width: 515px;
   height: 48px;
   border-radius: 5px;
   border: 1px solid #7d7d7d;
   box-shadow:inset 0 0 5px 1px lightgray;
   padding-left: 20px;
   color: #acacac;
   -webkit-color: #acacac;
   -moz-color: #acacac;
   -ms-color: #acacac;
   -o-color: #acacac;
   font-size: 16px;
   background-color: rgba(211, 211, 211, 0.50);
}

.note > input:focus {
   outline: none;
   background-color: #f9f9f9;
}

.note {
   position: relative;
   display: inline-block;
}

/* additional */
.note .required {
    position: absolute;
    top: 0;
    right: 0;
    z-index: 1;
    color: white;
    padding: 5px;
    box-sizing: border-box;
    border-top-right-radius: 5px;
    overflow: hidden;
    width: 35px;
    height: 35px;
    text-align: right;
}

.note .required:after {
    content: "";
    position: absolute;
    top: 0;
    right: 0;
    width: 0;
    height: 0;
    display: block;
    border-left: 35px solid transparent;
    border-bottom: 35px solid transparent;
    border-top: 35px solid #0094bb;
    z-index: -1;
}

<div class="input">
   <label>email adress</label>
   <div class="note">
      <span class="required">*</span>
      <input type="text" placeholder="Enter your email adress">
   </div>
</div>


问:
MongoEngine vs MongoKit for Django
Have you used MongoEngine or MongoKit with Django? Which one do you prefer?

Background:

I'm developing a new site and have experience with normal Django development but for the kind of data I'll be using the MongoDB will be better suited than a SQL database.

I'm using Python 2.7 and can compile/install anything on my host so that's not a problem.

答:
You say you have experience with

normal Django development

Then why don't you continue to use the usual Django ORM and connect it to MongoDB using a connector?

Djongo: The strategy is to translate Django SQL query syntax generated by the Django ORM into pymongo commands. Djongo translates every SQL query string into a mongoDB query document.

If you want to manipulate MongoDB using Django Admin, fire it up:

manage.py runserver

Goto: http://localhost:8000/admin/

Manipulate your MongoDB embedded models as shown in this screenshot:

There is an article on Using Django with MongoDB by adding just one line of code, if you are looking for more information. Otherwise, you can jump directly into the djongo documentation and start using it.

Title: MongoEngine vs MongoKit for Django


问:
List files with multiple conditions part2
I have the following rasters and would like to import them in R. My files are now called:

```<code>B02_10m.jp2
B03_10m.jp2
B04_10m.jp2
B08_10m.jp2

B05_20m.jp2
B06_20m.jp2
B07_20m.jp2
B8A_20m.jp2
B11_20m.jp2
B12_20m.jp2
</code>```

They are located in different sub-folders. That's way I am using recursive=TRUE

I have trying with the following options to combine the conditions but it's not working.

```<code> S2 <- "my/path"
S2 <- list.files(S2, recursive = TRUE, full.names = TRUE, pattern =  "B0[2348]_10m.jp2$ | B(0[567]_20m)|(1[12]_20m)|(8A_20m).jp2$")

S2 <- "my/path"
S2 <- list.files(S2, recursive = TRUE, full.names = TRUE, pattern =  "B0[2348]_10m | B(0[567]_20m)|(1[12]_20m)|(8A_20m).jp2$")
</code>```

答:
For other users and based on @docendo discimus answer, here is the idea to combine different conditions when listing files as in my case. My conditions are based on the numbers that are following the letter B so:

```<code>pattern="B( here we need to write the conditions).jp2$
</code>```

First, we will set the condition to import the files B02_10m, B03_10m, B04_10m, B08_10m

```<code>patter="B(FIRST CONDITION OR SECOND CONDITION).jp2$
pattern="B((0[2348]_10m)|SECOND CONDITION).jp2$
</code>```

Second, we will import the files B05_20m, B06_20m, B07_20m, B8A_20m, B11_20m, B12_20m. In this case, we have to combine several sub-conditions because the pattern changes from e.g.: 02 to 11, 12 and 8A

First we write the code for 5, 6 and 7

```<code>pattern="B((0[2348]_10m)|((0[567])_20m)).jp2$
</code>```

Then we add the code for bands 11 and 12

```<code>pattern="B((0[2348]_10m)|((0[567])|(1[12])_20m)).jp2$
</code>```

Then, the code for 8A

```<code>pattern="B((0[2348]_10m)|(((0[567])|(1[12])|(8A))_20m)).jp2$
</code>```

Hope it's clear

Body:
I have the following rasters and would like to import them in R. My files are now called:

B02_10m.jp2
B03_10m.jp2
B04_10m.jp2
B08_10m.jp2

B05_20m.jp2
B06_20m.jp2
B07_20m.jp2
B8A_20m.jp2
B11_20m.jp2
B12_20m.jp2

They are located in different sub-folders. That's way I am using recursive=TRUE

I have trying with the following options to combine the conditions but it's not working.

 S2 <- "my/path"
S2 <- list.files(S2, recursive = TRUE, full.names = TRUE, pattern =  "B0[2348]_10m.jp2$ | B(0[567]_20m)|(1[12]_20m)|(8A_20m).jp2$")

S2 <- "my/path"
S2 <- list.files(S2, recursive = TRUE, full.names = TRUE, pattern =  "B0[2348]_10m | B(0[567]_20m)|(1[12]_20m)|(8A_20m).jp2$")

Body:
For other users and based on @docendo discimus answer, here is the idea to combine different conditions when listing files as in my case. My conditions are based on the numbers that are following the letter B so:

pattern="B( here we need to write the conditions).jp2$

First, we will set the condition to import the files B02_10m, B03_10m, B04_10m, B08_10m

patter="B(FIRST CONDITION OR SECOND CONDITION).jp2$
pattern="B((0[2348]_10m)|SECOND CONDITION).jp2$

Second, we will import the files B05_20m, B06_20m, B07_20m, B8A_20m, B11_20m, B12_20m. In this case, we have to combine several sub-conditions because the pattern changes from e.g.: 02 to 11, 12 and 8A

First we write the code for 5, 6 and 7

pattern="B((0[2348]_10m)|((0[567])_20m)).jp2$

Then we add the code for bands 11 and 12

pattern="B((0[2348]_10m)|((0[567])|(1[12])_20m)).jp2$

Then, the code for 8A

pattern="B((0[2348]_10m)|(((0[567])|(1[12])|(8A))_20m)).jp2$

Hope it's clear


问:
How to log all thrown exceptions?
How to log any exceptions that were thrown and catched? Something like Visual Studio's IntelliTrace do. Or is there a way to integrate InteliTrace into debug version of application and then view its logs?

Update: I'll clarify that a bit. I want standard .txt (or any custom) logs, the format doesn't matter. The main point is I want to log all exceptions that occurred in all third-party libraries without adding code to them.

答: If your thing is a web thing then you can use https://elmah.github.io/ to automatically log errors (without even stopping your service!)</p>

Title: How to log all thrown exceptions?


答:
Does this do what you're after?

Explanation: We first convert tes into a flattened table with ftable(xtabs(...). Then we simply replicate the first and last column, and first and last row. We then give new column and row names to reflect the extra "flanking" rows and columns, and  finally convert back to a long dataframe with data.frame(table(...))

```<code># Convert to table then matrix
m <- ftable(xtabs(d ~ x + y, data = tes));
class(m) <- "matrix";

# Replicate first and last column/row by binding to the beginning
# and end, respectively of the matrix
m <- cbind(m[, 1], m, m[, ncol(m)]);
m <- rbind(m[1, ], m, m[nrow(m), ]);

# Set column/row names
rownames(m) <- seq(min(tes$x) - 1, max(tes$x) + 1);
colnames(m) <- seq(min(tes$y) - 1, max(tes$y) + 1);

# Convert back to long dataframe
tes.ext <- data.frame(as.table(m));
colnames(tes.ext) <- colnames(tes);

# Plot
ggplot(aes(x = x, y = y), data = tes.ext) + geom_point(aes(color = factor(d)), size = 5)
</code>```

Data

```<code>tes <- data.frame(x = c(1, 1, 1, 2, 2, 2, 3, 3, 3),
                  y = c(1, 2, 3, 1, 2, 3, 1, 2, 3),
                  d = c(10, 20, 30, 100, 11, 12, 403, 43, 21))
</code>```

Title: How to mirror the outer positions with the variable with R

Body:
I have a data frame:

 tes <- data.frame(x = c(1, 1, 1, 2, 2, 2, 3, 3, 3),
                      y = c(1, 2, 3, 1, 2, 3, 1, 2, 3),
                      d = c(10, 20, 30, 100, 11, 12, 403, 43, 21))

They look like this on the plot

ggplot(aes(x = x, y = y), data = tes) + geom_point(aes(color = factor(d)), size = 5)

I'd like to "mirror the outer rows in this data to obtain such data and plot

 tes1 <- data.frame(x = c(0, 0, 0, 0,0,  1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3,  3, 3, 3, 4, 4, 4, 4, 4),
                       y = c(0, 1, 2, 3, 4, 0, 1, 2, 3, 4,   0, 1, 2, 3, 4, 0, 1, 2, 3, 4,  0, 1, 2, 3, 4),
                       d = c(10, 10, 20, 30, 30, 10, 10, 20, 30, 30, 100, 100, 11, 12, 12, 403, 403, 43, 21, 21, 403, 403, 43, 21, 21))
ggplot(aes(x = x, y = y), data = tes1) + geom_point(aes(color = factor(d)), size = 4)

Body:
Does this do what you're after?

Explanation: We first convert tes into a flattened table with ftable(xtabs(...). Then we simply replicate the first and last column, and first and last row. We then give new column and row names to reflect the extra "flanking" rows and columns, and  finally convert back to a long dataframe with data.frame(table(...))

# Convert to table then matrix
m <- ftable(xtabs(d ~ x + y, data = tes));
class(m) <- "matrix";

# Replicate first and last column/row by binding to the beginning
# and end, respectively of the matrix
m <- cbind(m[, 1], m, m[, ncol(m)]);
m <- rbind(m[1, ], m, m[nrow(m), ]);

# Set column/row names
rownames(m) <- seq(min(tes$x) - 1, max(tes$x) + 1);
colnames(m) <- seq(min(tes$y) - 1, max(tes$y) + 1);

# Convert back to long dataframe
tes.ext <- data.frame(as.table(m));
colnames(tes.ext) <- colnames(tes);

# Plot
ggplot(aes(x = x, y = y), data = tes.ext) + geom_point(aes(color = factor(d)), size = 5)

Data

tes <- data.frame(x = c(1, 1, 1, 2, 2, 2, 3, 3, 3),
                  y = c(1, 2, 3, 1, 2, 3, 1, 2, 3),
                  d = c(10, 20, 30, 100, 11, 12, 403, 43, 21))


问:
PHP Soap Request foreach
I have a Souap Request and I do not know how I can go through all VoucherCodeItems with foreach.
I tried this, but it dosn't work:

```<code>foreach($response->VoucherCodeCollection->VoucherCodeItem AS $key => $val) {
 echo "Feld $key hat den Wert: $val<br>";
}
</code>```

This is what i get when make a print like:

```<code>print_r($response);
</code>```

Result

```<code>stdClass Object
(
    [TotalResults] => 2
    [VoucherCodeCollection] => stdClass Object
        (
            [VoucherCodeItem] => Array
                (
                    [0] => stdClass Object
                        (
                            [Id] => 215523
                            [ProgramId] => 6767
                            [Code] =>
                            [Title] => Adventskalender
                            [Description] => Im Adventskalender
                        )
                    [1] => stdClass Object
                        (
                            [Id] => 215453
                            [ProgramId] => 8476
                            [Code] =>
                            [Title] => Wir schenken dir 15 EUR!!
                            [Description] =>
                        )

                )

        )

)
</code>```

答:
You can't directly echo out the object:

Try:

```<code>foreach ($response->VoucherCodeCollection->VoucherCodeItem as $key => $val) {
 echo "Feld $key hat den Wert: {$val->Title}<br>";
}
</code>```

Title: PHP Soap Request foreach

Body:
I have a Souap Request and I do not know how I can go through all VoucherCodeItems with foreach.
I tried this, but it dosn't work:

foreach($response->VoucherCodeCollection->VoucherCodeItem AS $key => $val) {
 echo "Feld $key hat den Wert: $val
";
}

This is what i get when make a print like:

print_r($response);

Result

stdClass Object
(
    [TotalResults] => 2
    [VoucherCodeCollection] => stdClass Object
        (
            [VoucherCodeItem] => Array
                (
                    [0] => stdClass Object
                        (
                            [Id] => 215523
                            [ProgramId] => 6767
                            [Code] =>
                            [Title] => Adventskalender
                            [Description] => Im Adventskalender
                        )
                    [1] => stdClass Object
                        (
                            [Id] => 215453
                            [ProgramId] => 8476
                            [Code] =>
                            [Title] => Wir schenken dir 15 EUR!!
                            [Description] =>
                        )

                )

        )

)

Body:
You can't directly echo out the object:

Try:

foreach ($response->VoucherCodeCollection->VoucherCodeItem as $key => $val) {
 echo "Feld $key hat den Wert: {$val->Title}<br>";
}


问:
How to scrape a table with a blind caption?
I'm scraping a table from a page.

But the table's caption is 'blind'.

Is there no way to extract the table from the site?

Using BeautifulSoup like:

```<code>from urllib.request import urllib
from bs4 import BeautifulSoup
</code>```

答:
Take a look at this:</p>

```<code>import bs4 as bs
import urllib.request

link = 'http://companyinfo.stock.naver.com/v1/company/c1010001.aspx?cn=&cmp_cd=005930&menuType=block'
source = urllib.request.urlopen(link)

soup = bs.BeautifulSoup(source, 'html.parser')

table = soup.find('table', attrs={'id' : 'cTB24'})

for tr in table.find_all('tr'):
    for td in tr.find_all('td'):
        print(td.text)
</code>```

Body:
I'm scraping a table from a page.

But the table's caption is 'blind'.

Is there no way to extract the table from the site?

Using BeautifulSoup like:

from urllib.request import urllib
from bs4 import BeautifulSoup

Body:
Take a look at this:

import bs4 as bs
import urllib.request

link = 'http://companyinfo.stock.naver.com/v1/company/c1010001.aspx?cn=&cmp_cd=005930&menuType=block'
source = urllib.request.urlopen(link)

soup = bs.BeautifulSoup(source, 'html.parser')

table = soup.find('table', attrs={'id' : 'cTB24'})

for tr in table.find_all('tr'):
    for td in tr.find_all('td'):
        print(td.text)


问:
How to return a specific status code and no contents from Controller?
I want the example controller below to return a status code 418 with no contents. Setting the status code is easy enough but then it seems like there is something that needs to be done to signal the end of the request. In MVC prior to ASP.NET Core or in WebForms that might be a call to Response.End() but how does it work in ASP.NET Core where Response.End does not exist?

```<code>public class ExampleController : Controller
{
    [HttpGet][Route("/example/main")]
    public IActionResult Main()
    {
        this.HttpContext.Response.StatusCode = 418; // I'm a teapot
        // How to end the request?
        // I don't actually want to return a view but perhaps the next
        // line is required anyway?
        return View();
    }
}
</code>```

答:
This code might work for non-.NET Core MVC controllers:</p>

```<code>this.HttpContext.Response.StatusCode = 418; // I'm a teapot
return Json(new { status = "mer" }, JsonRequestBehavior.AllowGet);
</code>```

Body:
I want the example controller below to return a status code 418 with no contents. Setting the status code is easy enough but then it seems like there is something that needs to be done to signal the end of the request. In MVC prior to ASP.NET Core or in WebForms that might be a call to Response.End() but how does it work in ASP.NET Core where Response.End does not exist?

public class ExampleController : Controller
{
    [HttpGet][Route("/example/main")]
    public IActionResult Main()
    {
        this.HttpContext.Response.StatusCode = 418; // I'm a teapot
        // How to end the request?
        // I don't actually want to return a view but perhaps the next
        // line is required anyway?
        return View();
    }
}

Body:
This code might work for non-.NET Core MVC controllers:

this.HttpContext.Response.StatusCode = 418; // I'm a teapot
return Json(new { status = "mer" }, JsonRequestBehavior.AllowGet);


问:
How to apply if condition in multiple statements, as a best practice?
I need to apply If condition in multiple statements like below.

Two questions:

Any best practice to get it done?

Returning control from foreach loop like below: is it safe doing so?

```<code>if (assettFileParser.AddFile(_cfgFile, MyFileType.CFG) == ParserReturnCode.FileNotFound) return false;
    if (_psFiles != null)
         foreach (var file in _psFiles)
                  if(assettFileParser.AddFile(file, MyFileType.PS)== ParserReturnCode.FileNotFound) return false;
    if (_picFiles != null)
         foreach (var file in _picFiles)
                  if (assettFileParser.AddFile(file, MyFileType.ParaIC) == ParserReturnCode.FileNotFound) return false;
    if (_icFiles != null)
        foreach (var file in _icFiles)
                 if (assettFileParser.AddFile(file, MyFileType.IC) == ParserReturnCode.FileNotFound) return false;
    if (_xMasterFiles != null)
        foreach (var file in _xMasterFiles)
                 if (assettFileParser.AddFile(file, MyFileType.XMaster) == ParserReturnCode.FileNotFound) return false;
</code>```

答:
Here I combine the suggestions of Dylan Nicholson and Poylfun: use a helper method that throws an exception (you can introduce your own exception type by inheriting from System.Exception). I also moved the foreach into the helper method, it accepts a collection of files. The helper also makes sure that the collection  of files is not null, so the caller does not have to check this.

```<code>public void AddAssetFiles(AssettFileParser assettFileParser,
                          IEnumerable<string> files, MyFileType fileType) {
   if (files == null) {
       return; // do nothing
   }
   // note that looping over an empty collection will do nothing
   foreach (var file in files) {
        var returnCode = assettFileParser.AddFile(file, fileType);
        if (returnCode == ParserReturnCode.FileNotFound) {
            throw new AssetFileNotFoundException($"File '{file}' was not found.");
        }
   }
}
</code>```

Usage example. First file not found will result in termination of the whole try block. No further files are processed afterwards.

```<code>try {
    // put _cfgFile into a string array so it can be passed as IEnumerable<string>
    AddAssetFiles(assettFileParser, new string[] { _cfgFile }, MyFileType.CFG);
    AddAssetFiles(assettFileParser, _psFiles, MyFileType.PS);
    AddAssetFiles(assettFileParser, _picFiles, MyFileType.ParaIC);
    // ...
    return true;
}
catch (AssetFileNotFoundException ex) {
    Logger.Error(ex);
    return false;
}
</code>```

Side note on code style: you should always put if and foreach blocks into brackets { }, even if the block contains only a single line. This can forestall problems with dangling else etc.

Body:
I need to apply If condition in multiple statements like below.

Two questions:

Any best practice to get it done?

Returning control from foreach loop like below: is it safe doing so?

if (assettFileParser.AddFile(_cfgFile, MyFileType.CFG) == ParserReturnCode.FileNotFound) return false;
    if (_psFiles != null)
         foreach (var file in _psFiles)
                  if(assettFileParser.AddFile(file, MyFileType.PS)== ParserReturnCode.FileNotFound) return false;
    if (_picFiles != null)
         foreach (var file in _picFiles)
                  if (assettFileParser.AddFile(file, MyFileType.ParaIC) == ParserReturnCode.FileNotFound) return false;
    if (_icFiles != null)
        foreach (var file in _icFiles)
                 if (assettFileParser.AddFile(file, MyFileType.IC) == ParserReturnCode.FileNotFound) return false;
    if (_xMasterFiles != null)
        foreach (var file in _xMasterFiles)
                 if (assettFileParser.AddFile(file, MyFileType.XMaster) == ParserReturnCode.FileNotFound) return false;

Body:
Here I combine the suggestions of Dylan Nicholson and Poylfun: use a helper method that throws an exception (you can introduce your own exception type by inheriting from System.Exception). I also moved the foreach into the helper method, it accepts a collection of files. The helper also makes sure that the collection  of files is not null, so the caller does not have to check this.

public void AddAssetFiles(AssettFileParser assettFileParser,
                          IEnumerable<string> files, MyFileType fileType) {
   if (files == null) {
       return; // do nothing
   }
   // note that looping over an empty collection will do nothing
   foreach (var file in files) {
        var returnCode = assettFileParser.AddFile(file, fileType);
        if (returnCode == ParserReturnCode.FileNotFound) {
            throw new AssetFileNotFoundException($"File '{file}' was not found.");
        }
   }
}

Usage example. First file not found will result in termination of the whole try block. No further files are processed afterwards.

try {
    // put _cfgFile into a string array so it can be passed as IEnumerable<string>
    AddAssetFiles(assettFileParser, new string[] { _cfgFile }, MyFileType.CFG);
    AddAssetFiles(assettFileParser, _psFiles, MyFileType.PS);
    AddAssetFiles(assettFileParser, _picFiles, MyFileType.ParaIC);
    // ...
    return true;
}
catch (AssetFileNotFoundException ex) {
    Logger.Error(ex);
    return false;
}

Side note on code style: you should always put if and foreach blocks into brackets { }, even if the block contains only a single line. This can forestall problems with dangling else etc.


问:
Include javascript (or css) as inline in HEAD with Typoscript in TYPO3 7.6
I have a little javascript file that I need to run before my site loads (it contains some modernizr code and some more).
Usually I add it using includeJS but for performance issues I need it inline. As workaround I am including it using headerData in this way:

```<code>headerData {
    10 = TEXT
    10.value (
        <script>
           // Here goes my javascript code
        <script>
    )
}
</code>```

It works but it is ugly and difficult to update. Is there a way to say something like

```<code>headerData {
    10 = TEXT
    10.value < include(../path/to/my/file.js)
}
</code>```

答:
I don't see how this is an performance improvement over page.includeJs but you can just render a template here:

```<code>headerData {
    10 = FLUIDTEMPLATE
    10.file = EXT:my_ext/Resources/Private/Templates/MyTemplate
}
</code>```

Body:
I have a little javascript file that I need to run before my site loads (it contains some modernizr code and some more).
Usually I add it using includeJS but for performance issues I need it inline. As workaround I am including it using headerData in this way:

headerData {
    10 = TEXT
    10.value (

Body:
I don't see how this is an performance improvement over page.includeJs but you can just render a template here:

headerData {
    10 = FLUIDTEMPLATE
    10.file = EXT:my_ext/Resources/Private/Templates/MyTemplate
}


问:
django form without id=id_fieldname
I have the following form in django:

```<code>class Person(forms.Form):
    first_name = forms.CharField()
    last_name = forms.CharField()
    age = forms.IntegerField()
</code>```

When I render the form, the html output is the following:

```<code><input id="id_age" name="age" type="number">
</code>```

Is it possible to NOT include the input id?

My desired output would be:

```<code><input name="age" type="number">
</code>```

I don't want to change the id, i want the input to not have the id attribute at all.

答:
Please check the code below:</p>

```<code>class Person(forms.Form):
    first_name = forms.CharField(label=u'First Name',
                                widget=forms.TextInput(attrs = {"id":"set_your_id"}),
                                max_length=30)
</code>```

Title: django form without id=id_fieldname

Body:
I have the following form in django:

class Person(forms.Form):
    first_name = forms.CharField()
    last_name = forms.CharField()
    age = forms.IntegerField()

When I render the form, the html output is the following:

<input id="id_age" name="age" type="number">

Is it possible to NOT include the input id?

My desired output would be:

<input name="age" type="number">

I don't want to change the id, i want the input to not have the id attribute at all.

Body:
Please check the code below:

class Person(forms.Form):
    first_name = forms.CharField(label=u'First Name',
                                widget=forms.TextInput(attrs = {"id":"set_your_id"}),
                                max_length=30)


问:
How to add an Background Image to an HTML Email?
I want to add a background image to a table...

```<code><table background="https://host.tld/image.png">
<tr><td>blablabal</td></tr>
</table>
</code>```

doesn't work... any ideas?

答:
To cover almost every client, including the Windows Outlook's, the background image needs to be defined once in HTML/CSS and again in VML for versions of Outlook that use Microsoft Word to render emails.

Here's a modified version of Backgrounds.cm that I use for this:

```<code><table role="presentation" cellspacing="0" cellpadding="0" border="0" align="center" width="100%">
    <tr>
        <td background="http://placehold.it/680x180/222222/666666" bgcolor="#222222" valign="middle" style="text-align: center; background-position: center center !important; background-size: cover !important;">
            <!--[if gte mso 9]>
            <v:image xmlns:v="urn:schemas-microsoft-com:vml" fill="true" stroke="false" style="border: 0; display: inline-block; width: 680px; height: 180px;" src="http://placehold.it/680x180/222222/666666" />
            <v:rect xmlns:v="urn:schemas-microsoft-com:vml" fill="true" stroke="false" style="border: 0; display: inline-block; position: absolute; width: 680px; height: 180px;">
            <v:fill opacity="0%" color="#222222" />
            <![endif]-->
            <div>
                <!--[if mso]>
                <table role="presentation" border="0" cellspacing="0" cellpadding="0" align="center" width="500">
                <tr>
                <td align="center" valign="top" width="500">
                <![endif]-->
                <table role="presentation" border="0" cellpadding="0" cellspacing="0" align="center" width="100%" style="max-width:500px; margin: auto;">
                    <tr>
                        <td valign="middle" style="text-align: center; padding: 40px 20px; font-family: sans-serif; font-size: 15px; line-height: 140%; color: #ffffff;">
                            blah blah blah
                        </td>
                    </tr>
                </table>
                <!--[if mso]>
                </td>
                </tr>
                </table>
                <![endif]-->
            </div>
            <!--[if gte mso 9]>
            </v:fill>
            </v:rect>
            </v:image>
            <![endif]-->
        </td>
    </tr>
</table>
</code>```

Body:
I want to add a background image to a table...

blablabal

doesn't work... any ideas?

Body:
To cover almost every client, including the Windows Outlook's, the background image needs to be defined once in HTML/CSS and again in VML for versions of Outlook that use Microsoft Word to render emails.

Here's a modified version of Backgrounds.cm that I use for this:

<table role="presentation" cellspacing="0" cellpadding="0" border="0" align="center" width="100%">
    <tr>
        <td background="http://placehold.it/680x180/222222/666666" bgcolor="#222222" valign="middle" style="text-align: center; background-position: center center !important; background-size: cover !important;">
            <!--[if gte mso 9]>
            <v:image xmlns:v="urn:schemas-microsoft-com:vml" fill="true" stroke="false" style="border: 0; display: inline-block; width: 680px; height: 180px;" src="http://placehold.it/680x180/222222/666666" />
            <v:rect xmlns:v="urn:schemas-microsoft-com:vml" fill="true" stroke="false" style="border: 0; display: inline-block; position: absolute; width: 680px; height: 180px;">
            <v:fill opacity="0%" color="#222222" />
            <![endif]-->
            <div>
                <!--[if mso]>
                <table role="presentation" border="0" cellspacing="0" cellpadding="0" align="center" width="500">
                <tr>
                <td align="center" valign="top" width="500">
                <![endif]-->
                <table role="presentation" border="0" cellpadding="0" cellspacing="0" align="center" width="100%" style="max-width:500px; margin: auto;">
                    <tr>
                        <td valign="middle" style="text-align: center; padding: 40px 20px; font-family: sans-serif; font-size: 15px; line-height: 140%; color: #ffffff;">
                            blah blah blah
                        </td>
                    </tr>
                </table>
                <!--[if mso]>
                </td>
                </tr>
                </table>
                <![endif]-->
            </div>
            <!--[if gte mso 9]>
            </v:fill>
            </v:rect>
            </v:image>
            <![endif]-->
        </td>
    </tr>
</table>


问:
Scroll to an element in a div
I would like my

```<code>div="#course_navigation"
</code>```

in my sidebar with this css:

```<code>.sidebar #course_navigation {
    max-height: 700px !important;
    overflow-y: auto !important;
    overflow-x: hidden !important;
}
</code>```

to scroll to this class on page load:

```<code>.learndash-current-menu-item
</code>```

I try this, but nothing happens:

```<code>$('#course_navigation').scrollTo('.learndash-current-menu-item');
</code>```

I have tried many other codes, with no success. Don't know the problem is.

The structure looks like this:

Maybe I was not specific enough, so I repeat:

```<code>#course_navigation
</code>```

is scrollable.

I need #course_navigation scrolled until .learndash-current-menu-item can be seen at the top or center of #course_navigation on page load.

I have this at field of Theme Space before /head:

```<code><script src="code.jquery.com/jquery-1.10.2.js"></script>;
</code>```

I put the script to Space before /body like this:

```<code><script>$('#course_navigation').scrollTo('.learndash-current-menu-item');</script>
</code>```

No succes yet, nothing happens, none of the solution works...

Please help me out here with JS or jquery. The best should be scroll the element to the center of the div.

Thank you in advance!

András

答:
Try

```<code>$(document).on('click', '#course_navigation', function(){
    $('html, body').animate({
        scrollTop: $(".learndash-current-menu-item").offset().top
    }, 1000);
});
</code>```

This will scroll to your element with 1 second duration.

Here's the description of the code:

First, by binding the code to the document, instead simply to the element, we make sure that the code still works after you replaced the original element (with one with the same id, of course). This is called event delegation, and while it's not necessary for your case, it's always nice to use.

Then we create a function that triggers when you click on your element (this was the most important part you missed). Clicking on div#course_navigation will execute the lines you find in the function() tag.

The function uses jQuery animate to scroll to the top position of the element you want to. It takes two parameters: the first one if what you want to do (go to the top position of the desired element); the second one tells you hw long the animation should run (in milliseconds, so with 1000, it will take one second to the animation to finish and for the page to reach it's new position).

Title: Scroll to an element in a div

Body:
I would like my

div="#course_navigation"

in my sidebar with this css:

.sidebar #course_navigation {
    max-height: 700px !important;
    overflow-y: auto !important;
    overflow-x: hidden !important;
}

to scroll to this class on page load:

.learndash-current-menu-item

I try this, but nothing happens:

$('#course_navigation').scrollTo('.learndash-current-menu-item');

I have tried many other codes, with no success. Don't know the problem is.

The structure looks like this:

Maybe I was not specific enough, so I repeat:

#course_navigation

is scrollable.

I need #course_navigation scrolled until .learndash-current-menu-item can be seen at the top or center of #course_navigation on page load.

I have this at field of Theme Space before /head:

;

I put the script to Space before /body like this:

No succes yet, nothing happens, none of the solution works...

Please help me out here with JS or jquery. The best should be scroll the element to the center of the div.

Thank you in advance!

András

Body:
Try

$(document).on('click', '#course_navigation', function(){
    $('html, body').animate({
        scrollTop: $(".learndash-current-menu-item").offset().top
    }, 1000);
});

This will scroll to your element with 1 second duration.

Here's the description of the code:

First, by binding the code to the document, instead simply to the element, we make sure that the code still works after you replaced the original element (with one with the same id, of course). This is called event delegation, and while it's not necessary for your case, it's always nice to use.

Then we create a function that triggers when you click on your element (this was the most important part you missed). Clicking on div#course_navigation will execute the lines you find in the function() tag.

The function uses jQuery animate to scroll to the top position of the element you want to. It takes two parameters: the first one if what you want to do (go to the top position of the desired element); the second one tells you hw long the animation should run (in milliseconds, so with 1000, it will take one second to the animation to finish and for the page to reach it's new position).


问:
fold expression: right shift initialization behavior
I am having fun with the fold expressions to understand better where I will be able to use them in my projects. So I choose to initialize them with a simple

```<code>(datas = ... = 1);
</code>```

So far everything work as expected, every value is at 1. Then I tryed to use the left shift initialization so:

```<code>    (datas = ... = 1);
    (datas <<= ...);
</code>```

Here is also work as I expect it, it increase by a power of 2 it's nice.
And finally I tryed this:

```<code>(datas = ... = 1);
(datas >>= ...);
</code>```

And it give me as output a 0, 1, 0, 1, 0, 1, ..., I expected it would be all at 0. So here the code:

```<code>#include <iostream>

template<typename... T>
void test(T&&... datas) {
    (datas = ... = 1);
    (datas >>= ...);
    (std::cout << ... << (std::to_string(datas) + " ")) << std::endl;
}

int main(int argc, char const *argv[])
{
    int v1, v2, v3, v4;
    test(v1, v2, v3, v4);
    return 0;
}
</code>```

Why it is 0, 1, 0, 1 etc instead of 0, 0, 0, 0 ? I through for every argument it will do more something like that:
arg1 >>= arg2, arg2 >>= arg3, arg3 >>= arg4, etc
but it's true that then the last value should be 1 then so it could also be 0, 0, 0, 1.

答:
It is that way because your fold is

```<code>arg1 >>= arg2 >>= arg3 >>= arg4;
</code>```

arg3 >> arg4 is 1 >> 1, so arg3 becomes 0.

Then, arg2 >> arg3 is 1 >> 0, so arg2 becomes 1.

Then, arg1 >> arg2 is 1 >> 1, so arg1 becomes 0.

Thus, 0, 1, 0, 1.

I think the lesson here is "mutations and folds don't mix".

Body:
I am having fun with the fold expressions to understand better where I will be able to use them in my projects. So I choose to initialize them with a simple

(datas = ... = 1);

So far everything work as expected, every value is at 1. Then I tryed to use the left shift initialization so:

    (datas = ... = 1);
    (datas <<= ...);

Here is also work as I expect it, it increase by a power of 2 it's nice.
And finally I tryed this:

(datas = ... = 1);
(datas >>= ...);

And it give me as output a 0, 1, 0, 1, 0, 1, ..., I expected it would be all at 0. So here the code:

#include <iostream>

template<typename... T>
void test(T&&... datas) {
    (datas = ... = 1);
    (datas >>= ...);
    (std::cout << ... << (std::to_string(datas) + " ")) << std::endl;
}

int main(int argc, char const *argv[])
{
    int v1, v2, v3, v4;
    test(v1, v2, v3, v4);
    return 0;
}

Why it is 0, 1, 0, 1 etc instead of 0, 0, 0, 0 ? I through for every argument it will do more something like that:
arg1 >>= arg2, arg2 >>= arg3, arg3 >>= arg4, etc
but it's true that then the last value should be 1 then so it could also be 0, 0, 0, 1.

Body:
It is that way because your fold is

arg1 >>= arg2 >>= arg3 >>= arg4;

arg3 >> arg4 is 1 >> 1, so arg3 becomes 0.

Then, arg2 >> arg3 is 1 >> 0, so arg2 becomes 1.

Then, arg1 >> arg2 is 1 >> 1, so arg1 becomes 0.

Thus, 0, 1, 0, 1.

I think the lesson here is "mutations and folds don't mix".


问:
C3js - How to set category label on axis marker
I am using c3js to draw a line chart. x-axis displaying labels, which is rendered in between axis marker.
It is using axis.x.type : 'category'. otherwise the lines are not creating.

But I want to display it on x-axis marker, not in between them.

here is sample code

```<code>var chart = c3.generate({
    data: {
       x:'xaxis',
       columns: [
          ['xaxis','cat1', 'cat2', 'cat3', 'cat4', 'cat5', 'cat6', 'cat7', 'cat8', 'cat9'],
          ['data1', 30, 200, 100, 400, 150, 250, 50, 100, 250]
       ]
   },
    axis: {
       x: {
        type: 'category'
      }
  }
});
</code>```

Here is sample code on jsfiddle https://jsfiddle.net/abhinaw/kyjgzd62.

Is there a way to do this?

Thanks

答:
Use axis.x.tick.centered option:

```<code>axis: {
  x: {
    tick: {
      centered: true
    }
  }
}
</code>```

See updated fiddle.

Body:
I am using c3js to draw a line chart. x-axis displaying labels, which is rendered in between axis marker.
It is using axis.x.type : 'category'. otherwise the lines are not creating.

But I want to display it on x-axis marker, not in between them.

here is sample code

var chart = c3.generate({
    data: {
       x:'xaxis',
       columns: [
          ['xaxis','cat1', 'cat2', 'cat3', 'cat4', 'cat5', 'cat6', 'cat7', 'cat8', 'cat9'],
          ['data1', 30, 200, 100, 400, 150, 250, 50, 100, 250]
       ]
   },
    axis: {
       x: {
        type: 'category'
      }
  }
});

Here is sample code on jsfiddle https://jsfiddle.net/abhinaw/kyjgzd62.

Is there a way to do this?

Thanks

Body:
Use axis.x.tick.centered option:

axis: {
  x: {
    tick: {
      centered: true
    }
  }
}

See updated fiddle.