问:
isomorphic/universally-rendered React 15 app breaks with Cloudflare HTTP Proxy ("orange cloud")
I have an isomorphic/universal React app, meaning it is rendered on the server by the same JS that powers the client-side, Single Page App user experience.

I configure this app's DNS using Cloudflare, and use their "orange cloud" feature to accelerate and protect my site's traffic, as explained in the following graphic and in their support article:

From the linked-to article: "Cloudflare can operate in two modes - DNS only (unproxied; 'grey cloud') and as a HTTP proxy ('orange cloud') with our security, CDN & performance features."

I have discovered that running my app with React 15 and Cloudflare's "orange cloud" HTTP Proxy feature results in an error:

reactProdInvariant.js:31 Uncaught Error: Minified React error #32; visit http://facebook.github.io/react/docs/error-decoder.html?invariant=32&args[]=2 for the full message or use the non-minified dev environment for full errors and additional helpful warnings.

The text of the linked-to bug:

Unable to find element with ID 2.

This ID probably refers to the head tag of my page:

```<code><!doctype html>
<html lang="en-us" data-reactroot="" data-reactid="1" data-react-checksum="-1233854461"><head data-reactid="2">...
</code>```

I do NOT get this issue with React 14.

I do NOT get this bug when using the raw, un-DNS-ed address of my app, nor do I get it when I switch to the "grey cloud" to use Cloudflare as only a DNS service.

I do NOT get this issue when I disable server-side rendering.

When I google the text of the linked-to "actual" error, I find this Github thread that confirms that this has something to do with server-side rendering.

However, my situation differs slightly: that thread's author encounters the error with an "unable to find element" ID referring to a style tag, whereas in my case the unfound element ID refers to the head tag.

When I google the text of the production "wrapped" error, I find this Github thread that confirms that this has something to do with Cloudflare's HTTP Proxy. This comment says: "If you're using CloudFlare, please disable auto-minification of HTML."

So far, I can't figure out how to do that. It's hard for me to find good information on what exactly Cloudflare does with their HTTP Proxy, and how I can configure it.

Questions:

Why exactly does this bug happen?

Where can I find information about what exactly the "orange cloud" does?

What is the best way to fix this problem while maintaining the benefits of Cloudflare's HTTP Proxy?

答:
React on the server needs to render the application to a string of HTML that makes sense to the browser. At the same time, React in the browser needs to read this HTML and understand it in relation to your JS code: it needs to identify which DOM tree came from which React component, in a very detailed way. Thus, in effect, the intermediate HTML is a serialization format between React on the server and React on the client with an additional requirement for it to make sense for the browser even in the absence of React.

When you enable advanced Cloudflare functionality, it treats the HTML as a “regular” HTML, not fancy server-side rendered compnents. My baseless speculation on one thing that could be going wrong is stripping HTML comments. In general, this is a natural thing to do for minification. But React uses HTML comments to put a  placeholder where a React component returns null. Naturally, stripping these breaks React.

Cloudflare is there to make serving websites faster at a lower cost. They have a wide variety of tools to achieve that, see their introduction guide. Minifying HTML is completely natural and it is unfortunate it breaks your use case, but this is what we get when the meaning of nodes and attributes and flexibility changing them in our HTML is not strictly defined.

I think the most straight-forward way for you to move forward for now is to disable HTML minification in Cloudflare settings.

Body:
I have an isomorphic/universal React app, meaning it is rendered on the server by the same JS that powers the client-side, Single Page App user experience.

I configure this app's DNS using Cloudflare, and use their "orange cloud" feature to accelerate and protect my site's traffic, as explained in the following graphic and in their support article:

From the linked-to article: "Cloudflare can operate in two modes - DNS only (unproxied; 'grey cloud') and as a HTTP proxy ('orange cloud') with our security, CDN & performance features."

I have discovered that running my app with React 15 and Cloudflare's "orange cloud" HTTP Proxy feature results in an error:

reactProdInvariant.js:31 Uncaught Error: Minified React error #32; visit http://facebook.github.io/react/docs/error-decoder.html?invariant=32&args[]=2 for the full message or use the non-minified dev environment for full errors and additional helpful warnings.

The text of the linked-to bug:

Unable to find element with ID 2.

This ID probably refers to the head tag of my page:

<!doctype html>
...

I do NOT get this issue with React 14.

I do NOT get this bug when using the raw, un-DNS-ed address of my app, nor do I get it when I switch to the "grey cloud" to use Cloudflare as only a DNS service.

I do NOT get this issue when I disable server-side rendering.

When I google the text of the linked-to "actual" error, I find this Github thread that confirms that this has something to do with server-side rendering.

However, my situation differs slightly: that thread's author encounters the error with an "unable to find element" ID referring to a style tag, whereas in my case the unfound element ID refers to the head tag.

When I google the text of the production "wrapped" error, I find this Github thread that confirms that this has something to do with Cloudflare's HTTP Proxy. This comment says: "If you're using CloudFlare, please disable auto-minification of HTML."

So far, I can't figure out how to do that. It's hard for me to find good information on what exactly Cloudflare does with their HTTP Proxy, and how I can configure it.

Questions:

Why exactly does this bug happen?

Where can I find information about what exactly the "orange cloud" does?

What is the best way to fix this problem while maintaining the benefits of Cloudflare's HTTP Proxy?

Body:
React on the server needs to render the application to a string of HTML that makes sense to the browser. At the same time, React in the browser needs to read this HTML and understand it in relation to your JS code: it needs to identify which DOM tree came from which React component, in a very detailed way. Thus, in effect, the intermediate HTML is a serialization format between React on the server and React on the client with an additional requirement for it to make sense for the browser even in the absence of React.

When you enable advanced Cloudflare functionality, it treats the HTML as a “regular” HTML, not fancy server-side rendered compnents. My baseless speculation on one thing that could be going wrong is stripping HTML comments. In general, this is a natural thing to do for minification. But React uses HTML comments to put a <!-- empty --> placeholder where a React component returns null. Naturally, stripping these breaks React.

Cloudflare is there to make serving websites faster at a lower cost. They have a wide variety of tools to achieve that, see their introduction guide. Minifying HTML is completely natural and it is unfortunate it breaks your use case, but this is what we get when the meaning of nodes and attributes and flexibility changing them in our HTML is not strictly defined.

I think the most straight-forward way for you to move forward for now is to disable HTML minification in Cloudflare settings.


来源: stackexchange

问:
How to reset allocated memory and resources in c?
My program consists of a Menu, where you can select 1 of 2 options.
The second is just to exit the program. The first, however, is where you can find a specific sequence of bits that you choose, in a separate ".txt" file with 100.000 lines.

It does what I want the first time, and then returns to the Menu.

The problem is when the user goes for a second (or more) search. The program prints on screen random information.
It seems like I didn't do a "reset" of the resources, memory or values on     the first search.

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct{

    char ID[8];
    char content[2048];
    int distance;

} DATA;

void search(){

    FILE *f;
    DADO *z=NULL;
    long int tot=0;
    int a;
    int c;
    int i;
    int j=1;
    int k=0;
    char e;
    char b[2048];

    printf("\n");

    f=fopen("DANGER_DB_LARGE.txt", "r");

    printf("\n");
    printf("How many results do you wish?\n");
    scanf("%d",&a);

    printf("Introduce the sequence:\n");
    scanf("%s",b);
    c=strlen(b);

    printf("\n");

    z=(DATA*)realloc(z,(++tot)*sizeof(DATA));

    while(e!=EOF){
        e=fgetc(f);

        if(k<8){
            z[tot-1].ID[k]=e;
        }
        else if(k==8 && e=='\t'){
            continue;
        }
        else if(k>=9 && e!='\n'){
            z[tot-1].content[k-9]=e;
        }
        else if(e=='\n'){
            k=(-1);
            z=(DATA*)realloc(z,(++tot)*sizeof(DATA));
        }
        k++;
    }

    for(i=1; i<=tot; i++){
        distance(z,i,c,b);
    }

    free(z);
    fclose(f);
}
</code>```

I proceed to store the ID and content of every single one of those 100.000 lines of text. I end the function by doing free(z), but when I search again the program just prints random stuff.

答:
Use of uninitialised variables without an intervening assignment is undefined behaviour. It may work on the first Wednesday of every month, on the first time through the loop, only when the boss is looking, ...

```<code>int e; // originally was char
//...
while (e != EOF) { // uninitialised, no intervening assignment
</code>```

ContentLicense: CC BY-SA 3.0

Body:
My program consists of a Menu, where you can select 1 of 2 options.
The second is just to exit the program. The first, however, is where you can find a specific sequence of bits that you choose, in a separate ".txt" file with 100.000 lines.

It does what I want the first time, and then returns to the Menu.

The problem is when the user goes for a second (or more) search. The program prints on screen random information.
It seems like I didn't do a "reset" of the resources, memory or values on     the first search.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct{

    char ID[8];
    char content[2048];
    int distance;

} DATA;

void search(){

    FILE *f;
    DADO *z=NULL;
    long int tot=0;
    int a;
    int c;
    int i;
    int j=1;
    int k=0;
    char e;
    char b[2048];

    printf("\n");

    f=fopen("DANGER_DB_LARGE.txt", "r");

    printf("\n");
    printf("How many results do you wish?\n");
    scanf("%d",&a);

    printf("Introduce the sequence:\n");
    scanf("%s",b);
    c=strlen(b);

    printf("\n");

    z=(DATA*)realloc(z,(++tot)*sizeof(DATA));

    while(e!=EOF){
        e=fgetc(f);

        if(k<8){
            z[tot-1].ID[k]=e;
        }
        else if(k==8 && e=='\t'){
            continue;
        }
        else if(k>=9 && e!='\n'){
            z[tot-1].content[k-9]=e;
        }
        else if(e=='\n'){
            k=(-1);
            z=(DATA*)realloc(z,(++tot)*sizeof(DATA));
        }
        k++;
    }

    for(i=1; i<=tot; i++){
        distance(z,i,c,b);
    }

    free(z);
    fclose(f);
}

I proceed to store the ID and content of every single one of those 100.000 lines of text. I end the function by doing free(z), but when I search again the program just prints random stuff.

Body:
Use of uninitialised variables without an intervening assignment is undefined behaviour. It may work on the first Wednesday of every month, on the first time through the loop, only when the boss is looking, ...

int e; // originally was char
//...
while (e != EOF) { // uninitialised, no intervening assignment


问:
Prevent spring-data-rest from parsing json
I would like to store a post request as a string in a database using spring-data-rest and spring-data-jpa. The problem is that spring tries to convert the json request body to an object. Can I prevent this from happening? Can I configure spring to save the request body as a String?

Below is the entity and the repository.

Entity

```<code>@Entity
public class DatabaseRecord {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private String json;

    public DatabaseRecord(String json) {
        this.json = json;
    }

    public Long getId() {
        return id;
    }

    public String getJson() {
        return json;
    }
}
</code>```

Repository

```<code>public interface ExampleRepository extends CrudRepository<DatabaseRecord, Integer> {

    @Override
    @RestResource(exported = false)
    void delete(Integer integer);

    @Override
    @RestResource(exported = false)
    void delete(DatabaseRecord record);

    @Override
    @RestResource(exported = false)
    void delete(Iterable<? extends DatabaseRecord> iterable);

    @Override
    @RestResource(exported = false)
    void deleteAll();
}
</code>```

Any help would be much appreciated.

Thanks.

答:
The problem is that spring tries to convert the json request body to an object.

It's main idea of Spring Data REST - translating JSON directly into an instance for ORM mechanism to persist. If it was possible, where would this raw data be saved?

Can I prevent this from happening?

No, you can't (at least, via Spring Data REST module).

Can spring I configure spring to save the request body as a string?

You could use a plain Spring MVC controller which will delegate a request to REST repositories but before it does some processing raw data (e.g. saving it into another table).

The line @RestResource(exported = false) means excluding the method from the API, it  doesn't effect on the method behaviour (if you tried to use it for such purposes).

Body:
I would like to store a post request as a string in a database using spring-data-rest and spring-data-jpa. The problem is that spring tries to convert the json request body to an object. Can I prevent this from happening? Can I configure spring to save the request body as a String?

Below is the entity and the repository.

Entity

@Entity
public class DatabaseRecord {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private String json;

    public DatabaseRecord(String json) {
        this.json = json;
    }

    public Long getId() {
        return id;
    }

    public String getJson() {
        return json;
    }
}

Repository

public interface ExampleRepository extends CrudRepository<DatabaseRecord, Integer> {

    @Override
    @RestResource(exported = false)
    void delete(Integer integer);

    @Override
    @RestResource(exported = false)
    void delete(DatabaseRecord record);

    @Override
    @RestResource(exported = false)
    void delete(Iterable<? extends DatabaseRecord> iterable);

    @Override
    @RestResource(exported = false)
    void deleteAll();
}

Any help would be much appreciated.

Thanks.


问:
Laravel 5.4 Eloquent filter from a single input
I'm trying to make a query using laravel eloquent to join companies table with addresses and telephone numbers so a user can type into a single input field e.g address line or number and it will query across multiple tables/columns and only return ones which have a potential match.

I've looked into the wherehas but it seems to stop all results if both numbers and address tables have a match each.
I can get it to work I believe with a standard left join on these tables but I want a clean solution if possible. here is what i'm working with below which doesn't actually return any filtered results so i'm scratching my head a little.

The goal is a single input for ease of use but searching across multiple columns/tables and returning rows only with a match. Is there a wherehas option but for multiple conditions maybe? hope someone can understand what i'm trying to do.

```<code>public function addresses(){
    return $this->hasMany(Company_addresses::class, 'company_id', 'id');
}

public function digits(){
    return $this->hasMany(Company_digit::class, 'company_id', 'id');
}

public static function search($request)
{
    $filters = $request->all();
    $sortby = isset($filters['sortby']) ? $filters['sortby'] : 'created_at';
    $orderby = isset($filters['orderby']) ? $filters['orderby'] : 'desc';

    return static::with([
        'addresses' => function ($query) use ($filters) {
        $query->where('address_line_1', "LIKE", '%'.$filters['name'].'%')
            ->orWhere('address_line_2', "LIKE", '%'.$filters['name'].'%')
            ->orWhere('city', "LIKE", '%'.$filters['name'].'%')
            ->orWhere('county', "LIKE", '%'.$filters['name'].'%')
            ->orWhere('post_code', "LIKE", '%'.$filters['name'].'%');
        },
        'digits' => function ($query) use ($filters) {
        $query->where('number', "LIKE", '%'.$filters['name'].'%')
            ->orWhere('extension', "LIKE", '%'.$filters['name'].'%');
        }])
        ->orderBy('companies.'.$sortby, $orderby)
        ->select(['id', 'registered_name', 'trading_name', 'created_at', 'type'])
        ->paginate(20);
}
</code>```

答:
Since you got the answer before i could even understand. Here's a simple refactor for the code which i was gonna post after clarification on the question.</p>

```<code>public static function search()
{
    $name = request('name');

    return static::whereHas('addresses', function ($query) use ($name) {
            $query->where('address_line_1', "like", "%{$name}%")
                ->orWhere('address_line_2', "like", "%{$name}%")
                ->orWhere('city', "like", "%{$name}%")
                ->orWhere('county', "like", "%{$name}%")
                ->orWhere('post_code', "like", "%{$name}%");
        })->orWhereHas('digits', function ($query) use ($name) {
            $query->where('number', "like", "%{$name}%")
                ->orWhere('extension', "like", "%{$name}%");
        })
        ->orderBy('companies.'.request('sortby', 'created_at'), request('orderby', 'desc'))
        ->select(['id', 'registered_name', 'trading_name', 'created_at', 'type'])
        ->paginate(20);
}
</code>```

Body:
I'm trying to make a query using laravel eloquent to join companies table with addresses and telephone numbers so a user can type into a single input field e.g address line or number and it will query across multiple tables/columns and only return ones which have a potential match.

I've looked into the wherehas but it seems to stop all results if both numbers and address tables have a match each.
I can get it to work I believe with a standard left join on these tables but I want a clean solution if possible. here is what i'm working with below which doesn't actually return any filtered results so i'm scratching my head a little.

The goal is a single input for ease of use but searching across multiple columns/tables and returning rows only with a match. Is there a wherehas option but for multiple conditions maybe? hope someone can understand what i'm trying to do.

public function addresses(){
    return $this->hasMany(Company_addresses::class, 'company_id', 'id');
}

public function digits(){
    return $this->hasMany(Company_digit::class, 'company_id', 'id');
}

public static function search($request)
{
    $filters = $request->all();
    $sortby = isset($filters['sortby']) ? $filters['sortby'] : 'created_at';
    $orderby = isset($filters['orderby']) ? $filters['orderby'] : 'desc';

    return static::with([
        'addresses' => function ($query) use ($filters) {
        $query->where('address_line_1', "LIKE", '%'.$filters['name'].'%')
            ->orWhere('address_line_2', "LIKE", '%'.$filters['name'].'%')
            ->orWhere('city', "LIKE", '%'.$filters['name'].'%')
            ->orWhere('county', "LIKE", '%'.$filters['name'].'%')
            ->orWhere('post_code', "LIKE", '%'.$filters['name'].'%');
        },
        'digits' => function ($query) use ($filters) {
        $query->where('number', "LIKE", '%'.$filters['name'].'%')
            ->orWhere('extension', "LIKE", '%'.$filters['name'].'%');
        }])
        ->orderBy('companies.'.$sortby, $orderby)
        ->select(['id', 'registered_name', 'trading_name', 'created_at', 'type'])
        ->paginate(20);
}

Body:
Since you got the answer before i could even understand. Here's a simple refactor for the code which i was gonna post after clarification on the question.

public static function search()
{
    $name = request('name');

    return static::whereHas('addresses', function ($query) use ($name) {
            $query->where('address_line_1', "like", "%{$name}%")
                ->orWhere('address_line_2', "like", "%{$name}%")
                ->orWhere('city', "like", "%{$name}%")
                ->orWhere('county', "like", "%{$name}%")
                ->orWhere('post_code', "like", "%{$name}%");
        })->orWhereHas('digits', function ($query) use ($name) {
            $query->where('number', "like", "%{$name}%")
                ->orWhere('extension', "like", "%{$name}%");
        })
        ->orderBy('companies.'.request('sortby', 'created_at'), request('orderby', 'desc'))
        ->select(['id', 'registered_name', 'trading_name', 'created_at', 'type'])
        ->paginate(20);
}


问:
Proper usage of twoLineListItem Android
I am new to development on android and trying to create a list that has a bold header

and a smaller description for each item.
Like the one shown here (sorry can't post images yet):

http://i.stack.imgur.com/UVqzq.png

This is the XML that I have to start with:

```<code><LinearLayout android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TwoLineListItem android:layout_width="fill_parent"
android:layout_height="wrap_content" android:mode="twoLine">
<TextView android:textAppearance="?android:attr/textAppearanceLarge"
android:id="@android:id/text1" android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<TextView android:layout_below="@android:id/text1"
android:textAppearance="?android:attr/textAppearanceSmall"
android:layout_alignLeft="@android:id/text1" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:id="@android:id/text2" />
</TwoLineListItem>
</LinearLayout>
</code>```

Is there a way to populate the list from an array in another xml file?  If not how would I populate a list like this from the Java code?  Like I said I'm new to development, so I'm probably way off.  Thanks for any input!

答: You use a listview http://developer.android.com/reference/android/widget/ListView.html</p>

ContentLicense: CC BY-SA 2.5

Title: Proper usage of twoLineListItem Android

Body:
I am new to development on android and trying to create a list that has a bold header

and a smaller description for each item.
Like the one shown here (sorry can't post images yet):

http://i.stack.imgur.com/UVqzq.png

This is the XML that I have to start with:

<LinearLayout android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TwoLineListItem android:layout_width="fill_parent"
android:layout_height="wrap_content" android:mode="twoLine">
<TextView android:textAppearance="?android:attr/textAppearanceLarge"
android:id="@android:id/text1" android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<TextView android:layout_below="@android:id/text1"
android:textAppearance="?android:attr/textAppearanceSmall"
android:layout_alignLeft="@android:id/text1" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:id="@android:id/text2" />
</TwoLineListItem>
</LinearLayout>

Is there a way to populate the list from an array in another xml file?  If not how would I populate a list like this from the Java code?  Like I said I'm new to development, so I'm probably way off.  Thanks for any input!


问:
Search bar places under the navigation after adding tab bar
There was a search bar in a tableView.

And I had a navigation controller too

the search bar was located below the navigation bar.

navigation view controller is the entry point.

relationship root view controller to tab bar controller

and search bar is created in postViewController.Swift

relationship  tab bar view controller to postViewController

the setting:

```<code> searchController.searchResultsUpdater = self
        searchController.hidesNavigationBarDuringPresentation = false
        searchController.dimsBackgroundDuringPresentation = false
        searchController.searchBar.sizeToFit()
        searchController.searchBar.placeholder = "Search for the user id here ... "
        self.tableView.tableHeaderView = searchController.searchBar
        //blew code hides search bar on next page
        self.definesPresentationContext = true
</code>```

The problem is that after adding a tab bar. the search bar is behind the navigation bar.

答:
I created the same hierarchy as yours.

View Hierarchy

2.PostViewController

```<code>class PostViewController: UIViewController
{
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet var searchBar: UISearchBar!

    override func viewDidLoad()
    {
        super.viewDidLoad()
        self.tableView.tableHeaderView = self.searchBar
        //You can customize the controller and searchBar according to your requirement.
    }
}

extension PostViewController: UITableViewDataSource, UITableViewDelegate
{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        return 3
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        cell.textLabel?.text = "Hello"
        return cell
    }
}
</code>```

Output:

Body:
There was a search bar in a tableView.

And I had a navigation controller too

the search bar was located below the navigation bar.

navigation view controller is the entry point.

relationship root view controller to tab bar controller

and search bar is created in postViewController.Swift

relationship  tab bar view controller to postViewController

the setting:

 searchController.searchResultsUpdater = self
        searchController.hidesNavigationBarDuringPresentation = false
        searchController.dimsBackgroundDuringPresentation = false
        searchController.searchBar.sizeToFit()
        searchController.searchBar.placeholder = "Search for the user id here ... "
        self.tableView.tableHeaderView = searchController.searchBar
        //blew code hides search bar on next page
        self.definesPresentationContext = true

The problem is that after adding a tab bar. the search bar is behind the navigation bar.

Body:
I created the same hierarchy as yours.

View Hierarchy

2.PostViewController

class PostViewController: UIViewController
{
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet var searchBar: UISearchBar!

    override func viewDidLoad()
    {
        super.viewDidLoad()
        self.tableView.tableHeaderView = self.searchBar
        //You can customize the controller and searchBar according to your requirement.
    }
}

extension PostViewController: UITableViewDataSource, UITableViewDelegate
{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        return 3
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        cell.textLabel?.text = "Hello"
        return cell
    }
}

Output:


问:
Image Asset versus Vector Asset

When it comes to adding an icon to my app, there're two main options:

IMAGE ASSET || IMAGE VECTOR

What are the differences between the Image Asset and Vector Asset? What makes them different?

答:
According to Android User Guide :

Image Asset Studio helps you create various types of icons at different densities and shows you exactly where they'll be placed in your project. It includes tools for adjusting your icons and adding backdrops, all while displaying the result in a preview pane, so they appear exactly as you intended.

Vector Asset Studio adds a vector graphic to the project as an XML file that describes the image. Maintaining one XML file can be easier than updating multiple raster graphics at various resolutions.

ContentLicense: CC BY-SA 4.0

Title: Image Asset versus Vector Asset


问:
Delete file with same name contained in different sub-folders
For some reason, I have a copy of dismhost.exe in a lot of folders, inside temp folder; what I want to do is delete every instance of it, which are inside folders inside temp.

So the structure is as follows:

```<code>/temp
 /folder1
  dismhost.exe
 /folder2
  dismhost.exe
 /folder3
  dismhost.exe
 ...
</code>```

I first tried

```<code>rm ./*/dismhost.exe
</code>```

but then I remembered there is no rm in windows, so I tried with rd with same arguments. That raised an error, saying that the * modifier is not valid.

How can I achieve this?

答:
This can be done using a FOR loop iterating over a list of files returned by a recursive DIR search. When you are satisfied with the output, remove ECHO in order to actually delete the files.

```<code>FOR /F "usebackq tokens=*" %f IN (`DIR /S /B /A:-D \temp\dismhost.exe`) DO (ECHO DEL "%~f")
</code>```

If this is placed into a .bat script, be sure to double the % characters on the variable.

```<code>FOR /F "usebackq tokens=*" %%f IN (`DIR /S /B /A:-D \temp\dismhost.exe`) DO (
    ECHO DEL "%%~f"
)
</code>```

Body:
For some reason, I have a copy of dismhost.exe in a lot of folders, inside temp folder; what I want to do is delete every instance of it, which are inside folders inside temp.

So the structure is as follows:

/temp
 /folder1
  dismhost.exe
 /folder2
  dismhost.exe
 /folder3
  dismhost.exe
 ...

I first tried

rm ./*/dismhost.exe

but then I remembered there is no rm in windows, so I tried with rd with same arguments. That raised an error, saying that the * modifier is not valid.

How can I achieve this?

Body:
This can be done using a FOR loop iterating over a list of files returned by a recursive DIR search. When you are satisfied with the output, remove ECHO in order to actually delete the files.

FOR /F "usebackq tokens=*" %f IN (`DIR /S /B /A:-D \temp\dismhost.exe`) DO (ECHO DEL "%~f")

If this is placed into a .bat script, be sure to double the % characters on the variable.

FOR /F "usebackq tokens=*" %%f IN (`DIR /S /B /A:-D \temp\dismhost.exe`) DO (
    ECHO DEL "%%~f"
)


问:
I want to add some images in my apps by android studio
I want to add some images in my apps by android studio. but its not working, please help me how can i add more images.

deign and XML Screenshot uploaded.

Please help me,

Thanks
Miraz

Screenshots:
design
xml code

答: You need to change your Linear Layout to Relative Layout to achieve what you are looking for.


问:
Google font problems on wordpress child page
I have some problems with GFonts. My website try to call http://fonts.googleapis.com/css but didn't find nothing. I think that's because are not specify some parameters. (es. http://www.initiative.it/test/contattaci/)

In Home Page (www.initiative.it/test) I haven't this problem and montserrat load correctly. Why? Thank you so much.

答:
I suspect you should provide some missing parameter like
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">.

Note family=Roboto in the URL. In you page I cannot see any parameter provided as a result you have status code 400 Bad Request.

The same issue is happening on the Home page. Just open the browser console and you will see it.


问:
JTable: how to achieve custom rollover effect with TableCellRenderer
I already add a picture with JLabel in my JTable with TableCellRenderer. But how to add a border to the JLabel when mouse moves over the cell, on specific column and row?

This is the 1st renderer class:

```<code>public class RenderTabel implements TableCellRenderer{
@Override
public Component getTableCellRendererComponent(JTable table, Object
value,boolean isSelected, boolean hasFocus,int row, int column){

   JLabel gambar=new JLabel();
   String url="D:\\Kuliah Semester 4\\Pemrograman Berorientasi Objek\\DINUS BOOKSTORE\\image";
   ImageIcon img=scalegmbr(url+"\\"+table.getModel().getValueAt(row, 0)+".png");
   gambar.setIcon(img);
   gambar.setText("");
   gambar.setHorizontalAlignment(SwingConstants.CENTER);

        table.setRowHeight(row, 50);

        table.getColumnModel().getColumn(column).setPreferredWidth(80);
 return gambar;
 }
  public  ImageIcon scalegmbr(String file){
   Image image=new ImageIcon(file).getImage();
   return new ImageIcon(image.getScaledInstance(80,50,SCALE_SMOOTH));
 }
 }
</code>```

This is 2nd renderer class:

```<code>public class RenderTabel1 implements TableCellRenderer{
@Override
public Component getTableCellRendererComponent(JTable table, Object
value,boolean isSelected, boolean hasFocus,int row, int column){

   JLabel gambar=new JLabel();
   String url="D:\\Kuliah Semester 4\\Pemrograman Berorientasi Objek\\DINUS BOOKSTORE\\image";
   ImageIcon img=scalegmbr(url+"\\"+table.getModel().getValueAt(row, 0)+".png");
   gambar.setIcon(img);
   gambar.setText("");
   gambar.setHorizontalAlignment(SwingConstants.CENTER);
  gambar.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(200, 100, 52), 2));

        table.setRowHeight(row, 50);

        table.getColumnModel().getColumn(column).setPreferredWidth(80);
  return gambar;
  }
   public  ImageIcon scalegmbr(String file){
   Image image=new ImageIcon(file).getImage();
   return new ImageIcon(image.getScaledInstance(80,50,SCALE_SMOOTH));
 }
}
</code>```

and this is how I set the mouse enter and mouse clicked in my JTable:

```<code>private void tblbukuMouseEntered(java.awt.event.MouseEvent evt) {
    // TODO add your handling code here:

    tblbuku.getColumnModel().getColumn(6).setCellRenderer( new RenderTabel1());
}

private void tblbukuMouseExited(java.awt.event.MouseEvent evt) {
    // TODO add your handling code here:
    tblbuku.getColumnModel().getColumn(6).setCellRenderer( new RenderTabel());

}
</code>```

But this adds a border to all cells in column 6 when mouse moves ofer a cell of that column. How to change it only into  specific row and column when mouse entered that row and column?

答:
So, for a particular column of your table, you want to paint a border on the cell that is hovered by the mouse (only the hovered cell, only in this column).

(edit: after clarification it appears that this question has been asked before -- I'm leaving my answer below as it might still help)

don't change the cell renderer dynamically, have only 1 renderer for that column, and handle that situation within the single renderer.

don't add listeners on the Component that is returned by the renderer: such listeners won't be triggered, as the component is only used for its paint()-ing logic.

instead, add a mouse motion listener on the table itself, and compute the coordinates of hovered cells with JTable's methods rowAtPoint and columnAtPoint, when mouse moves over table, or exits the area.

(irrelevant to problem at hand, but deserves a mention) Avoid creating a new JLabel for each call of your renderer, this is wasteful. Swing is single-thread, it's safe to reuse the same object (provided you don't forget to reset all its properties that might have changed between 2 calls)

Small demo that shows the effect:

```<code>import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class SimpleTableDemo extends JPanel {

    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(SimpleTableDemo::createAndShowGUI);
    }

    private int
            hoveredRow = -1,
            hoveredColumn = -1;

    SimpleTableDemo() {
        super(new GridLayout(1,0));

        String[] columnNames = {"First Name", "Last Name", "Sport", "# of Years", "Vegetarian"};

        Object[][] data = {
                {"Kathy", "Smith", "Snowboarding", 5, Boolean.FALSE},
                {"John", "Doe", "Rowing", 3, Boolean.TRUE},
                {"Sue", "Black", "Knitting", 2, Boolean.FALSE},
                {"Jane", "White", "Speed reading", 20, Boolean.TRUE},
                {"Joe", "Brown", "Pool", 10, Boolean.FALSE}
        };

        final JTable table = new JTable(data, columnNames);
        table.setPreferredScrollableViewportSize(new Dimension(500, 70));
        table.setFillsViewportHeight(true);
        table.getColumn("Sport").setCellRenderer(new MyCellRenderer());

        table.addMouseMotionListener(new MouseAdapter() {
            public void mouseMoved(MouseEvent e) {
                Point p = e.getPoint();
                hoveredRow = table.rowAtPoint(p);
                hoveredColumn = table.columnAtPoint(p);
                table.repaint();
            }
            public void mouseExited(MouseEvent e) {
                hoveredRow = hoveredColumn = -1;
                table.repaint();
            }
        });

        JScrollPane scrollPane = new JScrollPane(table);

        add(scrollPane);
    }

    private static void createAndShowGUI() {
        JFrame frame = new JFrame("SimpleTableDemo");
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        SimpleTableDemo newContentPane = new SimpleTableDemo();
        newContentPane.setOpaque(true);
        frame.setContentPane(newContentPane);
        frame.pack();
        frame.setVisible(true);
    }

    private class MyCellRenderer extends DefaultTableCellRenderer {
        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
            JLabel label = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
            if (hoveredColumn == column && hoveredRow == row) {
                label.setBorder(BorderFactory.createLineBorder(Color.GREEN, 2));
            }
            else {
                label.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));
            }
            return label;
        }
    }

}
</code>```

Note 1: I'm using the default cell renderer, unlike you, but the same idea applies. The demo above is a generic example, that will be more useful as example to keep here than a specific solution for your case (for example, in my interpretation of the problem, I understand the details about icon are irrelevant).

Note 2: In the demo I repaint the whole visible area each time, but if you want to optimize it should be possible to repaint only 2 cells, that's an entire new question, see here for help about that.

Body:
I already add a picture with JLabel in my JTable with TableCellRenderer. But how to add a border to the JLabel when mouse moves over the cell, on specific column and row?

This is the 1st renderer class:

public class RenderTabel implements TableCellRenderer{
@Override
public Component getTableCellRendererComponent(JTable table, Object
value,boolean isSelected, boolean hasFocus,int row, int column){

   JLabel gambar=new JLabel();
   String url="D:\\Kuliah Semester 4\\Pemrograman Berorientasi Objek\\DINUS BOOKSTORE\\image";
   ImageIcon img=scalegmbr(url+"\\"+table.getModel().getValueAt(row, 0)+".png");
   gambar.setIcon(img);
   gambar.setText("");
   gambar.setHorizontalAlignment(SwingConstants.CENTER);

        table.setRowHeight(row, 50);

        table.getColumnModel().getColumn(column).setPreferredWidth(80);
 return gambar;
 }
  public  ImageIcon scalegmbr(String file){
   Image image=new ImageIcon(file).getImage();
   return new ImageIcon(image.getScaledInstance(80,50,SCALE_SMOOTH));
 }
 }

This is 2nd renderer class:

public class RenderTabel1 implements TableCellRenderer{
@Override
public Component getTableCellRendererComponent(JTable table, Object
value,boolean isSelected, boolean hasFocus,int row, int column){

   JLabel gambar=new JLabel();
   String url="D:\\Kuliah Semester 4\\Pemrograman Berorientasi Objek\\DINUS BOOKSTORE\\image";
   ImageIcon img=scalegmbr(url+"\\"+table.getModel().getValueAt(row, 0)+".png");
   gambar.setIcon(img);
   gambar.setText("");
   gambar.setHorizontalAlignment(SwingConstants.CENTER);
  gambar.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(200, 100, 52), 2));

        table.setRowHeight(row, 50);

        table.getColumnModel().getColumn(column).setPreferredWidth(80);
  return gambar;
  }
   public  ImageIcon scalegmbr(String file){
   Image image=new ImageIcon(file).getImage();
   return new ImageIcon(image.getScaledInstance(80,50,SCALE_SMOOTH));
 }
}

and this is how I set the mouse enter and mouse clicked in my JTable:

private void tblbukuMouseEntered(java.awt.event.MouseEvent evt) {
    // TODO add your handling code here:

    tblbuku.getColumnModel().getColumn(6).setCellRenderer( new RenderTabel1());
}

private void tblbukuMouseExited(java.awt.event.MouseEvent evt) {
    // TODO add your handling code here:
    tblbuku.getColumnModel().getColumn(6).setCellRenderer( new RenderTabel());

}

But this adds a border to all cells in column 6 when mouse moves ofer a cell of that column. How to change it only into  specific row and column when mouse entered that row and column?

Body:
So, for a particular column of your table, you want to paint a border on the cell that is hovered by the mouse (only the hovered cell, only in this column).

(edit: after clarification it appears that this question has been asked before -- I'm leaving my answer below as it might still help)

don't change the cell renderer dynamically, have only 1 renderer for that column, and handle that situation within the single renderer.

don't add listeners on the Component that is returned by the renderer: such listeners won't be triggered, as the component is only used for its paint()-ing logic.

instead, add a mouse motion listener on the table itself, and compute the coordinates of hovered cells with JTable's methods rowAtPoint and columnAtPoint, when mouse moves over table, or exits the area.

(irrelevant to problem at hand, but deserves a mention) Avoid creating a new JLabel for each call of your renderer, this is wasteful. Swing is single-thread, it's safe to reuse the same object (provided you don't forget to reset all its properties that might have changed between 2 calls)

Small demo that shows the effect:

import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class SimpleTableDemo extends JPanel {

    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(SimpleTableDemo::createAndShowGUI);
    }

    private int
            hoveredRow = -1,
            hoveredColumn = -1;

    SimpleTableDemo() {
        super(new GridLayout(1,0));

        String[] columnNames = {"First Name", "Last Name", "Sport", "# of Years", "Vegetarian"};

        Object[][] data = {
                {"Kathy", "Smith", "Snowboarding", 5, Boolean.FALSE},
                {"John", "Doe", "Rowing", 3, Boolean.TRUE},
                {"Sue", "Black", "Knitting", 2, Boolean.FALSE},
                {"Jane", "White", "Speed reading", 20, Boolean.TRUE},
                {"Joe", "Brown", "Pool", 10, Boolean.FALSE}
        };

        final JTable table = new JTable(data, columnNames);
        table.setPreferredScrollableViewportSize(new Dimension(500, 70));
        table.setFillsViewportHeight(true);
        table.getColumn("Sport").setCellRenderer(new MyCellRenderer());

        table.addMouseMotionListener(new MouseAdapter() {
            public void mouseMoved(MouseEvent e) {
                Point p = e.getPoint();
                hoveredRow = table.rowAtPoint(p);
                hoveredColumn = table.columnAtPoint(p);
                table.repaint();
            }
            public void mouseExited(MouseEvent e) {
                hoveredRow = hoveredColumn = -1;
                table.repaint();
            }
        });

        JScrollPane scrollPane = new JScrollPane(table);

        add(scrollPane);
    }

    private static void createAndShowGUI() {
        JFrame frame = new JFrame("SimpleTableDemo");
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        SimpleTableDemo newContentPane = new SimpleTableDemo();
        newContentPane.setOpaque(true);
        frame.setContentPane(newContentPane);
        frame.pack();
        frame.setVisible(true);
    }

    private class MyCellRenderer extends DefaultTableCellRenderer {
        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
            JLabel label = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
            if (hoveredColumn == column && hoveredRow == row) {
                label.setBorder(BorderFactory.createLineBorder(Color.GREEN, 2));
            }
            else {
                label.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));
            }
            return label;
        }
    }

}

Note 1: I'm using the default cell renderer, unlike you, but the same idea applies. The demo above is a generic example, that will be more useful as example to keep here than a specific solution for your case (for example, in my interpretation of the problem, I understand the details about icon are irrelevant).

Note 2: In the demo I repaint the whole visible area each time, but if you want to optimize it should be possible to repaint only 2 cells, that's an entire new question, see here for help about that.


问:
Using PHPMailer without gmail account
I wanted to test locally sending mails via PHPMailer (Symfony3 framework), but on the internet i see only configurations for gmail accounts. Is it possible to not configure any external server to send mails for testing locally?</p>

答:
You can set up your local server to handle smtp requests, or you can use a service like Mailtrap: https://mailtrap.io/

From their website: "Mailtrap is a fake SMTP server for development teams to test, view and share emails sent from the development and staging environments without spamming real customers."

Title: Using PHPMailer without gmail account


问:
scala type classes implicit ambiguity
I have a problem setting up type classes in an algebraic type hierarchy.

I have the following traits:

```<code>trait Field[F]{...}

trait VectorSpace3[V,F] extends Field[F]{...}
</code>```

Know I want to provide implementations:

```<code>trait DoubleIsField extends Field[Double]{
   ...
}

trait DoubleTurple3IsVectorSpace3 extends VectorSpace3[(Double,Double,Double), Double] with Field[Double]{
   ...
}
trait MyOtherClassIsVectorSpace3 extends VectorSpace3[MyOtherClass, Double] with Field[Double]{
   ...
}

//now the implicits
implicit object DoubleIsField extends DoubleIsField
implicit object DoubleTurple3IsVectorSpace3 extends DoubleTurple3IsVectorSpace3 with DoubleIsField
implicit object MyOtherClassIsVectorSpace3 extends MyOtherClassIsVectorSpace3 with DoubleIsField
</code>```

The last two implicits lead to ambiguity: DoubleIsField is a part of 3 implicit values, code does not compile. How to deal with this issue in scala ?

EDIT:

Error:

```<code>ambiguous implicit values:
[error]  both object DoubleIsField in object TypeClasses of type
Russoul.lib.common.TypeClasses.DoubleIsField.type
[error]  and object DoubleTurple3IsVectorSpace3 in object TypeClasses of type
Russoul.lib.common.TypeClasses.DoubleTurple3IsVectorSpace3.type
[error]  match expected type Russoul.lib.common.TypeClasses.Field[...Double]
</code>```

EDIT2:

```<code> def func()(implicit env: Field[Double]): Unit ={

 }

 func()
</code>```

Full testing program:

```<code>object Test extends App {

trait Field[F]{

}

trait VectorSpace3[V,F] extends Field[F]{

}
trait DoubleIsField extends Field[Double]{

}

trait DoubleTurple3IsVectorSpace3 extends VectorSpace3[(Double,Double,Double), Double] with Field[Double]{

}

//now the implicits
implicit object DoubleIsField extends DoubleIsField
implicit object DoubleTurple3IsVectorSpace3 extends DoubleTurple3IsVectorSpace3 with DoubleIsField

def func()(implicit env: Field[Double]): Unit ={

}

func()

}
</code>```

答:
(Updated in light of your recent comment...)

The problem is the definition of the following function:

```<code>def func()(implicit env: Field[Double]): Unit = {
  // ...
}
</code>```

Your issue is that you have multiple implicit values of this type in the same scope, and so the compiler cannot know which one to provide (they are all implicit values that can be expressed as having the type Field[Double]).

The whole point about implicit argument values is that there be a single value that can be identified by the compiler; if it can't identify one, it can't read your mind and pick the right one, nor would you want it to pick one at random.

The options you have available are as follows:

Forego using implicit argument values and pass values to your function explicitly.

Change the definition of the functions with implicit arguments to be types having unique implicit values.

Make do with a single implicit object definition. (Apologies for missing this off the list initially.)

Title: scala type classes implicit ambiguity

Body:
I have a problem setting up type classes in an algebraic type hierarchy.

I have the following traits:

trait Field[F]{...}

trait VectorSpace3[V,F] extends Field[F]{...}

Know I want to provide implementations:

trait DoubleIsField extends Field[Double]{
   ...
}

trait DoubleTurple3IsVectorSpace3 extends VectorSpace3[(Double,Double,Double), Double] with Field[Double]{
   ...
}
trait MyOtherClassIsVectorSpace3 extends VectorSpace3[MyOtherClass, Double] with Field[Double]{
   ...
}

//now the implicits
implicit object DoubleIsField extends DoubleIsField
implicit object DoubleTurple3IsVectorSpace3 extends DoubleTurple3IsVectorSpace3 with DoubleIsField
implicit object MyOtherClassIsVectorSpace3 extends MyOtherClassIsVectorSpace3 with DoubleIsField

The last two implicits lead to ambiguity: DoubleIsField is a part of 3 implicit values, code does not compile. How to deal with this issue in scala ?

EDIT:

Error:

ambiguous implicit values:
[error]  both object DoubleIsField in object TypeClasses of type
Russoul.lib.common.TypeClasses.DoubleIsField.type
[error]  and object DoubleTurple3IsVectorSpace3 in object TypeClasses of type
Russoul.lib.common.TypeClasses.DoubleTurple3IsVectorSpace3.type
[error]  match expected type Russoul.lib.common.TypeClasses.Field[...Double]

EDIT2:

 def func()(implicit env: Field[Double]): Unit ={

 }

 func()

Full testing program:

object Test extends App {

trait Field[F]{

}

trait VectorSpace3[V,F] extends Field[F]{

}
trait DoubleIsField extends Field[Double]{

}

trait DoubleTurple3IsVectorSpace3 extends VectorSpace3[(Double,Double,Double), Double] with Field[Double]{

}

//now the implicits
implicit object DoubleIsField extends DoubleIsField
implicit object DoubleTurple3IsVectorSpace3 extends DoubleTurple3IsVectorSpace3 with DoubleIsField

def func()(implicit env: Field[Double]): Unit ={

}

func()

}

Body:
(Updated in light of your recent comment...)

The problem is the definition of the following function:

def func()(implicit env: Field[Double]): Unit = {
  // ...
}

Your issue is that you have multiple implicit values of this type in the same scope, and so the compiler cannot know which one to provide (they are all implicit values that can be expressed as having the type Field[Double]).

The whole point about implicit argument values is that there be a single value that can be identified by the compiler; if it can't identify one, it can't read your mind and pick the right one, nor would you want it to pick one at random.

The options you have available are as follows:

Forego using implicit argument values and pass values to your function explicitly.

Change the definition of the functions with implicit arguments to be types having unique implicit values.

Make do with a single implicit object definition. (Apologies for missing this off the list initially.)


问:
How to compare two arrays in node js?
I am having two arrays, how can i compare the two arrays at single shot.</p>

```<code>   var arr1= ["a","b","c"];
   var arr2 = ["a","c","d"]

   if(arr1 == arr2){
      console.log(true);
    }else{
      console.log(false);
    }
</code>```

答:
[ES6]

Top answer is good & enough.

But when you just want to compare its values are same you have to sort it before.
here's no need sort code.

```<code>if(arr1.length == arr2.length && arr1.every((v) => arr2.indexOf(v) >= 0)) {
    console.log(true);
} else {
    console.log(false);
}
</code>```

And.. I think using a 'some' instead of 'every' is better.

If those are not same, 'some' gives you a early exit. - very little early but early ;)

```<code>if(arr1.length == arr2.length && !arr1.some((v) => arr2.indexOf(v) < 0)) {
    console.log(true);
} else {
    console.log(false);
}
</code>```

Title: How to compare two arrays in node js?

Body:
I am having two arrays, how can i compare the two arrays at single shot.

   var arr1= ["a","b","c"];
   var arr2 = ["a","c","d"]

   if(arr1 == arr2){
      console.log(true);
    }else{
      console.log(false);
    }

Body:
[ES6]

Top answer is good & enough.

But when you just want to compare its values are same you have to sort it before.
here's no need sort code.

if(arr1.length == arr2.length && arr1.every((v) => arr2.indexOf(v) >= 0)) {
    console.log(true);
} else {
    console.log(false);
}

And.. I think using a 'some' instead of 'every' is better.

If those are not same, 'some' gives you a early exit. - very little early but early ;)

if(arr1.length == arr2.length && !arr1.some((v) => arr2.indexOf(v) < 0)) {
    console.log(true);
} else {
    console.log(false);
}


问:
OSGI with Custom Class Loader Perm Gen Issue
For our purposes we didn't go with the standard OSGI jar reference that builds the jars into the bundle.  Rather for online upgrades, we wanted to be able to provide new and updated jars during upgrades.  Within our Activator class which starts and stops a bundle, we Implement our own URLClassLoader and then lookup all jars in a sub folder and supply to the URLClassLoader along with the OSGI CLassLoader as the parent.  This is great because now admins of the application can simply add jars to a classpath and restart the application(osgi restart, not actually shutting down jvm).  We got this working great.  Plus our bundle.jar doesn't get huge over time as all of the jar references are not included in the bundle jar.

However, now we have the ability to remotely restart the application using OSGI to do it within the same JVM.  However when the restart occurs, the class loader we added never gets garbage collected.  So if you restart the application like 10 times then it will blow the Perm Gen out of memory(Java 1.7).

We have tried to mimic what apache WebAppClassLoader does on unload but this didn't remove the references either.

I have scoured the internet for solutions to this and granted we are coding outside the typical OSGI implementation however is there not a way to clear the references to the ClassLoader.  After restart there honestly shouldn't be any references.

We have used MAT to analyze the heap dump but the referenced list of classes is always different.

Anyone know of a way to load external libraries a better way for use within OSGI?

Thanks for any information!

答: Use Java 8, there is no permanent generation in version 8.</p>


问:
Mathematica: what is symbolic programming?
I am a big fan of Stephen Wolfram, but he is definitely one not shy of tooting his own horn.  In many references, he extols Mathematica as a different symbolic programming paradigm.  I am not a Mathematica user.

My questions are: what is this symbolic programming? And how does it compare to functional languages (such as Haskell)?

答:
When I hear the phrase "symbolic programming", LISP, Prolog and (yes) Mathematica immediately leap to mind.  I would characterize a symbolic programming environment as one in which the expressions used to represent program text also happen to be the primary data structure.  As a result, it becomes very easy to build abstractions upon abstractions since data can easily be transformed into code and vice versa.

Mathematica exploits this capability heavily.  Even more heavily than LISP and Prolog (IMHO).

As an example of symbolic programming, consider the following sequence of events.  I have a CSV file that looks like this:

```<code>r,1,2
g,3,4
</code>```

I read that file in:

```<code>Import["somefile.csv"]
--> {{r,1,2},{g,3,4}}
</code>```

Is the result data or code?  It is both.  It is the data that results from reading the file, but it also happens to be the expression that will construct that data.  As code goes, however, this expression is inert since the result of evaluating it is simply itself.

So now I apply a transformation to the result:

```<code>% /. {c_, x_, y_} :> {c, Disk[{x, y}]}
--> {{r,Disk[{1,2}]},{g,Disk[{3,4}]}}
</code>```

Without dwelling on the details, all that has happened is that Disk[{...}] has been wrapped around the last two numbers from each input line.  The result is still data/code, but still inert.  Another transformation:

```<code>% /. {"r" -> Red, "g" -> Green}
--> {{Red,Disk[{1,2}]},{Green,Disk[{3,4}]}}
</code>```

Yes, still inert.  However, by a remarkable coincidence this last result just happens to be a list of valid directives in Mathematica's built-in domain-specific language for graphics.  One last transformation, and things start to happen:

```<code>% /. x_ :> Graphics[x]
--> Graphics[{{Red,Disk[{1,2}]},{Green,Disk[{3,4}]}}]
</code>```

Actually, you would not see that last result.  In an epic display of syntactic sugar, Mathematica would show this picture of red and green circles:

But the fun doesn't stop there.  Underneath all that syntactic sugar we still have a symbolic expression.  I can apply another transformation rule:

```<code>% /. Red -> Black
</code>```

Presto!  The red circle became black.

It is this kind of "symbol pushing" that characterizes symbolic programming.  A great majority of Mathematica programming is of this nature.

Functional vs. Symbolic

I won't address the differences between symbolic and functional programming in detail, but I will contribute a few remarks.

One could view symbolic programming as an answer to the question: "What would happen if I tried to model everything using only expression transformations?"  Functional programming, by contrast, can been seen as an answer to: "What would happen if I tried to model everything using only functions?"  Just like symbolic programming, functional programming makes it easy to quickly build up layers of abstractions.  The example I gave here could be easily be reproduced in, say, Haskell using a functional reactive animation approach.  Functional programming is all about function composition, higher level functions, combinators -- all the nifty things that you can do with functions.

Mathematica is clearly optimized for symbolic programming.  It is possible to write code in functional style, but the functional features in Mathematica are really just a thin veneer over transformations (and a leaky abstraction at that, see the footnote below).

Haskell is clearly optimized for functional programming.  It is possible to write code in symbolic style, but I would quibble that the syntactic representation of programs and data are quite distinct, making the experience suboptimal.

Concluding Remarks

In conclusion, I advocate that there is a distinction between functional programming (as epitomized by Haskell) and symbolic programming (as epitomized by Mathematica).  I think that if one studies both, then one will learn substantially more than studying just one -- the ultimate test of distinctness.

Leaky Functional Abstraction in Mathematica?

Yup, leaky.  Try this, for example:

```<code>f[x_] := g[Function[a, x]];
g[fn_] := Module[{h}, h[a_] := fn[a]; h[0]];
f[999]
</code>```

Duly reported to, and acknowledged by, WRI.  The response: avoid the use of Function[var, body] (Function[body] is okay).

Body:
When I hear the phrase "symbolic programming", LISP, Prolog and (yes) Mathematica immediately leap to mind.  I would characterize a symbolic programming environment as one in which the expressions used to represent program text also happen to be the primary data structure.  As a result, it becomes very easy to build abstractions upon abstractions since data can easily be transformed into code and vice versa.

Mathematica exploits this capability heavily.  Even more heavily than LISP and Prolog (IMHO).

As an example of symbolic programming, consider the following sequence of events.  I have a CSV file that looks like this:

r,1,2
g,3,4

I read that file in:

Import["somefile.csv"]
--> {{r,1,2},{g,3,4}}

Is the result data or code?  It is both.  It is the data that results from reading the file, but it also happens to be the expression that will construct that data.  As code goes, however, this expression is inert since the result of evaluating it is simply itself.

So now I apply a transformation to the result:

% /. {c_, x_, y_} :> {c, Disk[{x, y}]}
--> {{r,Disk[{1,2}]},{g,Disk[{3,4}]}}

Without dwelling on the details, all that has happened is that Disk[{...}] has been wrapped around the last two numbers from each input line.  The result is still data/code, but still inert.  Another transformation:

% /. {"r" -> Red, "g" -> Green}
--> {{Red,Disk[{1,2}]},{Green,Disk[{3,4}]}}

Yes, still inert.  However, by a remarkable coincidence this last result just happens to be a list of valid directives in Mathematica's built-in domain-specific language for graphics.  One last transformation, and things start to happen:

% /. x_ :> Graphics[x]
--> Graphics[{{Red,Disk[{1,2}]},{Green,Disk[{3,4}]}}]

Actually, you would not see that last result.  In an epic display of syntactic sugar, Mathematica would show this picture of red and green circles:

But the fun doesn't stop there.  Underneath all that syntactic sugar we still have a symbolic expression.  I can apply another transformation rule:

% /. Red -> Black

Presto!  The red circle became black.

It is this kind of "symbol pushing" that characterizes symbolic programming.  A great majority of Mathematica programming is of this nature.

Functional vs. Symbolic

I won't address the differences between symbolic and functional programming in detail, but I will contribute a few remarks.

One could view symbolic programming as an answer to the question: "What would happen if I tried to model everything using only expression transformations?"  Functional programming, by contrast, can been seen as an answer to: "What would happen if I tried to model everything using only functions?"  Just like symbolic programming, functional programming makes it easy to quickly build up layers of abstractions.  The example I gave here could be easily be reproduced in, say, Haskell using a functional reactive animation approach.  Functional programming is all about function composition, higher level functions, combinators -- all the nifty things that you can do with functions.

Mathematica is clearly optimized for symbolic programming.  It is possible to write code in functional style, but the functional features in Mathematica are really just a thin veneer over transformations (and a leaky abstraction at that, see the footnote below).

Haskell is clearly optimized for functional programming.  It is possible to write code in symbolic style, but I would quibble that the syntactic representation of programs and data are quite distinct, making the experience suboptimal.

Concluding Remarks

In conclusion, I advocate that there is a distinction between functional programming (as epitomized by Haskell) and symbolic programming (as epitomized by Mathematica).  I think that if one studies both, then one will learn substantially more than studying just one -- the ultimate test of distinctness.

Leaky Functional Abstraction in Mathematica?

Yup, leaky.  Try this, for example:

f[x_] := g[Function[a, x]];
g[fn_] := Module[{h}, h[a_] := fn[a]; h[0]];
f[999]

Duly reported to, and acknowledged by, WRI.  The response: avoid the use of Function[var, body] (Function[body] is okay).


问:
Angular 2 AOT build error (module not found)
I'm trying to build an Angular 2 project for production, but the following error occurs (full output)

```<code>$ ng build --prod
Hash: 1d8a022611a079fc4d52                                                         Time: 15057ms
chunk    {0} polyfills.6a841d7989dfdd57acf1.bundle.js (polyfills) 249 kB {5} [initial] [rendered]
chunk    {1} styles.872c1a24be4bf9c1223c.bundle.css (styles) 546 bytes {5} [initial] [rendered]
chunk    {2} scripts.938daa6986147a5346c9.bundle.js (scripts) 723 kB {5} [initial] [rendered]
chunk    {3} main.353b80e799563ca86907.bundle.js (main) 2.59 kB {4} [initial] [rendered]
chunk    {4} vendor.da282f8d8f035631cde9.bundle.js (vendor) 875 kB [initial] [rendered]
chunk    {5} inline.40400ad5f16398e09e79.bundle.js (inline) 0 bytes [entry] [rendered]

ERROR in ./src/main.ts
Module not found: Error: Can't resolve './$$_gendir/app/app.module.ngfactory' in '<project-root>/src'
 @ ./src/main.ts 17:0-74
 @ multi ./src/main.ts
</code>```

I have fixed all issues from ng lint that are not just style issues. I know that I need to export functions instead of "const lambda" and the other usual AoT things, but I can't find any issues and the error gives no hint of where to look. I have tried with --verbose which didn't produce any useful information.

I have read all GitHub issues and SO questions I could find, but none has helped.

EDIT: It seems that it could have to do with using absolute paths in combination with bareUrl typescripts compiler options.

答: Eventually this came down to two tsconfig.json issues. First I was mistakenly including some mock files that there used for tests only. Second I was including typings.d.ts in the include section of tsconfig.json which also broke the build.

Body:
I'm trying to build an Angular 2 project for production, but the following error occurs (full output)

$ ng build --prod
Hash: 1d8a022611a079fc4d52                                                         Time: 15057ms
chunk    {0} polyfills.6a841d7989dfdd57acf1.bundle.js (polyfills) 249 kB {5} [initial] [rendered]
chunk    {1} styles.872c1a24be4bf9c1223c.bundle.css (styles) 546 bytes {5} [initial] [rendered]
chunk    {2} scripts.938daa6986147a5346c9.bundle.js (scripts) 723 kB {5} [initial] [rendered]
chunk    {3} main.353b80e799563ca86907.bundle.js (main) 2.59 kB {4} [initial] [rendered]
chunk    {4} vendor.da282f8d8f035631cde9.bundle.js (vendor) 875 kB [initial] [rendered]
chunk    {5} inline.40400ad5f16398e09e79.bundle.js (inline) 0 bytes [entry] [rendered]

ERROR in ./src/main.ts
Module not found: Error: Can't resolve './$$_gendir/app/app.module.ngfactory' in '<project-root>/src'
 @ ./src/main.ts 17:0-74
 @ multi ./src/main.ts

I have fixed all issues from ng lint that are not just style issues. I know that I need to export functions instead of "const lambda" and the other usual AoT things, but I can't find any issues and the error gives no hint of where to look. I have tried with --verbose which didn't produce any useful information.

I have read all GitHub issues and SO questions I could find, but none has helped.

EDIT: It seems that it could have to do with using absolute paths in combination with bareUrl typescripts compiler options.


问:
Writing to locals() works in contrast to documentation saying its not
I am currently tinkering with the variable scopes and how they can be modified / copied, as I would like to postprocess some results dynamically in IPython.
The confusion about locals(), vars() and globals() is real for me right now.
Especially because the output of this piece of code:

```<code>Python 3.6.1 (v3.6.1:69c0db5050, Mar 21 2017, 01:21:04)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> locals()["test"] = 5
>>> print(test)
5
</code>```

According to the more than brief documentation this should not be possible in my understanding:

Note, the locals dictionary is only useful for reads since updates to
  the locals dictionary are ignored.

(which is for whatever reason stated in the description of the vars() function)

I hope someone can enlight me :)

答:
Where are you reading this? Both Py 2 docs and Py 3 docs have the following disclaimer:

Note: The contents of this dictionary should not be modified; changes may not affect the values of local and free variables used by the interpreter.

This shows exactly what this is: an implementation detail. Sure, it works in CPython, but it might not  work in the various other interpreters, like IronPython and Jython. It's what would be called a hack.

Do not rely on it updating any variables. Do not even try to do it for anything serious, as it causes undefined behaviour.

In CPython 3.6.0, help(locals) has the following note:

NOTE: Whether or not updates to this dictionary will affect name lookups in
the local scope and vice-versa is *implementation dependent* and not
covered by any backwards compatibility guarantees.
```

CPython 2.7.13 has no such note, however.

Body:
I am currently tinkering with the variable scopes and how they can be modified / copied, as I would like to postprocess some results dynamically in IPython.
The confusion about locals(), vars() and globals() is real for me right now.
Especially because the output of this piece of code:

Python 3.6.1 (v3.6.1:69c0db5050, Mar 21 2017, 01:21:04)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> locals()["test"] = 5
>>> print(test)
5

According to the more than brief documentation this should not be possible in my understanding:

Note, the locals dictionary is only useful for reads since updates to
  the locals dictionary are ignored.

(which is for whatever reason stated in the description of the vars() function)

I hope someone can enlight me :)

Body:
Where are you reading this? Both Py 2 docs and Py 3 docs have the following disclaimer:

Note: The contents of this dictionary should not be modified; changes may not affect the values of local and free variables used by the interpreter.

This shows exactly what this is: an implementation detail. Sure, it works in CPython, but it might not  work in the various other interpreters, like IronPython and Jython. It's what would be called a hack.

Do not rely on it updating any variables. Do not even try to do it for anything serious, as it causes undefined behaviour.

In CPython 3.6.0, help(locals) has the following note:

NOTE: Whether or not updates to this dictionary will affect name lookups in
the local scope and vice-versa is *implementation dependent* and not
covered by any backwards compatibility guarantees.

CPython 2.7.13 has no such note, however.


问:
Extend 'Component'; Uncaught TypeError: Super expression must either be null or a function, not object
I am trying to extend React Component for that thing I dislike doing over and over again, the this.onInputChange = this.onInputChange.bind(this); requirement. So far I have tried:

MyComponent.js-

```<code>import React, { Component } from 'react';

// function bindReactMethod(this_value, method_name) {
//     // Bind all of your custom methods, like:
//     //   this.onInputChange = this.onInputChange.bind(this);
//     this_value[method_name] = this_value[method_name].bind(this_value)
// }

// https://stackoverflow.com/questions/15192722/javascript-extending-class
class MyComponent extends Component {

    constructor(props) {
        super(props);
        this.bindReactMethods = this.bindReactMethods.bind(this)
    }

    bindReactMethods(this_value, method_name) {
        // Bind all of your custom methods, like:
        //   this.onInputChange = this.onInputChange.bind(this);
        this_value[method_name] = this_value[method_name].bind(this_value)
    }
}
</code>```

SearchBar.js-

```<code>import React from 'react';
import MyComponent from '../utils/MyComponent';

export default class SearchBar extends MyComponent {

    constructor(props) {
        super(props);
        this.state = {term: ''};
        this.bindReactMethods(['onInputChange'])
    }

    onInputChange(event) {
        console.log(event.target.value);
        this.setState({term: event.target.value})
    }
</code>```

fails with

```<code>Uncaught TypeError: Super expression must either be null or a function, not object
</code>```

and

MyComponent.js-

```<code>import React, { Component } from 'react';

function bindReactMethod(this_value, method_name) {
    // Bind all of your custom methods, like:
    //   this.onInputChange = this.onInputChange.bind(this);
    this_value[method_name] = this_value[method_name].bind(this_value)
}

// https://stackoverflow.com/questions/15192722/javascript-extending-class
class MyComponent extends Component {

    constructor(props, custom_methods=[]) {
        super(props);
        try {
            custom_methods.map((method_name) => {
                bindReactMethod(this, method_name)
            });
        }
        catch (error) { } // ignore error because that means the user didnt have custom methods to bind
    }
}
</code>```

SearchBar.js-

```<code>import React from 'react';
import MyComponent from '../utils/MyComponent';

export default class SearchBar extends MyComponent {

    constructor(props) {
        super(props, ['onInputChange']);
        this.state = {term: ''};
    }

    onInputChange(event) {
        console.log(event.target.value);
        this.setState({term: event.target.value})
    }
</code>```

also fails on

```<code>Uncaught TypeError: Super expression must either be null or a function, not object
</code>```

I would like to extend Component and always use my component, with this bindReactMethods callback being optional.

答:
In ReactJS you should be using Composition instead of Inheritance.

React has a powerful composition model, and we recommend using composition instead of inheritance to reuse code between components. Link to docs

Body:
I am trying to extend React Component for that thing I dislike doing over and over again, the this.onInputChange = this.onInputChange.bind(this); requirement. So far I have tried:

MyComponent.js-

import React, { Component } from 'react';

// function bindReactMethod(this_value, method_name) {
//     // Bind all of your custom methods, like:
//     //   this.onInputChange = this.onInputChange.bind(this);
//     this_value[method_name] = this_value[method_name].bind(this_value)
// }

// https://stackoverflow.com/questions/15192722/javascript-extending-class
class MyComponent extends Component {

    constructor(props) {
        super(props);
        this.bindReactMethods = this.bindReactMethods.bind(this)
    }

    bindReactMethods(this_value, method_name) {
        // Bind all of your custom methods, like:
        //   this.onInputChange = this.onInputChange.bind(this);
        this_value[method_name] = this_value[method_name].bind(this_value)
    }
}

SearchBar.js-

import React from 'react';
import MyComponent from '../utils/MyComponent';

export default class SearchBar extends MyComponent {

    constructor(props) {
        super(props);
        this.state = {term: ''};
        this.bindReactMethods(['onInputChange'])
    }

    onInputChange(event) {
        console.log(event.target.value);
        this.setState({term: event.target.value})
    }

fails with

Uncaught TypeError: Super expression must either be null or a function, not object

and

MyComponent.js-

import React, { Component } from 'react';

function bindReactMethod(this_value, method_name) {
    // Bind all of your custom methods, like:
    //   this.onInputChange = this.onInputChange.bind(this);
    this_value[method_name] = this_value[method_name].bind(this_value)
}

// https://stackoverflow.com/questions/15192722/javascript-extending-class
class MyComponent extends Component {

    constructor(props, custom_methods=[]) {
        super(props);
        try {
            custom_methods.map((method_name) => {
                bindReactMethod(this, method_name)
            });
        }
        catch (error) { } // ignore error because that means the user didnt have custom methods to bind
    }
}

SearchBar.js-

import React from 'react';
import MyComponent from '../utils/MyComponent';

export default class SearchBar extends MyComponent {

    constructor(props) {
        super(props, ['onInputChange']);
        this.state = {term: ''};
    }

    onInputChange(event) {
        console.log(event.target.value);
        this.setState({term: event.target.value})
    }

also fails on

Uncaught TypeError: Super expression must either be null or a function, not object

I would like to extend Component and always use my component, with this bindReactMethods callback being optional.


问:
String parametern in URL on server side gets wrong decoding
When I am trying to send URL to server, it's look like:
http://192.168.0.80:8080/directory/getCertainServices/1/Кузовные работы

But on the server side "Кузовные работы" parameter looks like:

```<code>ÐÑÐ·Ð¾Ð²Ð½ÑÐµ ÑÐ°Ð±Ð¾ÑÑ
</code>```

I am using RestTemplate from spring framework to send data from client:

```<code>@Override
        protected Service[] doInBackground(Object... voids) {
            restTemplate = new RestTemplate();
            restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
            return restTemplate.getForObject(customURL, Service[].class);
        }
</code>```

Server side code:

```<code> @RequestMapping(value = "/getCertainServices/{autoServiceId}/{serviceCategory}", method = RequestMethod.GET)
    @ResponseBody
    public List<Object> getService(@PathVariable("autoServiceId") Long autoServiceId, @PathVariable("serviceCategory") String serviceCategory){
        return dataBaseServiceService.findByAutoServiceAndCategory(autoServiceId, serviceCategory);
    }
</code>```

Can anyone give an advice what's the problem here ?

UPDATE QUESTION:
Does this mean that I have to use only english words in URL path ?

答:
Tomcat Wiki has a good page called "Character Encoding Issues" that describes the problem pretty well.

The solution depends on the actual web server being used, but if it's Tomcat (default for Spring), the solution is on that wiki page:

How do I change how GET parameters are interpreted?

Tomcat will use ISO-8859-1 as the default character encoding of the entire URL, including the query string ("GET parameters") (though see Tomcat 8 notice below).

There are two ways to specify how GET parameters are interpreted:

Set the URIEncoding attribute on the  element in server.xml to something specific (e.g. URIEncoding="UTF-8").

Set the useBodyEncodingForURI attribute on the  element in server.xml to true. This will cause the Connector to use the request body's encoding for GET parameters.

In Tomcat 8 starting with 8.0.0 (8.0.0-RC3, to be specific), the default value of URIEncoding attribute on the  element depends on "strict servlet compliance" setting. The default value (strict compliance is off) of URIEncoding is now UTF-8. If "strict servlet compliance" is enabled, the default value is ISO-8859-1.

Body:
When I am trying to send URL to server, it's look like:
http://192.168.0.80:8080/directory/getCertainServices/1/Кузовные работы

But on the server side "Кузовные работы" parameter looks like:

ÐÑÐ·Ð¾Ð²Ð½ÑÐµ ÑÐ°Ð±Ð¾ÑÑ

I am using RestTemplate from spring framework to send data from client:

@Override
        protected Service[] doInBackground(Object... voids) {
            restTemplate = new RestTemplate();
            restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
            return restTemplate.getForObject(customURL, Service[].class);
        }

Server side code:

 @RequestMapping(value = "/getCertainServices/{autoServiceId}/{serviceCategory}", method = RequestMethod.GET)
    @ResponseBody
    public List<Object> getService(@PathVariable("autoServiceId") Long autoServiceId, @PathVariable("serviceCategory") String serviceCategory){
        return dataBaseServiceService.findByAutoServiceAndCategory(autoServiceId, serviceCategory);
    }

Can anyone give an advice what's the problem here ?

UPDATE QUESTION:
Does this mean that I have to use only english words in URL path ?


问:
Java Strings: "String s = new String("silly");"
I'm a C++ guy learning Java. I'm reading Effective Java and something confused me. It says never to write code like this:

```<code>String s = new String("silly");
</code>```

Because it creates unnecessary String objects. But instead it should be written like this:

```<code>String s = "No longer silly";
</code>```

Ok fine so far...However, given this class:

```<code>public final class CaseInsensitiveString {
    private String s;
    public CaseInsensitiveString(String s) {
        if (s == null) {
            throw new NullPointerException();
        }
        this.s = s;
    }
    :
    :
}

CaseInsensitiveString cis = new CaseInsensitiveString("Polish");
String s = "polish";
</code>```

Why is the first statement ok? Shouldn't it be

CaseInsensitiveString cis = "Polish";

How do I make CaseInsensitiveString behave like String so the above statement is OK (with and without extending String)? What is it about String that makes it OK to just be able to pass it a literal like that? From my understanding there is no "copy constructor" concept in Java?

答: CaseInsensitiveString is not a String although it contains a String. A String literal e.g "example" can be only assigned to a String.

OwnerDisplayName: JavaNewbie

Body:
I'm a C++ guy learning Java. I'm reading Effective Java and something confused me. It says never to write code like this:

String s = new String("silly");

Because it creates unnecessary String objects. But instead it should be written like this:

String s = "No longer silly";

Ok fine so far...However, given this class:

public final class CaseInsensitiveString {
    private String s;
    public CaseInsensitiveString(String s) {
        if (s == null) {
            throw new NullPointerException();
        }
        this.s = s;
    }
    :
    :
}

CaseInsensitiveString cis = new CaseInsensitiveString("Polish");
String s = "polish";

Why is the first statement ok? Shouldn't it be

CaseInsensitiveString cis = "Polish";

How do I make CaseInsensitiveString behave like String so the above statement is OK (with and without extending String)? What is it about String that makes it OK to just be able to pass it a literal like that? From my understanding there is no "copy constructor" concept in Java?


问:
Get the index of Item selected in ListView
I've been searching for about an hour already and couldn't find a best solution.
I am migrating from VB.NET to C# Forms and to C# WPF.
Never mind that...
so I use this code for C# forms and it works, but not in C# WPF

```<code> if (ListView1.SelectedItems.Count > 0)
            {
                for (lcount = 0; lcount <= ListView1.Items.Count - 1; lcount++)
                {
                    if (ListView1.Items[lcount].Selected == true)
                    {
                        var2 = lcount;
                        break;
                    }
                }
            }
</code>```

this is the way I want to get the index of the item clicked in listbox.
I have the error in .SELECTED

please help.

答:
It can return NULL. Also the SelectedIndexChanged event can be FIRED TWICE. And the first time, there nothing selected yet.

So the only safe way to find it is like this:

```<code>    private void lv1_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (lv1.FocusedItem == null) return;
        int p = lv1.FocusedItem.Index;
</code>```

... now int p has the correct value...

Body:
I've been searching for about an hour already and couldn't find a best solution.
I am migrating from VB.NET to C# Forms and to C# WPF.
Never mind that...
so I use this code for C# forms and it works, but not in C# WPF

 if (ListView1.SelectedItems.Count > 0)
            {
                for (lcount = 0; lcount <= ListView1.Items.Count - 1; lcount++)
                {
                    if (ListView1.Items[lcount].Selected == true)
                    {
                        var2 = lcount;
                        break;
                    }
                }
            }

this is the way I want to get the index of the item clicked in listbox.
I have the error in .SELECTED

please help.

Body:
It can return NULL. Also the SelectedIndexChanged event can be FIRED TWICE. And the first time, there nothing selected yet.

So the only safe way to find it is like this:

    private void lv1_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (lv1.FocusedItem == null) return;
        int p = lv1.FocusedItem.Index;

... now int p has the correct value...


问:
iOS Swift: How to recreate a Photos App UICollectionView Layout
I am wondering for quiet a while now how to create the iOS Photos App layout. How can I make it so it looks like zooming in to a collection while at the same time the navigation bar shows a back button?

Is it a new view controller which gets pushed onto a UINavigationController? And if so, how exactly do they manage to match the tiles while expanding.

Is there maybe even a 3rd party library which lets me easily recreate such a layout?

Hope you can help me to understand the concept of how this works.

答:
To create a Photo Gallery, you can refer to : https://github.com/inspace-io/INSPhotoGallery.

It is a nice library for showing photos, zooming funcationality and many more.


问:
Convert Non-List Type to List Directly
I have a list of items that I need to actually be a list of lists. All the conversion methods I have seen convert the non-list items to lists of individual characters ["12", "cat", 87] to [['1', '2'], ['c', 'a', 't'], ['8', '7']] instead of [['12'], ['cat'], [87]]. The following works,

```<code>v_Data = ["12", "cat", 87]
for index, i in enumerate(v_Data):
    if type(i) != list:
        v_Data[index] = [i]
print(v_Data) ## [['12'], ['cat'], [87]]
</code>```

Is there a better way to do this?

Using Python 2.7

答:
You can use list-comprehension:

```<code>v_Data = ["12", "cat", 87]

[v if isinstance(v, list) else [v] for v in v_Data]
# [['12'], ['cat'], [87]]
</code>```

Title: Convert Non-List Type to List Directly

Body:
I have a list of items that I need to actually be a list of lists. All the conversion methods I have seen convert the non-list items to lists of individual characters ["12", "cat", 87] to [['1', '2'], ['c', 'a', 't'], ['8', '7']] instead of [['12'], ['cat'], [87]]. The following works,

v_Data = ["12", "cat", 87]
for index, i in enumerate(v_Data):
    if type(i) != list:
        v_Data[index] = [i]
print(v_Data) ## [['12'], ['cat'], [87]]

Is there a better way to do this?

Using Python 2.7

Body:
You can use list-comprehension:

v_Data = ["12", "cat", 87]

[v if isinstance(v, list) else [v] for v in v_Data]
# [['12'], ['cat'], [87]]


问:
Angular 2 Routing with parameter undefined
I'm trying to create a route in Angular 2 that takes me to data of a json file, depending on the id. For instance I have 10001.json, 10002.json, 10003.json, etc...

People should be able to get to their patientfile by typing in that particular id as an url, but so far that's not working. I'm actually getting :

GET http://localhost:4200/assets/backend/patienten/undefined.json 404 (Not Found)

This is my patientcomponent:

```<code>import { Component, OnInit } from '@angular/core';
import {PatientService} from "../patient.service";
import {Patient} from "../models";
import {ActivatedRoute, Params} from "@angular/router";
import 'rxjs/add/operator/switchMap';

@Component({
  selector: 'app-patient',
  templateUrl: './patient.component.html',
  styleUrls: ['./patient.component.sass']
})
export class PatientComponent implements OnInit {

  patient:Patient[];
  id:any;

  errorMessage:string;

  constructor(private patientService:PatientService, private route: ActivatedRoute) { }

  ngOnInit():void {
    this.getData();
    this.id = this.route.params['id'];
    this.patientService.getPatient(this.id)
      .subscribe(patient => this.patient = patient);

  }

  getData() {
    this.patientService.getPatient(this.id)
      .subscribe(
        data => {
          this.patient = data;
          console.log(this.patient);
        }, error => this.errorMessage = <any> error);

  }
}
</code>```

This is the routing, very basic:

```<code>import {Routes} from "@angular/router";
import {AfdelingComponent} from "./afdeling/afdeling.component";
import {PatientComponent} from "./patient/patient.component";

export const routes: Routes = [
  {path: '', component: AfdelingComponent},
  {path: 'patient/:id', component: PatientComponent}

];
</code>```

And the service:

```<code>import { Injectable } from '@angular/core';
import {Http, RequestOptions, Response, Headers} from '@angular/http';
import {Observable} from "rxjs";
import {Patient} from "./models";

@Injectable()
export class PatientService {
  private patientUrl = "/assets/backend/patienten/";
  constructor(private http: Http) { }

  getPatient(id:any): Observable<Patient[]>{
    return this.http.get(this.patientUrl + id + '.json' )
        .map(this.extractData)
        .catch(this.handleError);
  }

  private extractData(res: Response) {
    let body = res.json();
    return body || { };
  }

  private handleError(error: any): Promise<any> {
    console.error('An error occurred', error);
    return Promise.reject(error.message || error);
  }

  addPatient(afdelingsNaam: string, afdeling: any): Observable<Patient> {
    let body = JSON.stringify({"afdelingsNaam": afdelingsNaam, afdeling: afdeling});
    let headers = new Headers({'Content-Type': 'application/json'});
    let options = new RequestOptions({headers: headers});
    return this.http.post(this.patientUrl, body, options)
      .map(res => <Patient> res.json())
      .catch(this.handleError)
  }
}
</code>```

答:
You need to provide those files as static assets to your angular app, otherwise the angular router will try route those requests to your in-app routes, which wont have a matching route.

You can do this by editing the 'assets' value in your angular-cli.json, and specifying any files and folders you would like to have accessible via your routing. (and also copied by the angular cli to your dist folder during build.)

As an example, the following would copy and allow routing to the following:

src/assets/* (entire folder)

src/somefolder/* (entire folder)

src/favicon.ico

src/web.config

      "assets": [
        "assets",
        "somefolder",
        "favicon.ico",
        "web.config"
      ],

For more in depth examples, have a look at the Angular CLI wiki here: https://github.com/angular/angular-cli/wiki/stories-asset-configuration

Body:
I'm trying to create a route in Angular 2 that takes me to data of a json file, depending on the id. For instance I have 10001.json, 10002.json, 10003.json, etc...

People should be able to get to their patientfile by typing in that particular id as an url, but so far that's not working. I'm actually getting :

GET http://localhost:4200/assets/backend/patienten/undefined.json 404 (Not Found)

This is my patientcomponent:

import { Component, OnInit } from '@angular/core';
import {PatientService} from "../patient.service";
import {Patient} from "../models";
import {ActivatedRoute, Params} from "@angular/router";
import 'rxjs/add/operator/switchMap';

@Component({
  selector: 'app-patient',
  templateUrl: './patient.component.html',
  styleUrls: ['./patient.component.sass']
})
export class PatientComponent implements OnInit {

  patient:Patient[];
  id:any;

  errorMessage:string;

  constructor(private patientService:PatientService, private route: ActivatedRoute) { }

  ngOnInit():void {
    this.getData();
    this.id = this.route.params['id'];
    this.patientService.getPatient(this.id)
      .subscribe(patient => this.patient = patient);

  }

  getData() {
    this.patientService.getPatient(this.id)
      .subscribe(
        data => {
          this.patient = data;
          console.log(this.patient);
        }, error => this.errorMessage = <any> error);

  }
}

This is the routing, very basic:

import {Routes} from "@angular/router";
import {AfdelingComponent} from "./afdeling/afdeling.component";
import {PatientComponent} from "./patient/patient.component";

export const routes: Routes = [
  {path: '', component: AfdelingComponent},
  {path: 'patient/:id', component: PatientComponent}

];

And the service:

import { Injectable } from '@angular/core';
import {Http, RequestOptions, Response, Headers} from '@angular/http';
import {Observable} from "rxjs";
import {Patient} from "./models";

@Injectable()
export class PatientService {
  private patientUrl = "/assets/backend/patienten/";
  constructor(private http: Http) { }

  getPatient(id:any): Observable<Patient[]>{
    return this.http.get(this.patientUrl + id + '.json' )
        .map(this.extractData)
        .catch(this.handleError);
  }

  private extractData(res: Response) {
    let body = res.json();
    return body || { };
  }

  private handleError(error: any): Promise<any> {
    console.error('An error occurred', error);
    return Promise.reject(error.message || error);
  }

  addPatient(afdelingsNaam: string, afdeling: any): Observable<Patient> {
    let body = JSON.stringify({"afdelingsNaam": afdelingsNaam, afdeling: afdeling});
    let headers = new Headers({'Content-Type': 'application/json'});
    let options = new RequestOptions({headers: headers});
    return this.http.post(this.patientUrl, body, options)
      .map(res => <Patient> res.json())
      .catch(this.handleError)
  }
}


问:
Make Multiple Copies From Original with image = MiniMagick
I need to generate several copies of an image in different formats/sizes. Can I do it without re-opening the source for each format/size?

Take this example:

```<code># Original image is jpeg
image = MiniMagick::Image.open url
image.crop dimensions
image.format 'pdf'
upload image
# image = MiniMagick::Image.open url # No! Needless network traffic and processing.
image.format 'png'
image.resize new_size
upload image
</code>```

This code is no good without the second #open because when image.format 'png' is called the image is a PDF, so I would end up rasterizing it, which is not what I want to do.

There's a method #clone, but it does not make a clone of the image object. Rather it sets a parameter for the converter. I can't figure out if this will somehow suit my purpose.

答:
I found one way to do it, which seems fine.

```<code># Original image is jpeg
image = MiniMagick::Image.open url
image.crop dimensions

new_image = MiniMagick::Image.open image.tempfile.path

image.format 'pdf'
upload image

new_image.format 'png'
new_image.resize new_size
upload new_image
</code>```

Both the PDF and PNG will be cropped but each will only be converted once.

Body:
I need to generate several copies of an image in different formats/sizes. Can I do it without re-opening the source for each format/size?

Take this example:

# Original image is jpeg
image = MiniMagick::Image.open url
image.crop dimensions
image.format 'pdf'
upload image
# image = MiniMagick::Image.open url # No! Needless network traffic and processing.
image.format 'png'
image.resize new_size
upload image

This code is no good without the second #open because when image.format 'png' is called the image is a PDF, so I would end up rasterizing it, which is not what I want to do.

There's a method #clone, but it does not make a clone of the image object. Rather it sets a parameter for the converter. I can't figure out if this will somehow suit my purpose.

Body:
I found one way to do it, which seems fine.

# Original image is jpeg
image = MiniMagick::Image.open url
image.crop dimensions

new_image = MiniMagick::Image.open image.tempfile.path

image.format 'pdf'
upload image

new_image.format 'png'
new_image.resize new_size
upload new_image

Both the PDF and PNG will be cropped but each will only be converted once.


问:
Fixed positioned element scrolls with page until the scrolling is complete in Firefox mobile
I have an element, which CSS is position: fixed.

It works fine on PC browsers, but it works badly on mobile browsers (especially Firefox)

The problem is that the fixed positioned element scrolls with the page and then awkwardly snap back into position once scrolling is complete.

Here's the demonstration: (Notice the “Top” block at the bottom right corner, which is a fixed positioned element)

http://imgur.com/a/94A3v

How to solve this problem?

答:
For mobile browsers, "fixed" is discussed at length here:
http://bradfrost.com/blog/mobile/fixed-position/

You could use jQuery Mobile, as discussed here:
http://demos.jquerymobile.com/1.2.1/docs/toolbars/bars-fixed.html

You'd end up with something like

```<code><div data-role="header" data-position="fixed">
  <h1>Fixed Header!</h1>
</div>
</code>```

Body:
For mobile browsers, "fixed" is discussed at length here:
http://bradfrost.com/blog/mobile/fixed-position/

You could use jQuery Mobile, as discussed here:
http://demos.jquerymobile.com/1.2.1/docs/toolbars/bars-fixed.html

You'd end up with something like

<div data-role="header" data-position="fixed">
  <h1>Fixed Header!</h1>
</div>